问:
Sending data through serial using jQuery slider
This is my first question on stack overflow so I'd like to say hello to everyone. My question today is as follows...

I am trying to use a jQuery UI slider to send values over TCP/IP to Arduino's serial port.

I have the communication part pretty much done (TCP and serial). The problem is that whenever the user moves the slider, every value along the way is sent one after another very rapidly. I'd like to delay the slider so that it sends those values with a 100ms delay between every step.

I've tried to use 'setInterval' and 'clearInterval' with no success.  Here is the code:

```<code>$(document).ready(function() {

    $( "#mySlider" ).slider({
        range: "min",
        min: 0,
        max: 180,
        value: 90,
        slide: function( event, ui ) {

        delayPan(ui.value);

        }
});

$( "#total" ).val( $( "#mySlider" ).slider( "value" ) );

});

var timeOut;

function delayPan(vals) {

    $( "#total" ).val("$" +  vals );

    //the part below sends values to another PHP file in order to then send it using TCP/IP

    timeOut = setInterval(function()
    {

        $.get("insert_commands.php", {command: 39, parameter: 0, value: vals, number: 0},
        function(command,parameter,value,number){}, "json");

    }, 100);

    clearInterval(timeOut);

}
</code>```

And for more clarity, here is the slider's HTML on my index.php website:

```<code><label for="total">ANGLE:</label>
<input type="text" id="total" style="border:0; color:#fa4b2a; font-weight:bold;">
</p>
<div id="mySlider"></div>
</code>```

I am not sure how to go about solving this- I am pretty new to javascript/jQuery. I could just delay the reception on Arduino or TCP socket but there are other buttons on the main website with different delays set so I need to do it in jQuery if possible.

I'd appreciate any advice.

Thank you
Rob

答:
Congratulations on a well-written question.

I think what you're looking at is a Debounced or Throttled function (depending on how many times you want to send the new value). In your case, you want to "throttle" the function- that means, limit the frequency at which it's called.

So we could throttle the position-sending function at every 100ms. That way, even if the slider position is changed 25 times in 100 ms, the AJAX request will only be sent one time in that 100ms.

Lodash and Underscore both give you possibilities for Debouncing and Throttling a function. Ben Alman also offers a tiny library (no longer maintained) for Debouncing/Throttling. I can only speak for Ben Alman's library, because that's the only one I've used.

I've created a Codepen to demonstrate. Click to see it in action.
Here's the relevant code:

```<code>$(document).ready(function() {

  function delayPan(vals) {

    $( "#total" ).val("$" +  vals );

    //the part below sends values to another PHP file in order to then send it using TCP/IP
    $.get("insert_commands.php", {command: 39, parameter: 0, value: vals, number: 0}, function(command,parameter,value,number){}, "json");
 }

    const throttledDelayPan = $.throttle(1000, delayPan);

    $( "#mySlider" ).slider({
        range: "min",
        min: 0,
        max: 180,
        value: 90,
        slide: function( event, ui ) {
            throttledDelayPan(ui.value);
         }
    });

  $( "#total" ).val( $( "#mySlider" ).slider( "value" ) );

});
</code>```

Basically, you declare a function that sends the AJAX request. delayPan, in your example.

Then you pass it into the Throttle library's throttle function ($.throttle), along with a throttle time (1000ms in this case, to demonstrate the delay).

The throttle function returns you another function, which we store at throttledDelayPan.

Finally we call throttledDelayPan in the "slide" callback of the jQuery UI Slider.

As an aside, I have some recommendations:

I would dissuade you from using a GET request if you specifically want to send data to a REST API- it would be more idiomatic to use a POST request.

you may wish to separate this into two functions- the throttled function that sends the AJAX request, and the function that updates the "#total" display. That way, you could continuously update the display while still reducing the number of AJAX requests you are sending.

Body:
This is my first question on stack overflow so I'd like to say hello to everyone. My question today is as follows...

I am trying to use a jQuery UI slider to send values over TCP/IP to Arduino's serial port.

I have the communication part pretty much done (TCP and serial). The problem is that whenever the user moves the slider, every value along the way is sent one after another very rapidly. I'd like to delay the slider so that it sends those values with a 100ms delay between every step.

I've tried to use 'setInterval' and 'clearInterval' with no success.  Here is the code:

$(document).ready(function() {

    $( "#mySlider" ).slider({
        range: "min",
        min: 0,
        max: 180,
        value: 90,
        slide: function( event, ui ) {

        delayPan(ui.value);

        }
});

$( "#total" ).val( $( "#mySlider" ).slider( "value" ) );

});

var timeOut;

function delayPan(vals) {

    $( "#total" ).val("$" +  vals );

    //the part below sends values to another PHP file in order to then send it using TCP/IP

    timeOut = setInterval(function()
    {

        $.get("insert_commands.php", {command: 39, parameter: 0, value: vals, number: 0},
        function(command,parameter,value,number){}, "json");

    }, 100);

    clearInterval(timeOut);

}

And for more clarity, here is the slider's HTML on my index.php website:

ANGLE:
<input type="text" id="total" style="border:0; color:#fa4b2a; font-weight:bold;">

I am not sure how to go about solving this- I am pretty new to javascript/jQuery. I could just delay the reception on Arduino or TCP socket but there are other buttons on the main website with different delays set so I need to do it in jQuery if possible.

I'd appreciate any advice.

Thank you
Rob

Body:
Congratulations on a well-written question.

I think what you're looking at is a Debounced or Throttled function (depending on how many times you want to send the new value). In your case, you want to "throttle" the function- that means, limit the frequency at which it's called.

So we could throttle the position-sending function at every 100ms. That way, even if the slider position is changed 25 times in 100 ms, the AJAX request will only be sent one time in that 100ms.

Lodash and Underscore both give you possibilities for Debouncing and Throttling a function. Ben Alman also offers a tiny library (no longer maintained) for Debouncing/Throttling. I can only speak for Ben Alman's library, because that's the only one I've used.

I've created a Codepen to demonstrate. Click to see it in action.
Here's the relevant code:

$(document).ready(function() {

  function delayPan(vals) {

    $( "#total" ).val("$" +  vals );

    //the part below sends values to another PHP file in order to then send it using TCP/IP
    $.get("insert_commands.php", {command: 39, parameter: 0, value: vals, number: 0}, function(command,parameter,value,number){}, "json");
 }

    const throttledDelayPan = $.throttle(1000, delayPan);

    $( "#mySlider" ).slider({
        range: "min",
        min: 0,
        max: 180,
        value: 90,
        slide: function( event, ui ) {
            throttledDelayPan(ui.value);
         }
    });

  $( "#total" ).val( $( "#mySlider" ).slider( "value" ) );

});

Basically, you declare a function that sends the AJAX request. delayPan, in your example.

Then you pass it into the Throttle library's throttle function ($.throttle), along with a throttle time (1000ms in this case, to demonstrate the delay).

The throttle function returns you another function, which we store at throttledDelayPan.

Finally we call throttledDelayPan in the "slide" callback of the jQuery UI Slider.

As an aside, I have some recommendations:

I would dissuade you from using a GET request if you specifically want to send data to a REST API- it would be more idiomatic to use a POST request.

you may wish to separate this into two functions- the throttled function that sends the AJAX request, and the function that updates the "#total" display. That way, you could continuously update the display while still reducing the number of AJAX requests you are sending.


来源: stackexchange

问:
Material UI : How to use my own image in avatar
I want to use an image in the avatar. But I am not able to get the desired result.

This is my project structure.

projectname -> packages -> portal -> public -> favicon-16x16.png

```<code>      <Avatar
        src="/public/favicon-16x16.png"
        className={classes.avatar}
      />
</code>```

```<code>         <Avatar
           src="packages/portal/public/favicon-16x16.png"
           className={classes.avatar}
         />
</code>```

I have tried the above two ways. But not load to get the image. Any help is appreciated. Thanks.

答:
This the correct way :

```<code><Avatar src={`${process.env.PUBLIC_URL}/apple-touch-icon.png`} className={classes.avatar} style={{ borderRadius: 0 }} />
</code>```

Thank you @RobB

ContentLicense: CC BY-SA 4.0

Body:
I want to use an image in the avatar. But I am not able to get the desired result.

This is my project structure.

projectname -> packages -> portal -> public -> favicon-16x16.png

      <Avatar
        src="/public/favicon-16x16.png"
        className={classes.avatar}
      />

         <Avatar
           src="packages/portal/public/favicon-16x16.png"
           className={classes.avatar}
         />

I have tried the above two ways. But not load to get the image. Any help is appreciated. Thanks.

Body:
This the correct way :

<Avatar src={`${process.env.PUBLIC_URL}/apple-touch-icon.png`} className={classes.avatar} style={{ borderRadius: 0 }} />

Thank you @RobB


问:
how to replace particular occurence of string with regex in javascript
here is the code,it's  for one single line string but it's not working for the multiline text.
i'm extracting data from xml file .

```<code>let xmlData = `<?xml version="1.0" encoding="utf-8"?>
    <RecipeData>
    <SUNDAY Value="1"/>
    <SUNDAY/>
    <SUNDAY/>
    <SUNDAY/>
    <MONDAY Value="1"/>
    </MONDAY>
    <MONDAY>
    </MONDAY>
    </RecipeData>`;
    search = '<SUNDAY/>'
    let n = 2
    console.log(xmlData.replace(RegExp("((<SUNDAY(\s*)\/(\s*)>)$\g){" + n + "}"), function(x){return x.replace(RegExp("((<SUNDAY(\s*)\/(\s*)>)$\g)" + "$"), "HHHH")}))
</code>```

Expected output :

We are replacing the second occurance of the

```<code>`<SUNDAY with HHHH.`
</code>```

So the output will be :

```<code><?xml version="1.0" encoding="utf-8"?>
        <RecipeData>
        <SUNDAY Value="1"/>
        <HHHHH/>
        <SUNDAY/>
        <SUNDAY/>
        <MONDAY Value="1"/>
        </MONDAY>
        <MONDAY>
        </MONDAY>
        </RecipeData>;
</code>```

答:
One option is using a DOMParser and for example count the occurrences where nodeName equals SUNDAY.

If there is a match, replace the node with a new node through the parentNode.

let xmlData = `<?xml version="1.0" encoding="utf-8"?>
    <RecipeData>
    <SUNDAY Value="1"/>
    <SUNDAY/>
    <SUNDAY/>
    <SUNDAY/>
    <MONDAY Value="1">
    </MONDAY>
    <MONDAY>
    </MONDAY>
</RecipeData>`,
  search = 'SUNDAY',
  n = 2;

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlData, "text/xml");
let childNodes = xmlDoc.documentElement.childNodes;
let nrSundays = 0;

for (let i = 0; i < childNodes.length; i++) {
  if (childNodes[i].nodeName === search) {
    nrSundays++;
    if (nrSundays === n) {
      let childNode = childNodes[i];
      childNode.parentNode.replaceChild(xmlDoc.createElement('HHHHH'), childNode);
    }
  }
}

console.log(new XMLSerializer().serializeToString(xmlDoc.documentElement));```
</div>
</div>
</p>

<hr>

<p>Another option could be using xpath using evaluate</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let xmlData = `<?xml version="1.0" encoding="utf-8"?>
    <RecipeData>
    <SUNDAY Value="1"/>
    <SUNDAY/>
    <SUNDAY/>
    <SUNDAY/>
    <MONDAY Value="1">
    </MONDAY>
    <MONDAY>
    </MONDAY>
</RecipeData>`,
  search = 'SUNDAY',
  n = 2;

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlData, "text/xml");
let nodeSunday = xmlDoc.evaluate(`/RecipeData/${search}[${n}]`, xmlDoc.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
nodeSunday.singleNodeValue.parentNode.replaceChild(xmlDoc.createElement('HHHH'), nodeSunday.singleNodeValue);
console.log(new XMLSerializer().serializeToString(xmlDoc.documentElement));</code>```

Another

Body:
here is the code,it's  for one single line string but it's not working for the multiline text.
i'm extracting data from xml file .

let xmlData = `<?xml version="1.0" encoding="utf-8"?>
    <RecipeData>
    <SUNDAY Value="1"/>
    <SUNDAY/>
    <SUNDAY/>
    <SUNDAY/>
    <MONDAY Value="1"/>
    </MONDAY>
    <MONDAY>
    </MONDAY>
    </RecipeData>`;
    search = '<SUNDAY/>'
    let n = 2
    console.log(xmlData.replace(RegExp("((<SUNDAY(\s*)\/(\s*)>)$\g){" + n + "}"), function(x){return x.replace(RegExp("((<SUNDAY(\s*)\/(\s*)>)$\g)" + "$"), "HHHH")}))

Expected output :

We are replacing the second occurance of the

`<SUNDAY with HHHH.`

So the output will be :

<?xml version="1.0" encoding="utf-8"?>
        <RecipeData>
        <SUNDAY Value="1"/>
        <HHHHH/>
        <SUNDAY/>
        <SUNDAY/>
        <MONDAY Value="1"/>
        </MONDAY>
        <MONDAY>
        </MONDAY>
        </RecipeData>;

Body:
One option is using a DOMParser and for example count the occurrences where nodeName equals SUNDAY.

If there is a match, replace the node with a new node through the parentNode.

let xmlData = `<?xml version="1.0" encoding="utf-8"?>
    <RecipeData>
    <SUNDAY Value="1"/>
    <SUNDAY/>
    <SUNDAY/>
    <SUNDAY/>
    <MONDAY Value="1">
    </MONDAY>
    <MONDAY>
    </MONDAY>
</RecipeData>`,
  search = 'SUNDAY',
  n = 2;

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlData, "text/xml");
let childNodes = xmlDoc.documentElement.childNodes;
let nrSundays = 0;

for (let i = 0; i < childNodes.length; i++) {
  if (childNodes[i].nodeName === search) {
    nrSundays++;
    if (nrSundays === n) {
      let childNode = childNodes[i];
      childNode.parentNode.replaceChild(xmlDoc.createElement('HHHHH'), childNode);
    }
  }
}

console.log(new XMLSerializer().serializeToString(xmlDoc.documentElement));

Another option could be using xpath using evaluate

let xmlData = `<?xml version="1.0" encoding="utf-8"?>
    <RecipeData>
    <SUNDAY Value="1"/>
    <SUNDAY/>
    <SUNDAY/>
    <SUNDAY/>
    <MONDAY Value="1">
    </MONDAY>
    <MONDAY>
    </MONDAY>
</RecipeData>`,
  search = 'SUNDAY',
  n = 2;

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlData, "text/xml");
let nodeSunday = xmlDoc.evaluate(`/RecipeData/${search}[${n}]`, xmlDoc.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
nodeSunday.singleNodeValue.parentNode.replaceChild(xmlDoc.createElement('HHHH'), nodeSunday.singleNodeValue);
console.log(new XMLSerializer().serializeToString(xmlDoc.documentElement));

Another


问:
What is the difference between @ExtendWith(SpringExtension.class) and @ExtendWith(MockitoExtension.class)?
I was using @RunWith(MockitoJUnitRunner.class) for my junit test with mockito. But now I am working with spring-boot and JUnit 5.

What's the difference between the two annotations ?

Can I use only @ExtendWith(SpringExtension.class) to mock my objects ?

答:
When involving Spring:

If you want to use Spring test framework features in your tests like for example @MockBean, then you have to use @ExtendWith(SpringExtension.class). It replaces the deprecated JUnit4 @RunWith(SpringJUnit4ClassRunner.class)

When NOT involving Spring:

If you just want to involve Mockito and don't have to involve Spring, for example,  when you just want to use the @Mock / @InjectMocks annotations, then you want to use @ExtendWith(MockitoExtension.class), as it doesn't load in a bunch of unneeded Spring stuff. It replaces the deprecated JUnit4 @RunWith(MockitoJUnitRunner.class).

To answer your question:

Yes you can just use @ExtendWith(SpringExtension.class), but if you're not involving Spring test framework features in your tests, then you probably want to just use @ExtendWith(MockitoExtension.class).


问:
for loop keeps starting over
So I'm trying to make a code that gets every word in a list and adds the same word with the first letter in lowercase or uppercase (depending on the word)

here's the code

lost = ["de", "da", "do"] #The actual list is much bigger and with numbers but this list is small and has the same problem

for x in lost:
    if x[:1] == x[:1].lower():
        try:
            print x
            int(x[:1])
        except ValueError:
            print x
            lost.append(x[:1].upper() + x[1:])
    elif x[:1] == x[:1].upper():
        try:
            int(x[:1])
        except ValueError:
            lost.append(x[:1].lower() + x[1:])
```

<p>but after it did all the 3 words the for loop starts over again so the console looks like this:</p>

```de
de
da
da
do
do
de
de
da
da
do
do
....
```

why doesnt it stop after it has done those 3 words?

答: you are increasing the size of your list over and over again so you are cycling your initial list, again and again, to solve the issue you should store the "lost" values in a different list</p>

Title: for loop keeps starting over

Body:
So I'm trying to make a code that gets every word in a list and adds the same word with the first letter in lowercase or uppercase (depending on the word)

here's the code

lost = ["de", "da", "do"] #The actual list is much bigger and with numbers but this list is small and has the same problem

for x in lost:
    if x[:1] == x[:1].lower():
        try:
            print x
            int(x[:1])
        except ValueError:
            print x
            lost.append(x[:1].upper() + x[1:])
    elif x[:1] == x[:1].upper():
        try:
            int(x[:1])
        except ValueError:
            lost.append(x[:1].lower() + x[1:])

but after it did all the 3 words the for loop starts over again so the console looks like this:

de
de
da
da
do
do
de
de
da
da
do
do
....

why doesnt it stop after it has done those 3 words?


问:
How to get SUM of f3 but Grouped by f2
I want to get all comments count grouped by category. eg

```<code>f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43
</code>```

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

答:
```<code>SELECT SUM(f3) FROM `tablename` GROUP BY f2, f3
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get SUM of f3 but Grouped by f2

Body:
I want to get all comments count grouped by category. eg

f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique


问:
Instantly detect client disconnection from server socket
How can I detect that a client has disconnected from my server?

I have the following code in my AcceptCallBack method

```<code>static Socket handler = null;
public static void AcceptCallback(IAsyncResult ar)
{
  //Accept incoming connection
  Socket listener = (Socket)ar.AsyncState;
  handler = listener.EndAccept(ar);
}
</code>```

I need to find a way to discover as soon as possible that the client has disconnected from the handler Socket.

I've tried:

handler.Available;

handler.Send(new byte[1], 0,
SocketFlags.None);

handler.Receive(new byte[1], 0,
SocketFlags.None);

The above approaches work when you are connecting to a server and want to detect when the server disconnects but they do not work when you are the server and want to detect client disconnection.

Any help will be appreciated.

答:
This is in VB, but it seems to work well for me.  It looks for a 0 byte return like the previous post.</p>

```<code>Private Sub RecData(ByVal AR As IAsyncResult)
    Dim Socket As Socket = AR.AsyncState

    If Socket.Connected = False And Socket.Available = False Then
        Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
        Exit Sub
    End If
    Dim BytesRead As Int32 = Socket.EndReceive(AR)
    If BytesRead = 0 Then
        Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
        UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
        Socket.Close()
        Exit Sub
    End If
    Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
    Erase ByteData
    ReDim ByteData(1024)
    ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
    UpdateText(msg)
End Sub
</code>```

OwnerDisplayName: Smart Alec

ContentLicense: CC BY-SA 2.5

Body:
How can I detect that a client has disconnected from my server?

I have the following code in my AcceptCallBack method

static Socket handler = null;
public static void AcceptCallback(IAsyncResult ar)
{
  //Accept incoming connection
  Socket listener = (Socket)ar.AsyncState;
  handler = listener.EndAccept(ar);
}

I need to find a way to discover as soon as possible that the client has disconnected from the handler Socket.

I've tried:

handler.Available;

handler.Send(new byte[1], 0,
SocketFlags.None);

handler.Receive(new byte[1], 0,
SocketFlags.None);

The above approaches work when you are connecting to a server and want to detect when the server disconnects but they do not work when you are the server and want to detect client disconnection.

Any help will be appreciated.

Body:
This is in VB, but it seems to work well for me.  It looks for a 0 byte return like the previous post.

Private Sub RecData(ByVal AR As IAsyncResult)
    Dim Socket As Socket = AR.AsyncState

    If Socket.Connected = False And Socket.Available = False Then
        Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
        Exit Sub
    End If
    Dim BytesRead As Int32 = Socket.EndReceive(AR)
    If BytesRead = 0 Then
        Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
        UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
        Socket.Close()
        Exit Sub
    End If
    Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
    Erase ByteData
    ReDim ByteData(1024)
    ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
    UpdateText(msg)
End Sub


问:
Divide every element in 2 dimensional array
I have the sums of x and y coordinates and I need to calculate the mean

```<code>float [][] sums = new float[n][2];
</code>```

e.g. my array consists of:

```<code>
{ [ 8,6 ],
  [ 4,2 ] }
</code>```

After the dividing to 2:

```<code>
{ [ 4,3 ],
  [ 2,1 ] }
</code>```

I can do this with loops but I wonder if It is possible to do it with 1 function.

答:
Something like this:

```<code>Arrays.stream(sums).map(y -> Arrays.stream(y).map(x -> x/2).toArray(Double[]::new))
.toArray(Double[][]::new);
</code>```

probably should do what you want.

Body:
I have the sums of x and y coordinates and I need to calculate the mean

float [][] sums = new float[n][2];

e.g. my array consists of:

{ [ 8,6 ],
  [ 4,2 ] }

After the dividing to 2:

{ [ 4,3 ],
  [ 2,1 ] }

I can do this with loops but I wonder if It is possible to do it with 1 function.

Body:
Something like this:

Arrays.stream(sums).map(y -> Arrays.stream(y).map(x -> x/2).toArray(Double[]::new))
.toArray(Double[][]::new);

probably should do what you want.


问:
TinyMCE theme files missing when used with LaravelMix
I tried to use TinyMCE with plain HTML & jquery, like below and it works fine.

```<code><script src="js/jquery-3.3.1.min.js"></script>
<script src="js/tinymce/jquery.tinymce.min.js" charset="utf-8"></script>
<script type="text/javascript">
    tinymce.init({
        selector: '#comment'
    });
</script>
</code>```

But when I try to do same with latest Laravel mix, referring TinyMCE from node_modules, it gives me errors like GET http://localhost:3000/js/themes/modern/theme.js net::ERR_ABORTED 404 (Not Found)

Somebody please tell me what will be a good place include/require TinyMCE library and how to refer that.

I tried referring it like below in app.js

```<code>require('tinymce/tinymce.min.js');
</code>```

and

```<code>require('tinymce');
</code>```

答:
Here's the cleanest solution as of 2020.

Install tinymce via NPM:

```<code>npm i tinymce
</code>```

Add these requires to resources/js/app.js:

```<code>require('tinymce');
require('tinymce/themes/silver');
</code>```

Add this line to webpack.mix.js:

```<code>mix.copy('node_modules/tinymce/skins', 'public/js/skins');
</code>```

Then do npm run dev and you're good to go.

Body:
I tried to use TinyMCE with plain HTML & jquery, like below and it works fine.

But when I try to do same with latest Laravel mix, referring TinyMCE from node_modules, it gives me errors like GET http://localhost:3000/js/themes/modern/theme.js net::ERR_ABORTED 404 (Not Found)

Somebody please tell me what will be a good place include/require TinyMCE library and how to refer that.

I tried referring it like below in app.js

require('tinymce/tinymce.min.js');

and

require('tinymce');

Body:
Here's the cleanest solution as of 2020.

Install tinymce via NPM:

npm i tinymce

Add these requires to resources/js/app.js:

require('tinymce');
require('tinymce/themes/silver');

Add this line to webpack.mix.js:

mix.copy('node_modules/tinymce/skins', 'public/js/skins');

Then do npm run dev and you're good to go.


问:
set input max length with php
I'm trying to set a max value to my inputs. I can do it with html but anyone can easily overwrite that in any browser's inspect menu. So I want to use php to set it. I don't really know where I should put it and if this is the right way or not.</p>

```<code><?php
$link = mysqli_connect("localhost", "root", "", "reg");
mysqli_set_charset($link, "utf8");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$job = mysqli_real_escape_string($link, $_REQUEST['job']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$phone2 = mysqli_real_escape_string($link, $_REQUEST['phone2']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$description = mysqli_real_escape_string($link, $_REQUEST['description']);
$visibility = mysqli_real_escape_string($link, $_REQUEST['visibility']);

// attempt insert query execution
$sql = "INSERT INTO cards (name, job, email, phone, phone2, address, description, visibility) VALUES ('$name', '$job', '$email', '$phone', '$phone2', '$address', '$description', '$visibility')";
if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=1");
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

if(strlen($name) > 10)
{
echo "Max value is 10";
}

// close connection
mysqli_close($link);
?>
</code>```

```<code><label>Name</label>
<input class="form-control" id="name" name="name" type="text" required="required">
</code>```

答:
You need to do the strlen() check before you perform the insert, and not insert anything if the check fails.

```<code>if(strlen($name) > 10)
{
    echo "Max value is 10";
    exit();
}
// attempt insert query execution
$sql = "INSERT INTO cards (name, job, email, phone, phone2, address, description, visibility) VALUES ('$name', '$job', '$email', '$phone', '$phone2', '$address', '$description', '$visibility')";
if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=1");
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

</code>```

Title: set input max length with php

Body:
I'm trying to set a max value to my inputs. I can do it with html but anyone can easily overwrite that in any browser's inspect menu. So I want to use php to set it. I don't really know where I should put it and if this is the right way or not.

<?php
$link = mysqli_connect("localhost", "root", "", "reg");
mysqli_set_charset($link, "utf8");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$job = mysqli_real_escape_string($link, $_REQUEST['job']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$phone2 = mysqli_real_escape_string($link, $_REQUEST['phone2']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$description = mysqli_real_escape_string($link, $_REQUEST['description']);
$visibility = mysqli_real_escape_string($link, $_REQUEST['visibility']);

// attempt insert query execution
$sql = "INSERT INTO cards (name, job, email, phone, phone2, address, description, visibility) VALUES ('$name', '$job', '$email', '$phone', '$phone2', '$address', '$description', '$visibility')";
if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=1");
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

if(strlen($name) > 10)
{
echo "Max value is 10";
}

// close connection
mysqli_close($link);
?>

Name
<input class="form-control" id="name" name="name" type="text" required="required">

Body:
You need to do the strlen() check before you perform the insert, and not insert anything if the check fails.

if(strlen($name) > 10)
{
    echo "Max value is 10";
    exit();
}
// attempt insert query execution
$sql = "INSERT INTO cards (name, job, email, phone, phone2, address, description, visibility) VALUES ('$name', '$job', '$email', '$phone', '$phone2', '$address', '$description', '$visibility')";
if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=1");
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


问:
How to use RecyclerView.scrollToPosition() to move the position to the top of current view?
The RecyclerView.scrollToPosition() is extremely strange.
for example, supposed a RecyclerView named "rv".

if now item 10 is under the current RecyclerView, call rv.scrollToPosition(10), the RecyclerView will scroll item 10 to bottom.

if now item 10 is in the current RecyclerView, call rv.scrollToPosition(10), there won't be any scrolling, nothing will be done.

if now item 10 is on the top of the current RecyclerView, call rv.scrollToPosition(10), the RecyclerView will scroll item 10 to top.

To help understanding, look at this picture

But what i need is that, whenever i call it, the RecyclerView will scroll the supposed position to the top of current view just like case 3. How to do that?

答:
This is the Kotlin code snippet but you can just get the point for scrolling to the item by position properly. The point is to declare the member variable for the layout manager and use its method to scroll.</p>

```<code>lateinit var layoutManager: LinearLayoutManager

fun setupView() {
    ...

    layoutManager = LinearLayoutManager(applicationContext)
    mainRecyclerView.layoutManager = layoutManager

    ...
}

fun moveToPosition(position: Int) {
    layoutManager.scrollToPositionWithOffset(position, 0)
}
</code>```

Body:
This is the Kotlin code snippet but you can just get the point for scrolling to the item by position properly. The point is to declare the member variable for the layout manager and use its method to scroll.

lateinit var layoutManager: LinearLayoutManager

fun setupView() {
    ...

    layoutManager = LinearLayoutManager(applicationContext)
    mainRecyclerView.layoutManager = layoutManager

    ...
}

fun moveToPosition(position: Int) {
    layoutManager.scrollToPositionWithOffset(position, 0)
}


问:
ON UPDATE CURRENT_TIMESTAMP not working when updating with identical information
I have this column in my table:

```<code>date_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
</code>```

I noticed that when I try to update the row with the same information, timestamp does not change.

For example, my table (users) is this:

```<code>+----+-------+----------------+-----------+-------------+
| id | name  | food           | confirmed | signup_date |
+----+-------+----------------+-----------+-------------+
|  1 | John  | Casserole      | Y         | 2012-04-11 12:46:55  |
|  2 | Sandy | Key Lime Tarts | N         | 2012-04-14 11:02:02  |
+----+-------+----------------+-----------+-------------+
</code>```

When I run this query, everything works fine (signup_date updates as expected):

```<code>UPDATE users SET name = 'new', food = 'new' where id = 1;
</code>```

However, when I run this (inserting exact info), signup_date remains the same as the previous one:

```<code>UPDATE users SET name = 'John', food = 'Casserole' where id = 1;
</code>```

I need help with getting signup_date update disregarding whether information is the same or not. Who can help?

答: if the value does not change, it won't trigger the automatic update. you can easily try it yourself. </p>

Body:
I have this column in my table:

date_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

I noticed that when I try to update the row with the same information, timestamp does not change.

For example, my table (users) is this:

+----+-------+----------------+-----------+-------------+
| id | name  | food           | confirmed | signup_date |
+----+-------+----------------+-----------+-------------+
|  1 | John  | Casserole      | Y         | 2012-04-11 12:46:55  |
|  2 | Sandy | Key Lime Tarts | N         | 2012-04-14 11:02:02  |
+----+-------+----------------+-----------+-------------+

When I run this query, everything works fine (signup_date updates as expected):

UPDATE users SET name = 'new', food = 'new' where id = 1;

However, when I run this (inserting exact info), signup_date remains the same as the previous one:

UPDATE users SET name = 'John', food = 'Casserole' where id = 1;

I need help with getting signup_date update disregarding whether information is the same or not. Who can help?


问:
Number of rows with specified number of null columns
How to get information how many rows in a table have particular number of nulls in it?

I want to get something like this:

```<code>Number of nulls | Number of rows
        0       |      10
        1       |       4
        2       |      11
</code>```

Motivation:

I need this for data mining purposes. If for example I have an observation that has in almost all columns null value then I need to get rid of this observation, but there can be also a situation where many observations have small value of nulls which is acceptable.

答:
Something like:</p>

```<code>select MyCol, Count(MyCountCol) from
(select 0 +
      case  when Col1 is null then 1 else 0 end
      + case  when Col2 is null then 1 else 0 end
      -- + whatever other col names are in your table
      as MyCountCol

from MyTable)
group by MyCol
</code>```

Body:
How to get information how many rows in a table have particular number of nulls in it?

I want to get something like this:

Number of nulls | Number of rows
        0       |      10
        1       |       4
        2       |      11

Motivation:

I need this for data mining purposes. If for example I have an observation that has in almost all columns null value then I need to get rid of this observation, but there can be also a situation where many observations have small value of nulls which is acceptable.

Body:
Something like:

select MyCol, Count(MyCountCol) from
(select 0 +
      case  when Col1 is null then 1 else 0 end
      + case  when Col2 is null then 1 else 0 end
      -- + whatever other col names are in your table
      as MyCountCol

from MyTable)
group by MyCol


问:
Retrofit/Moshi request gives error - java.lang.IllegalStateException : dangling name
I'm using Retrofit to make some API calls.

Recently, I added a new endpoint

```<code>@POST("api/test/myRequest")
    fun createRequest(
        @retrofit2.http.Body request: MyRequest
    ): Single<MyResponse>
</code>```

Using the following DataClass to represent the non-serialized request

```<code>data class MyRequest(
    @Json(name = "myData") @field:Json(name = "myData") var myData: String,
    @Json(name = "myuuid") @field:Json(name = "myuuid") var myuuid: UUID? = null
)
</code>```

When I try to make the request, it fails with the error: java.lang.IllegalStateException: Dangling name: myuuid

The top item in the stacktrace is: com.squareup.moshi.JsonUtf8Writer.  It seems Moshi is throwing an error when trying to serialize the request.  It's not clear to me why though.

What does this error mean, and how can I fix it?

答:
I would suggest you to use only one of the annotations, for instance you get the issue if you do not use @Json( name, but only @field
I am not sure and could cancel this post if did not help you, but please try, I am quite curious

Body:
I'm using Retrofit to make some API calls.

Recently, I added a new endpoint

@POST("api/test/myRequest")
    fun createRequest(
        @retrofit2.http.Body request: MyRequest
    ): Single<MyResponse>

Using the following DataClass to represent the non-serialized request

data class MyRequest(
    @Json(name = "myData") @field:Json(name = "myData") var myData: String,
    @Json(name = "myuuid") @field:Json(name = "myuuid") var myuuid: UUID? = null
)

When I try to make the request, it fails with the error: java.lang.IllegalStateException: Dangling name: myuuid

The top item in the stacktrace is: com.squareup.moshi.JsonUtf8Writer.  It seems Moshi is throwing an error when trying to serialize the request.  It's not clear to me why though.

What does this error mean, and how can I fix it?


问:
What is more efficient? Storing a split string in an array, or calling the split method everytime you need it
What is going to be faster, storing a split string into an array and using this array within my program, or could I call the .split() method on the string whenever I needed an array to iterate through?

```<code>String main = "1,2,3,4,5,6";
String[] array = main.split(",");
</code>```

vs

```<code>main.split(",");
</code>```

whenever I need to use the input values?

I realise it will be way more readable if I were to store the string in an array. I'd just like to know if the .split() takes more computing time than using an array. Since the split method returns an array containing the split strings.

A simple example(?) loop to go with the question:

```<code>for (int i = main.length - 1; i >= 0; i--){}
</code>```

vs

```<code>for (int i = main.split(",") - 1; i >= 0; i--){}
</code>```

答: As you can see, the split() method returns an array so behind the scenes the main.split(",") will iterate every time you call it through main String to extract the values. So it's faster to use it only once and use the result.

Body:
What is going to be faster, storing a split string into an array and using this array within my program, or could I call the .split() method on the string whenever I needed an array to iterate through?

String main = "1,2,3,4,5,6";
String[] array = main.split(",");

vs

main.split(",");

whenever I need to use the input values?

I realise it will be way more readable if I were to store the string in an array. I'd just like to know if the .split() takes more computing time than using an array. Since the split method returns an array containing the split strings.

A simple example(?) loop to go with the question:

for (int i = main.length - 1; i >= 0; i--){}

vs

for (int i = main.split(",") - 1; i >= 0; i--){}


问:
How can I use POST method in place of GET method
I used POST method but getting following error. Last line shows the error. Initially , I didn't use SecurityConfiguration. Right now, I am using SecurityConfiguration to permit all and still getting authentication error.

```<code>public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
    }
}
</code>```

[2020-02-19 16:02:59.357] [DEBUG] [Context:FilterSecurityInterceptor] [] [Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@64bc4ef4: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 53EB7CECE3D38AF3B70968DB6125DA86; Granted Authorities: ROLE_ANONYMOUS]
[2020-02-19 16:02:59.368] [DEBUG] [Context:AffirmativeBased] [] [Voter: org.springframework.security.web.access.expression.WebExpressionVoter@1173b3b2, returned: -1]
[2020-02-19 16:02:59.371] [DEBUG] [Context:ExceptionTranslationFilter] [] [Access is denied (user is anonymous); redirecting to authentication entry point]
org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:216)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:461)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:394)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:253)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
[2020-02-19 16:02:59.385] [DEBUG] [Context:AndRequestMatcher] [] [Trying to match using Ant [pattern='/', GET]]
**[2020-02-19 16:02:59.386] [DEBUG] [Context:AntPathRequestMatcher] [] [Request 'POST /error' doesn't match 'GET /']**

```<code>
   @PostMapping(value ="/createAncillaries")
   public CreateOrderResponseType createAncillaries(@RequestBody(required=true) String message ) {
      return orderDetailsService.createAncillaries(message);
   }

</code>```

答:
URLs have length restrictions. Check this - https://stackoverflow.com/a/417184/919158.

Try using POST method and post the data as @RequestBody

Body:
I used POST method but getting following error. Last line shows the error. Initially , I didn't use SecurityConfiguration. Right now, I am using SecurityConfiguration to permit all and still getting authentication error.

public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
    }
}

[2020-02-19 16:02:59.357] [DEBUG] [Context:FilterSecurityInterceptor] [] [Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@64bc4ef4: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 53EB7CECE3D38AF3B70968DB6125DA86; Granted Authorities: ROLE_ANONYMOUS]
[2020-02-19 16:02:59.368] [DEBUG] [Context:AffirmativeBased] [] [Voter: org.springframework.security.web.access.expression.WebExpressionVoter@1173b3b2, returned: -1]
[2020-02-19 16:02:59.371] [DEBUG] [Context:ExceptionTranslationFilter] [] [Access is denied (user is anonymous); redirecting to authentication entry point]
org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:216)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:461)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:394)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:253)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
[2020-02-19 16:02:59.385] [DEBUG] [Context:AndRequestMatcher] [] [Trying to match using Ant [pattern='/', GET]]
**[2020-02-19 16:02:59.386] [DEBUG] [Context:AntPathRequestMatcher] [] [Request 'POST /error' doesn't match 'GET /']**

   @PostMapping(value ="/createAncillaries")
   public CreateOrderResponseType createAncillaries(@RequestBody(required=true) String message ) {
      return orderDetailsService.createAncillaries(message);
   }


问:
Is there any reason to retain a scheduled NSTimer if you don't need to invalidate it?
I'm going back over some crufty code to tidy it up and I see I've been retaining NSTimers returned from scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: and storing them in a field - then releasing and nulling the field when it fires. In some cases I use the timer to send an invalidate message to it later - but in many cases not.

In more recent code I usually just schedule the timer and forget about it. I understand that the constructor method is autoreleasing and the timer is retained by the run loop while it is active - so I don't see any issue with this.

So, just to round out my understanding - is there any other reason I should be holding on to my timers, or is what I am doing now the accepted idiom?

This is all in the context of iPhone code, but I don't believe this is iPhone specific.

答:
I'm answering my own question.

I was mostly asking the question because I'd been browsing through the class reference docs and this issue was not really made clear. I've since read the Timer Programming Topics: Using Timers article in the ADC and it covers it pretty well - especially the section on memory management at the end.

According to that what I am doing now (just scheduling, unless I need to be able to call invalidate, or isValid etc) is the right way.

OwnerDisplayName: Phil Nash


问:
Using a loop when sending a Postmark message
I am trying to send an email to the user of my site with order details in it. The email would show a list of items that the user has ordered. On web pages I use a foreach loop that displays the list of items.
When I try to this within my postmark email message it gives the error: "Invalid expression term 'foreach'".
I don't know how to proceed with this and there isn't much postmark documentation to help.

My code:

```<code>    //database query
PostmarkMessage cmessage = new PostmarkMessage
{
From = "server@server.co.uk",
To = "user@user.co.uk",
Subject = "Thank you! " + ordernumber,
HtmlBody = "<h2>Your Order:" + ordernumber + "</h2><br />" +
 foreach (var o in order)//error here
 {
  <div>
  <div>@o.to_ChooseCanvasSize</div><div>£@o.to_Price</div>
  <div>@o.to_Amount</div><div>£@o.to_ItemTotalPrice</div></div>
  }
  "end!",
 };
</code>```

I am working in C# and ASP.NET Web Pages.
Thanks

答:
You need to manually assemble a string using a StringBuilder and a separate loop, then set the HtmlBody property to the generated string.

Alternatively, if you're really in a Razor page, you could use an inline helper:

```<code>HtmlBody = new Func<object, HelperResult>(@<text>
    <h2>...</h2>
    @foreach(...) { ... }
</text>)(null).ToString()
</code>```

Body:
I am trying to send an email to the user of my site with order details in it. The email would show a list of items that the user has ordered. On web pages I use a foreach loop that displays the list of items.
When I try to this within my postmark email message it gives the error: "Invalid expression term 'foreach'".
I don't know how to proceed with this and there isn't much postmark documentation to help.

My code:

    //database query
PostmarkMessage cmessage = new PostmarkMessage
{
From = "server@server.co.uk",
To = "user@user.co.uk",
Subject = "Thank you! " + ordernumber,
HtmlBody = "
Your Order:" + ordernumber + "

" +
 foreach (var o in order)//error here
 {

@o.to_ChooseCanvasSize

£@o.to_Price

@o.to_Amount

£@o.to_ItemTotalPrice

  }
  "end!",
 };

I am working in C# and ASP.NET Web Pages.
Thanks

Body:
You need to manually assemble a string using a StringBuilder and a separate loop, then set the HtmlBody property to the generated string.

Alternatively, if you're really in a Razor page, you could use an inline helper:

HtmlBody = new Func<object, HelperResult>(@<text>
    <h2>...</h2>
    @foreach(...) { ... }
</text>)(null).ToString()


问:
Antd Popover close on click inside popover
Here is a sandbox Antd popover.

Popover by default closes whenever you click anywhere outside of the popover window. I want to also have the popover close whenever you click on any content inside the popover

I have seen some examples where popover is called and rendered in a class like this. Where they use state to control visibility and in content they can use onClick={this.hide} to close the window whenever you click on that content.

I would like to keep popover in a function and Links as its own function that just returns a list of links.

For example, I have tried using react useState and onBlur to achieve my desired result like this. In that sandbox if you look at the console log, the link in Links is never clicked.

Is this possible with antd popover?

edit: I would prefer a solution that does not pass anything from the function with popover to the function producing links.

答:
Try sharing the visible state with Link component:

```<code>function Links({ setShow }) {
  return (
    <div
      onClick={e => {
        e.preventDefault();
        setShow(false);
      }}
      onBlur={() => {
        setShow(false);
      }}
    >
      <a href="j">Then click here</a>
    </div>
  );
}
</code>```

Body:
Try sharing the visible state with Link component:

function Links({ setShow }) {
  return (
    <div
      onClick={e => {
        e.preventDefault();
        setShow(false);
      }}
      onBlur={() => {
        setShow(false);
      }}
    >
      <a href="j">Then click here</a>
    </div>
  );
}


问:
Is it possible to get a list of files under a directory of a website? How?
Say I have a website www.example.com. Under the website directory there is a page secret.html. It can be accessed directly like www.example.com/secret.html, but there are no pages that link to it. Is it possible to discover this page, or will it remain hidden from outside world?

答:
Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories.  If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more.  But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging.  But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

Except, of course, if they can enter your FTP or access your site control panel.


问:
Create lines of string where the number of lines is equal to the number of elements in a list
I am trying to create a function where it takes the length of a list and can produce lines of string where the number of lines is equal to the number of elements in said list.

For example, if for list x, len(x) = 2, and I want to produce:

Hello
Hello
```

<p>Or if <code>len(x) = 3</code></p>

<pre class="lang-py prettyprint-override"><code>Hello
Hello
Hello
</code>```

How could I code this for any length, which is bigger than 0?

Thanks in advance!

答:
You can do it in multiple ways:

1) As @jordanm said in a comment, you can do it in such a way (when you multiply a string by integer Python returns a new string that is repeated the given (len(x)) number of times):

```<code>def my_func():
    print("Hello\n" * len(x))
</code>```

2) As @John Gordon said in the answer you can do it like this (iterate over your x list, print will be called exactly len(x) times):

```<code>def my_func():
    for _ in x:
        print("Hello")
</code>```

3) Or you can do it this way (iterate over range(len(x)) iterable which contains numbers from 0 to len(x) - 1 (both ends included) - print function will be called exactly len(x) times):

```<code>def my_func():
    for _ in range(len(x)):
        print("Hello")
</code>```

In all these examples x is your list

Body:
I am trying to create a function where it takes the length of a list and can produce lines of string where the number of lines is equal to the number of elements in said list.

For example, if for list x, len(x) = 2, and I want to produce:

Hello
Hello

Or if len(x) = 3

Hello
Hello
Hello

How could I code this for any length, which is bigger than 0?

Thanks in advance!

Body:
You can do it in multiple ways:

1) As @jordanm said in a comment, you can do it in such a way (when you multiply a string by integer Python returns a new string that is repeated the given (len(x)) number of times):

def my_func():
    print("Hello\n" * len(x))

2) As @John Gordon said in the answer you can do it like this (iterate over your x list, print will be called exactly len(x) times):

def my_func():
    for _ in x:
        print("Hello")

3) Or you can do it this way (iterate over range(len(x)) iterable which contains numbers from 0 to len(x) - 1 (both ends included) - print function will be called exactly len(x) times):

def my_func():
    for _ in range(len(x)):
        print("Hello")

In all these examples x is your list


问:
Completing or inserting empty rows in-between ordered factors
I have a data frame where I have aggregated the total activity per member for 15 different months (as ordered factors). Now the months/levels, where a member has not had any activity is simply skipped as there are no rows in the original data.

The data looks like this:

```<code>MemberID  MonthYr  freq
1         04-2014    2
1         05-2014    3
1         07-2014    2
1         08-2014    5
2         04-2014    3
2         05-2014    3
3         06-2014    6
3         07-2014    4
3         11-2014    2
3         12-2014    3
</code>```

I want to insert new rows in between the active months, so that the months show a frequency of 0.

Like this:

```<code>MemberID  MonthYr  freq
1         04-2014    2
1         05-2014    3
1         06-2014    0
1         07-2014    2
1         08-2014    5
2         04-2014    3
2         05-2014    3
3         06-2014    6
3         07-2014    4
3         08-2014    0
3         09-2014    0
3         10-2014    0
3         11-2014    2
3         12-2014    3
</code>```

However every member hasn't become members at the same time, so the 0's can only be between the min and max MonthYr for each member.

答:
We can use complete to do this.  Convert the 'MonthYr' to Date class, then grouped by 'MemberID', use complete to expand the 'MonthYr' from min to max 'Date' by 'month', while filling  the 'freq' with 0 and if needed, convert back the 'MonthYr' to original format

```<code>library(dplyr)
library(tidyr)
library(zoo)
df1 %>%
   mutate(MonthYr = as.Date(as.yearmon(MonthYr, "%m-%Y"))) %>%
   group_by(MemberID) %>%
   complete(MonthYr = seq(min(MonthYr), max(MonthYr), by = '1 month'),
      fill = list(freq = 0)) %>%
   mutate(MonthYr = format(MonthYr, "%m-%Y"))
# A tibble: 14 x 3
# Groups:   MemberID [3]
#   MemberID MonthYr  freq
#      <int> <chr>   <dbl>
# 1        1 04-2014     2
# 2        1 05-2014     3
# 3        1 06-2014     0
# 4        1 07-2014     2
# 5        1 08-2014     5
# 6        2 04-2014     3
# 7        2 05-2014     3
# 8        3 06-2014     6
# 9        3 07-2014     4
#10        3 08-2014     0
#11        3 09-2014     0
#12        3 10-2014     0
#13        3 11-2014     2
#14        3 12-2014     3
</code>```

data

```<code>df1 <- structure(list(MemberID = c(1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L,
3L), MonthYr = c("04-2014", "05-2014", "07-2014", "08-2014",
"04-2014", "05-2014", "06-2014", "07-2014", "11-2014", "12-2014"
), freq = c(2L, 3L, 2L, 5L, 3L, 3L, 6L, 4L, 2L, 3L)),
class = "data.frame", row.names = c(NA,
-10L))
</code>```

Body:
I have a data frame where I have aggregated the total activity per member for 15 different months (as ordered factors). Now the months/levels, where a member has not had any activity is simply skipped as there are no rows in the original data.

The data looks like this:

MemberID  MonthYr  freq
1         04-2014    2
1         05-2014    3
1         07-2014    2
1         08-2014    5
2         04-2014    3
2         05-2014    3
3         06-2014    6
3         07-2014    4
3         11-2014    2
3         12-2014    3

I want to insert new rows in between the active months, so that the months show a frequency of 0.

Like this:

MemberID  MonthYr  freq
1         04-2014    2
1         05-2014    3
1         06-2014    0
1         07-2014    2
1         08-2014    5
2         04-2014    3
2         05-2014    3
3         06-2014    6
3         07-2014    4
3         08-2014    0
3         09-2014    0
3         10-2014    0
3         11-2014    2
3         12-2014    3

However every member hasn't become members at the same time, so the 0's can only be between the min and max MonthYr for each member.

Body:
We can use complete to do this.  Convert the 'MonthYr' to Date class, then grouped by 'MemberID', use complete to expand the 'MonthYr' from min to max 'Date' by 'month', while filling  the 'freq' with 0 and if needed, convert back the 'MonthYr' to original format

library(dplyr)
library(tidyr)
library(zoo)
df1 %>%
   mutate(MonthYr = as.Date(as.yearmon(MonthYr, "%m-%Y"))) %>%
   group_by(MemberID) %>%
   complete(MonthYr = seq(min(MonthYr), max(MonthYr), by = '1 month'),
      fill = list(freq = 0)) %>%
   mutate(MonthYr = format(MonthYr, "%m-%Y"))
# A tibble: 14 x 3
# Groups:   MemberID [3]
#   MemberID MonthYr  freq
#      <int> <chr>   <dbl>
# 1        1 04-2014     2
# 2        1 05-2014     3
# 3        1 06-2014     0
# 4        1 07-2014     2
# 5        1 08-2014     5
# 6        2 04-2014     3
# 7        2 05-2014     3
# 8        3 06-2014     6
# 9        3 07-2014     4
#10        3 08-2014     0
#11        3 09-2014     0
#12        3 10-2014     0
#13        3 11-2014     2
#14        3 12-2014     3

data

df1 <- structure(list(MemberID = c(1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L,
3L), MonthYr = c("04-2014", "05-2014", "07-2014", "08-2014",
"04-2014", "05-2014", "06-2014", "07-2014", "11-2014", "12-2014"
), freq = c(2L, 3L, 2L, 5L, 3L, 3L, 6L, 4L, 2L, 3L)),
class = "data.frame", row.names = c(NA,
-10L))


问:
Why is the Row of a named range in Excel not an integer
```<code>Sub fix_name_ranges()
    Dim rangeData As Range
    Dim startRow As Integer

    Set rangeData = ThisWorkbook.Names("test_range").RefersToRange
    Set startRow = rangeData.Row
</code>```

The last statement gives an error of:

```<code>Compile Error

Object Required
</code>```

rangeData.Row is an object of Integer, no?

答:
Others have already given the quick solution - remove the Set keyword, because this is a value assignment, not a reference assignment.

rangeData.Row is an object of Integer, no?

No. Let's learn how to fish here. Hit F2 to bring up the Object Browser; locate the Range class, then its Row member:

Range.Row is a read-only Long integer property. So yes, it's an integer value (Long is a 32-bit signed integer type), but not an Integer (that's a 16-bit signed integer type), and not an object either.

```<code>Dim startRow As Integer
</code>```

Change that declaration to As Long, to avoid overflow errors when you assign it to anything greater than 2^15-1 (i.e. 32,767).

Intrinsic data types are assigned with what's dubbed a "let" assignment:

```<code>[Let] startRow = 42
</code>```

Of course that Let keyword is deprecated and redundant, you don't need to specify it. But just know that it's implicitly there, whenever you are assigning a value.

When you assign an object reference, then you need a "set" assignment, like you (correctly) have here:

```<code>Set rangeData = ThisWorkbook.Names("test_range").RefersToRange
</code>```

The intrinsic data types ("let assignment") are your Boolean, Byte, Currency, Date, Double, Integer, Long, Single, ..and probably others I'm forgetting; object data types ("set assignment") are Object, and any data type defined by a class, like Range, Worksheet, and Class1.

The reason a Set keyword is required, is because objects can have a parameterless default member that make the assignment ambiguous otherwise:

```<code>foo = Range("A1")
</code>```

If Set wasn't required, VBA wouldn't have a way to know whether foo is supposed to hold a Range reference, or whether that assignment means to grab the Range object's default property value, and assign that value to foo.

Body:
Sub fix_name_ranges()
    Dim rangeData As Range
    Dim startRow As Integer

    Set rangeData = ThisWorkbook.Names("test_range").RefersToRange
    Set startRow = rangeData.Row

The last statement gives an error of:

Compile Error

Object Required

rangeData.Row is an object of Integer, no?

Body:
Others have already given the quick solution - remove the Set keyword, because this is a value assignment, not a reference assignment.

rangeData.Row is an object of Integer, no?

No. Let's learn how to fish here. Hit F2 to bring up the Object Browser; locate the Range class, then its Row member:

Range.Row is a read-only Long integer property. So yes, it's an integer value (Long is a 32-bit signed integer type), but not an Integer (that's a 16-bit signed integer type), and not an object either.

Dim startRow As Integer

Change that declaration to As Long, to avoid overflow errors when you assign it to anything greater than 2^15-1 (i.e. 32,767).

Intrinsic data types are assigned with what's dubbed a "let" assignment:

[Let] startRow = 42

Of course that Let keyword is deprecated and redundant, you don't need to specify it. But just know that it's implicitly there, whenever you are assigning a value.

When you assign an object reference, then you need a "set" assignment, like you (correctly) have here:

Set rangeData = ThisWorkbook.Names("test_range").RefersToRange

The intrinsic data types ("let assignment") are your Boolean, Byte, Currency, Date, Double, Integer, Long, Single, ..and probably others I'm forgetting; object data types ("set assignment") are Object, and any data type defined by a class, like Range, Worksheet, and Class1.

The reason a Set keyword is required, is because objects can have a parameterless default member that make the assignment ambiguous otherwise:

foo = Range("A1")

If Set wasn't required, VBA wouldn't have a way to know whether foo is supposed to hold a Range reference, or whether that assignment means to grab the Range object's default property value, and assign that value to foo.


问:
Set cultureinfo into listview xamarin forms?
I need to convert a currency value to the culture of a specific country. In the code behind it works perfectly, but I don't know how to do it in a listview.

Code behind

```<code>TotalLabel.Text = MyDouble.ToString("C0", CultureInfo.CreateSpecificCulture("es-CL"));
</code>```

How can I do it in a listview?

```<code> <ListView.ItemTemplate >
                    <DataTemplate >
                        <ViewCell >
                                <Label Grid.Row="0" Grid.Column="2" Margin="0"   Text="{Binding Price,StringFormat='{0:C}'}" BackgroundColor="Transparent" HorizontalTextAlignment="End" HorizontalOptions="FillAndExpand" />
                                <Label Grid.Row="0" Grid.Column="3" Margin="0"   Text="{Binding Total,StringFormat='{0:C}'}" BackgroundColor="Transparent" HorizontalTextAlignment="End" HorizontalOptions="FillAndExpand" Style="{StaticResource entryReadOnlyStyle}"/>
                        </ViewCell>
                    </DataTemplate>
 </ListView.ItemTemplate>
</code>```

Could you help me?. Thank you

答:
You can write a converter. Here's an example of how to write and consume it in your XAML page.

First create a class called CurrencyCultureConverter or something like that

```<code>using System;
using System.Globalization;
using Xamarin.Forms;

namespace YourApp.Converters
{
    public class CurrencyCultureConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString("C0", CultureInfo.CreateSpecificCulture("es-CL"));
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
</code>```

Then in your XAML

```<code>...
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converter="clr-namespace:YourApp.Converters;assembly=YourApp"
...

<ResourceDictionary>
    <converter:CurrencyCultureConverter x:Key="CurrencyCultureConverter" />
</ResourceDictionary>

<Label ... Text="{Binding Price,Converter={StaticResource CurrencyCultureConverter}}" BackgroundColor="Transparent" ... />
</code>```

Body:
I need to convert a currency value to the culture of a specific country. In the code behind it works perfectly, but I don't know how to do it in a listview.

Code behind

TotalLabel.Text = MyDouble.ToString("C0", CultureInfo.CreateSpecificCulture("es-CL"));

How can I do it in a listview?

 <ListView.ItemTemplate >
                    <DataTemplate >
                        <ViewCell >

                        </ViewCell>
                    </DataTemplate>
 </ListView.ItemTemplate>

Could you help me?. Thank you

Body:
You can write a converter. Here's an example of how to write and consume it in your XAML page.

First create a class called CurrencyCultureConverter or something like that

using System;
using System.Globalization;
using Xamarin.Forms;

namespace YourApp.Converters
{
    public class CurrencyCultureConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString("C0", CultureInfo.CreateSpecificCulture("es-CL"));
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Then in your XAML

...
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converter="clr-namespace:YourApp.Converters;assembly=YourApp"
...

<ResourceDictionary>
    <converter:CurrencyCultureConverter x:Key="CurrencyCultureConverter" />
</ResourceDictionary>

<Label ... Text="{Binding Price,Converter={StaticResource CurrencyCultureConverter}}" BackgroundColor="Transparent" ... />


问:
IO values into haskell function
I currently have a function with definition:

```<code>f :: [Int] -> Int -> [[Int]]
</code>```

And have two variables of type IO [Int] and IO Int. I want to pass these variables to this function f. I am able to do this when it is just one variable being passed to the function, but when it is 2 I can't get it to work.

答:
IO has an Applicative instance, so you can use liftA2:

```<code>> f = undefined :: [Int] -> Int -> [[Int]]
> import Control.Applicative
> :t liftA2 f
liftA2 f :: Applicative f => f [Int] -> f Int -> f [[Int]]
</code>```

With the TypeApplications extension, you can see it more clearly.

```<code>> :set -XTypeApplications
> :t liftA2 @IO f
liftA2 @IO f :: IO [Int] -> IO Int -> IO [[Int]]
</code>```

Title: IO values into haskell function

Body:
I currently have a function with definition:

f :: [Int] -> Int -> [[Int]]

And have two variables of type IO [Int] and IO Int. I want to pass these variables to this function f. I am able to do this when it is just one variable being passed to the function, but when it is 2 I can't get it to work.

Body:
IO has an Applicative instance, so you can use liftA2:

> f = undefined :: [Int] -> Int -> [[Int]]
> import Control.Applicative
> :t liftA2 f
liftA2 f :: Applicative f => f [Int] -> f Int -> f [[Int]]

With the TypeApplications extension, you can see it more clearly.

> :set -XTypeApplications
> :t liftA2 @IO f
liftA2 @IO f :: IO [Int] -> IO Int -> IO [[Int]]


问:
Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundColor(int)' on a null object reference
This code is inside a while loop that moves the cursor in a database for each loop. I want that if daysLeftInt is under 6, then the id (R.id.leftColor) should be the color of the variable redColor.

```<code>            if(daysLeftInt < 6) {
                Context context = this;
                int redColor = ContextCompat.getColor(context, R.color.red);
                TextView rectangleView = (TextView)findViewById(R.id.leftColor);
                rectangleView.setBackgroundColor(redColor);

            }
</code>```

I get this error message:

Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundColor(int)' on a null object reference

This is how my layouts is setup:

Do anyone know how i will get the result that I want?

activity_main.xml.

```<code><?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer" />

    </android.support.v4.widget.DrawerLayout>
</code>```

activity_main.xml includes this file called app_bar_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mysubscriptions.alexklug.mysubscriptions.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />
<include layout="@layout/content_subscription" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    app:srcCompat="@android:drawable/ic_menu_send"
    android:onClick="openSubscriptionActivity"
    />

</android.support.design.widget.CoordinatorLayout>
</code>```

app_bar_main.xml include the layout file content_main.xml which is this file:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.mysubscriptions.alexklug.mysubscriptions.MainActivity"
tools:showIn="@layout/app_bar_main">

<ListView
    android:id="@+id/subscriptionsList"
    android:layout_width="368dp"
    android:textAllCaps="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="8dp">
</ListView>
</code>```

Inside the ListView an ArrayAdapter helps displaying the last file called list_item.xml.
The first TextView is the view with the id of leftColor.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <TextView

        android:id="@+id/leftColor"
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.01"
        />

    <ImageView
        android:id="@+id/subscription_image"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:src="@mipmap/ic_netflix"
        android:padding="10dp"/>

    <TextView
        android:id="@+id/subscription_name"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textColor="#000000"
        android:textSize="15sp"
        android:textStyle="bold"
        tools:text="First"
        android:ellipsize="end"
        android:maxLines="1"

        />

    <TextView
        android:id="@+id/subscription_price"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        tools:text="Second"
        android:textSize="12sp"
        android:layout_width="0dp"
        android:layout_weight=".7"
        android:gravity="center"
        />

    <TextView
        android:id="@+id/subscription_days_left"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:textSize="24sp"
        android:textColor="#000000"
        tools:text="12"
        android:layout_width="0dp"
        android:layout_weight=".7"
        android:textStyle="bold"
        android:gravity="center"
        />

    <View
        android:id="@+id/myRectangleView"
        android:layout_width="7dp"
        android:layout_height="7dp"
        android:layout_marginTop="24dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:background="@drawable/circle" />

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

答:
It's android studios fault, just put in a delay of about 50 milliseconds. Example:</p>

```<code> Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                listView.getChildAt(0).setBackgroundColor(Color.BLUE);
                listView.getChildAt(1).setBackgroundColor(Color.WHITE);
                listView.getChildAt(2).setBackgroundColor(Color.RED);
                listView.getChildAt(3).setBackgroundColor(Color.BLACK);
            }
        }, 50);
</code>```

Body:
This code is inside a while loop that moves the cursor in a database for each loop. I want that if daysLeftInt is under 6, then the id (R.id.leftColor) should be the color of the variable redColor.

            if(daysLeftInt < 6) {
                Context context = this;
                int redColor = ContextCompat.getColor(context, R.color.red);
                TextView rectangleView = (TextView)findViewById(R.id.leftColor);
                rectangleView.setBackgroundColor(redColor);

            }

I get this error message:

Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundColor(int)' on a null object reference

This is how my layouts is setup:

Do anyone know how i will get the result that I want?

activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer" />

    </android.support.v4.widget.DrawerLayout>

activity_main.xml includes this file called app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mysubscriptions.alexklug.mysubscriptions.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />
<include layout="@layout/content_subscription" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    app:srcCompat="@android:drawable/ic_menu_send"
    android:onClick="openSubscriptionActivity"
    />

</android.support.design.widget.CoordinatorLayout>

app_bar_main.xml include the layout file content_main.xml which is this file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.mysubscriptions.alexklug.mysubscriptions.MainActivity"
tools:showIn="@layout/app_bar_main">

<ListView
    android:id="@+id/subscriptionsList"
    android:layout_width="368dp"
    android:textAllCaps="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="8dp">
</ListView>

Inside the ListView an ArrayAdapter helps displaying the last file called list_item.xml.
The first TextView is the view with the id of leftColor.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <TextView

        android:id="@+id/leftColor"
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.01"
        />

    <ImageView
        android:id="@+id/subscription_image"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:src="@mipmap/ic_netflix"
        android:padding="10dp"/>

    <TextView
        android:id="@+id/subscription_name"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textColor="#000000"
        android:textSize="15sp"
        android:textStyle="bold"
        tools:text="First"
        android:ellipsize="end"
        android:maxLines="1"

        />

    <TextView
        android:id="@+id/subscription_price"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        tools:text="Second"
        android:textSize="12sp"
        android:layout_width="0dp"
        android:layout_weight=".7"
        android:gravity="center"
        />

    <TextView
        android:id="@+id/subscription_days_left"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:textSize="24sp"
        android:textColor="#000000"
        tools:text="12"
        android:layout_width="0dp"
        android:layout_weight=".7"
        android:textStyle="bold"
        android:gravity="center"
        />

    <View
        android:id="@+id/myRectangleView"
        android:layout_width="7dp"
        android:layout_height="7dp"
        android:layout_marginTop="24dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:background="@drawable/circle" />

    </LinearLayout>
</LinearLayout>

Body:
It's android studios fault, just put in a delay of about 50 milliseconds. Example:

 Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                listView.getChildAt(0).setBackgroundColor(Color.BLUE);
                listView.getChildAt(1).setBackgroundColor(Color.WHITE);
                listView.getChildAt(2).setBackgroundColor(Color.RED);
                listView.getChildAt(3).setBackgroundColor(Color.BLACK);
            }
        }, 50);