问:
How to find the most recent file in a directory using cpp filesystem
I'm trying to get the most recent file in a log directory. I'm using c++ and filesystem library.

I tried to use a directory_iterator from experimental/filesystem to iterate on every file in my directory, and, using std::max_element, compare the last_write_time of each file to have the greater one.

namespace fs = std::experimental::filesystem;
auto dir_it = fs::directory_iterator(my_path);
auto path = *std::max_element(fs::begin(dir_it), fs::end(dir_it), [](const fs::directory_entry& f1, const fs::directory_entry& f2){
  return fs::last_write_time(f1.path()) < fs::last_write_time(f2.path());
});
```

I expect to get an fs::directory_entry object but when I print the path, it's empty.
So I took a look at the compared elements inside my function, and at each step, f1.path() == f2.path(), so the output is understandable but I didn't figure out why the compare function doesn't work.

答:
max_element requires a forward iterator, while directory_iterator is an input iterator.

So if you want to do things this way, you'll need to either create a container from the iterators, or manually write a loop yourself.

Body:
I'm trying to get the most recent file in a log directory. I'm using c++ and filesystem library.

I tried to use a directory_iterator from experimental/filesystem to iterate on every file in my directory, and, using std::max_element, compare the last_write_time of each file to have the greater one.

namespace fs = std::experimental::filesystem;
auto dir_it = fs::directory_iterator(my_path);
auto path = *std::max_element(fs::begin(dir_it), fs::end(dir_it), [](const fs::directory_entry& f1, const fs::directory_entry& f2){
  return fs::last_write_time(f1.path()) < fs::last_write_time(f2.path());
});

I expect to get an fs::directory_entry object but when I print the path, it's empty.
So I took a look at the compared elements inside my function, and at each step, f1.path() == f2.path(), so the output is understandable but I didn't figure out why the compare function doesn't work.


来源: stackexchange

问:
APK size is too big because of audio files
I'm working on my own Ebook application. My book has a total of 15 chapters, so I have a list with 15 elements - each one is a string with all the chapter's text.

I also have 15 .ogg files that I paid a voice over talent to record. The size of my final APK is almost 97MB, where about 90MB of them are a result of my audio files.

What can I do in order to reduce the APK to 25MB or less and yet give my users the option to listen to the narration?

答:
You should look into Google Play Dynamic Delivery with the Android App Bundle.

This allows to split your Android app in modules, some of which you could download on-demand at runtime.

Effectively, this would allow you to download the .ogg only when the user needs them, or pre-load them if you can predict which ones are going to be listened to next (e.g. if they have an order).

ContentLicense: CC BY-SA 4.0


问:
How to do append insertion in sparksql?
I have a api endpoint written by sparksql with the following sample code. Every time api accept a request it will run sparkSession.sql(sql_to_hive) which would create a single file in HDFS. Is there any way to do insert by appending data to existing file in HDFS ? Thanks.</p>

```<code>    sqlContext = SQLContext(sparkSession.sparkContext)
    df = sqlContext.createDataFrame(ziped_tuple_list, schema=schema)
    df.registerTempTable('TMP_TABLE')
    sql_to_hive = 'insert into log.%(table_name)s partition%(partition)s select %(title_str)s from TMP_TABLE'%{
        'table_name': table_name,
        'partition': partition_day,
        'title_str': title_str
    }
    sparkSession.sql(sql_to_hive)
</code>```

答:
When you write the resulted dataframe:

result_df = sparkSession.sql(sql_to_hive)

set it’s mode to append:

result_df.write.mode(SaveMode.Append).

Title: How to do append insertion in sparksql?

Body:
I have a api endpoint written by sparksql with the following sample code. Every time api accept a request it will run sparkSession.sql(sql_to_hive) which would create a single file in HDFS. Is there any way to do insert by appending data to existing file in HDFS ? Thanks.

    sqlContext = SQLContext(sparkSession.sparkContext)
    df = sqlContext.createDataFrame(ziped_tuple_list, schema=schema)
    df.registerTempTable('TMP_TABLE')
    sql_to_hive = 'insert into log.%(table_name)s partition%(partition)s select %(title_str)s from TMP_TABLE'%{
        'table_name': table_name,
        'partition': partition_day,
        'title_str': title_str
    }
    sparkSession.sql(sql_to_hive)


问:
jQuery .keyup() function
I'm not receiving any output from this code. What could be the error.

terminal.html

```<code><html>
<head>
<link href="/css/webterminal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.5.2.js"/>
<script type="text/javascript">
function shell_execute(str) {
  $.ajax({
    url: 'exec.php',
    dataType: 'text',
    data: {
      q: str
    },
    success: function (response) {
      $('#txtOut').append(response);

  });
}
</script>
</head
<body">
    <div class="container">

    <h2>UNIX Web Based Terminal 1.0</h2>
        <br />
    <p><b>output</b></p>
<form>
<span id="User"></span>< <input type="text" id="txtcmd" onkeyup="shell_execute(this.value)" class="textbox" size="20" />
</form>
<div class="output">
<p><span id="txtOut"></span></p>

    </div>
</div>
</body>
</html>
</code>```

exec.php

```<code><?php

$q=$_GET["q"];
$output=shell_exec($q);
echo "```$output```";
?>
</code>```

答:
Instead of

```<code><script type="text/javascript" src="jquery-1.5.2.js"/>
</code>```

Close your script tag like this:

```<code><script type="text/javascript" src="jquery-1.5.2.js"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery .keyup() function

Body:
I'm not receiving any output from this code. What could be the error.

terminal.html

<link href="/css/webterminal.css" rel="stylesheet" type="text/css" />

</head

UNIX Web Based Terminal 1.0

output

<form>
< <input type="text" id="txtcmd" onkeyup="shell_execute(this.value)" class="textbox" size="20" />
</form>

exec.php

<?php

$q=$_GET["q"];
$output=shell_exec($q);
echo "
$output
";
?>

Body:
Instead of

<script type="text/javascript" src="jquery-1.5.2.js"/>

Close your script tag like this:

<script type="text/javascript" src="jquery-1.5.2.js"></script>


问:
Firefox won't redirect to HTTPS properly
I've wrote the lines below in the .htaccess of my wordpress website, however, Firefox redirects neither http://mywebsite.com nor http://www.mywebsite.com to https://www.mywebsite.com. All the other browsers redirects properly.

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Does anyone know what's the issue?

答: Maybe your problem will be solved if you disable the cache.</p>

Body:
I've wrote the lines below in the .htaccess of my wordpress website, however, Firefox redirects neither http://mywebsite.com nor http://www.mywebsite.com to https://www.mywebsite.com. All the other browsers redirects properly.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Does anyone know what's the issue?


问:
make api call for each item of array
I have an array of object of days, I want to make separate HTTP call for each array item. but the condition is when I get the previous items success response then only I want to make next items API request till I want to wait. suppose I have 5 items in my array so it will make API call immediately. I want that each items API request sequentially. means when my first items API requests response is true then second items API should call.

I have used a for & for each loop and traverse each array item & make HTTP post call but it don't wait for previous requests success response.

// component call

daysArr = [
    {
      day: 'Monday',
      date: '20-10-2018'
    },
    {
      day: 'Tuesday',
      date: '21-10-2018'
    },
    {
      day: 'Wednesday',
      date: '22-10-2018'
    },
    {
      day: 'Thursday',
      date: '23-10-2018'
    },
    {
      day: 'Friday',
      date: '24-10-2018'
    },
    {
      day: 'Saturday',
      date: '25-10-2018'
    },
    {
      day: 'Sunday',
      date: '26-10-2018'
    }
  ]

  postCall() {
  let apiUrl = 'https:someurl.com/api/dayspost';
  for (let i = 0; i < this.daysArr.length; i++) {

      // how to check previous request response & make request for next array element

    this.service.createPost(apiUrl,this.daysArr[i])
    .subscribe(response => {
      console.log('response',response)
    })
  }
}

//service post call

createPost(url, post) {
   return this.http.post(url,post)
    .pipe(
      map(data => {
        return data;
      })
     )
 }```

above is the snippet which displays the API request. but I don't understand how can I check my previous response & then only make new API/post call for new array element.

Thank you.

答:
You can do something like this:

```<code>let i = 0;
makeRequest(apiUrl, this.daysArr[i]){
  this.service.createPost(apiUrl,post)
    .subscribe(response => {
       console.log('response',response)
       i++;
       if(i < this.days.length){
          makeRequest(apiUrl, this.daysArr[i])
       }
  })
}
</code>```

I have no IDE right now to try this, but it should work fine

Title: make api call for each item of array

Body:
I have an array of object of days, I want to make separate HTTP call for each array item. but the condition is when I get the previous items success response then only I want to make next items API request till I want to wait. suppose I have 5 items in my array so it will make API call immediately. I want that each items API request sequentially. means when my first items API requests response is true then second items API should call.

I have used a for & for each loop and traverse each array item & make HTTP post call but it don't wait for previous requests success response.

// component call

daysArr = [
    {
      day: 'Monday',
      date: '20-10-2018'
    },
    {
      day: 'Tuesday',
      date: '21-10-2018'
    },
    {
      day: 'Wednesday',
      date: '22-10-2018'
    },
    {
      day: 'Thursday',
      date: '23-10-2018'
    },
    {
      day: 'Friday',
      date: '24-10-2018'
    },
    {
      day: 'Saturday',
      date: '25-10-2018'
    },
    {
      day: 'Sunday',
      date: '26-10-2018'
    }
  ]

  postCall() {
  let apiUrl = 'https:someurl.com/api/dayspost';
  for (let i = 0; i < this.daysArr.length; i++) {

      // how to check previous request response & make request for next array element

    this.service.createPost(apiUrl,this.daysArr[i])
    .subscribe(response => {
      console.log('response',response)
    })
  }
}

//service post call

createPost(url, post) {
   return this.http.post(url,post)
    .pipe(
      map(data => {
        return data;
      })
     )
 }

above is the snippet which displays the API request. but I don't understand how can I check my previous response & then only make new API/post call for new array element.

Thank you.

Body:
You can do something like this:

let i = 0;
makeRequest(apiUrl, this.daysArr[i]){
  this.service.createPost(apiUrl,post)
    .subscribe(response => {
       console.log('response',response)
       i++;
       if(i < this.days.length){
          makeRequest(apiUrl, this.daysArr[i])
       }
  })
}

I have no IDE right now to try this, but it should work fine


问:
GoCD - Angular Build not able execute
I am working on GoCD interface for Angular deployment configuration. I did configure npm install but after I am trying to execute the build command as below, but it is throwing error like

Please make sure [/usr/local/lib/node_modules/@angular/cli/bin/ng build] can be executed on this agent.

Command:

```<code>/usr/local/bin/ng build --configuration=qa
</code>```

See below for the console output (it is working if I execute the above in my machine directly).

I have configured GoCD in my local mac.

```<code> [go] Task: "/usr/local/lib/node_modules/@angular/cli/bin/ng build" --configuration=qatook: 0.5s
    Error happened while attempting to execute '/usr/local/lib/node_modules/@angular/cli/bin/ng build --configuration=qa'.
    Please make sure [/usr/local/lib/node_modules/@angular/cli/bin/ng build] can be executed on this agent.

  [Debug Information] Environment variable PATH: /usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
    [go] Task status: failed, took: 0.5s
    [go] Current job status: failed
</code>```

答:
It's a stupid mistake that i have made. GoCD mentioned it below to the input field.

Basically, If it is multiple arguments, then we need to put that in a new line. So after that, it started working fine.

so in my case, it would be like,

```<code>build
--configuration=qa
</code>```

Please see screen shot.

Title: GoCD - Angular Build not able execute

Body:
I am working on GoCD interface for Angular deployment configuration. I did configure npm install but after I am trying to execute the build command as below, but it is throwing error like

Please make sure [/usr/local/lib/node_modules/@angular/cli/bin/ng build] can be executed on this agent.

Command:

/usr/local/bin/ng build --configuration=qa

See below for the console output (it is working if I execute the above in my machine directly).

I have configured GoCD in my local mac.

 [go] Task: "/usr/local/lib/node_modules/@angular/cli/bin/ng build" --configuration=qatook: 0.5s
    Error happened while attempting to execute '/usr/local/lib/node_modules/@angular/cli/bin/ng build --configuration=qa'.
    Please make sure [/usr/local/lib/node_modules/@angular/cli/bin/ng build] can be executed on this agent.

  [Debug Information] Environment variable PATH: /usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
    [go] Task status: failed, took: 0.5s
    [go] Current job status: failed

Body:
It's a stupid mistake that i have made. GoCD mentioned it below to the input field.

Basically, If it is multiple arguments, then we need to put that in a new line. So after that, it started working fine.

so in my case, it would be like,

build
--configuration=qa

Please see screen shot.


问:
How can I get an array of all the messages from a text channel in discord.py?
I have the channel object, and I've tried

```<code>mess = channel.history(limit=200)
</code>```

but mess is a HistoryIterator object and does not contain any messages in its mess.messages object (size = 0). There are messages in the channel, so it shouldn't say the size is 0.

I've also tried:

```<code>mess = client.logs_from(channel, limit=200)
</code>```

but PyCharm tells me that client has no logs_from function.

Is there an easy way to get all of the messages from a text channel in an array?

答:
HistoryIterator implements the AsyncIterator interface.  You can use the AsyncIterator.flatten method to consume the contents of the Iterator into a list:

```<code>messages = await channel.history(limit=200).flatten()
</code>```

Body:
I have the channel object, and I've tried

mess = channel.history(limit=200)

but mess is a HistoryIterator object and does not contain any messages in its mess.messages object (size = 0). There are messages in the channel, so it shouldn't say the size is 0.

I've also tried:

mess = client.logs_from(channel, limit=200)

but PyCharm tells me that client has no logs_from function.

Is there an easy way to get all of the messages from a text channel in an array?

Body:
HistoryIterator implements the AsyncIterator interface.  You can use the AsyncIterator.flatten method to consume the contents of the Iterator into a list:

messages = await channel.history(limit=200).flatten()


问:
Invalid postback or callback argument.  Event validation is enabled using '<pages enableEventValidation="true"/>'
I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.

How do we fix this?

Error details below:

```<code>Server Error in '/XXX' Application.

--------------------------------------------------------------------------------
Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
   System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
</code>```

答:
3: I changed my button type in grid
  column from "PushButton" to
  "LinkButton". It worked!
  ("ButtonType="LinkButton") I think if
  you can change your button to other
  controls like "LinkButton" in other
  cases, it would work properly.

I wish I could vote you up, Amir (alas my rep is too low.)  I was just having this problem and changing this worked like a champ on my gridview.  Just a little aside, I think the valid code is:  ButtonType="Link"

I suspect this is because when you click 'edit', your edit changes to 'update' and 'cancel' which then change back to 'edit' on submit.  And these shifting controls make .net uneasy.

OwnerDisplayName: Jangwenyi

Body:
I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.

How do we fix this?

Error details below:

Server Error in '/XXX' Application.

--------------------------------------------------------------------------------
Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
   System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

OwnerDisplayName: bdub

ContentLicense: CC BY-SA 2.5


答:
In terminal.html what is str for ???

you should pass some value to get the output

try echoing $_GET['q']; you will come to know

Title: jQuery .keyup() function


问:
running a .py file from another Python script using os
Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

```<code>import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')
</code>```

答:
You can execute an arbitrary Python script as a separate process using the subprocess.run() function something like this:

```<code>import os
import subprocess
import sys

#py_filepath = 'C:/Users/benb/Desktop/flaskEconServer/plots.py'
py_filepath = 'plots_test.py'

args = '"%s" "%s" "%s"' % (sys.executable,                  # command
                           py_filepath,                     # argv[0]
                           os.path.basename(py_filepath))   # argv[1]

proc = subprocess.run(args)
print('returncode:', proc.returncode)
</code>```

If you would like to communicate with the process while it's running, that can also be done, plus there are other subprocess functions, including the lower-level but very general subprocess.Popen class that support doing those kind of things.

Body:
Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')

Body:
You can execute an arbitrary Python script as a separate process using the subprocess.run() function something like this:

import os
import subprocess
import sys

#py_filepath = 'C:/Users/benb/Desktop/flaskEconServer/plots.py'
py_filepath = 'plots_test.py'

args = '"%s" "%s" "%s"' % (sys.executable,                  # command
                           py_filepath,                     # argv[0]
                           os.path.basename(py_filepath))   # argv[1]

proc = subprocess.run(args)
print('returncode:', proc.returncode)

If you would like to communicate with the process while it's running, that can also be done, plus there are other subprocess functions, including the lower-level but very general subprocess.Popen class that support doing those kind of things.


问:
I need to convert the below CSV data to a javascript array
I need to convert this CSV data to an javascript array:

```<code>5/27/2019 19:54:09,5/27/2019, GSCOH6EUYN77D5N5HB22222222,"defgv",street
5/27/2019 20:21:58,5/27/2019, ZJ2ZOMAFNGTWEITTD333333333,"defgv",apartment
5/27/2019 20:33:09,5/27/2019, E3V5MNRGDU4WV4QVD444444444,"defgv",address
5/27/2019 20:34:39,5/27/2019, NQ5TZYVDIDBCEXBYC555555555,"defgv",home
</code>```

I have tried to use :

```<code>var dataArr = xmlData.split("\n");
var data = dataArr.splice(1,dataArr.length-1);
</code>```

but it doesn't work..think its because of the space in the character defgv.Could you please help me to convert this.

Expected output:-

```<code>["5/27/2019 9:54:09,5/27/2019,GSCOH6EUYN77D5N5HB22222222,defgv,street",
"5/27/2019 20:21:58,5/27/2019,OMAFNGTWEITTD333333333,defgv,apartment"]
</code>```

Instead m receiving the output as :

```<code>0: "5/22/2019 17:10:08,5/22/2019, GSCOH6EUYN77D5N5HB22222222,""
1: "      defgv",street
"
2: "5/22/2019 17:24:19,5/22/2019, OMAFNGTWEITTD333333333,""
3: "      defgv",apartment
"
</code>```

答:
It's not clear to me what your input format is.  But taking a guess at it, you might have to split into strings and then combine pairs of them into single strings.  This would do that:

const splitIntoJointRows = (data) =>   data .split ('\n')
       .reduce ((a, s, i, ss) => i % 2 ? [...a, ss[i - 1] + s] : a, [])

//-------------------------------------------------------------------------

const data = `5/27/2019 19:54:09,5/27/2019, GSCOH6EUYN77D5N5HB22222222,
     "defgv",street
5/27/2019 20:21:58,5/27/2019, ZJ2ZOMAFNGTWEITTD333333333,
     "defgv",apartment
5/27/2019 20:33:09,5/27/2019, E3V5MNRGDU4WV4QVD444444444,
     "defgv",address
5/27/2019 20:34:39,5/27/2019, NQ5TZYVDIDBCEXBYC555555555,
     "defgv",home
`;

console .log (
  splitIntoJointRows(data)
)

console .log (
  splitIntoJointRows(data)
    .map(s => s.split(/,\s*/))
)

console .log (
  splitIntoJointRows(data)
    .map(s => s.split(/,\s*/))
    .map(([date, a, b, c, d]) => ({date, a, b, c, d}))
)```

Also in that snippet is a call that use this to build an array of arrays of fields and one that further converts this to an array of objects (with invented keys.)

Body:
I need to convert this CSV data to an javascript array:

5/27/2019 19:54:09,5/27/2019, GSCOH6EUYN77D5N5HB22222222,"defgv",street
5/27/2019 20:21:58,5/27/2019, ZJ2ZOMAFNGTWEITTD333333333,"defgv",apartment
5/27/2019 20:33:09,5/27/2019, E3V5MNRGDU4WV4QVD444444444,"defgv",address
5/27/2019 20:34:39,5/27/2019, NQ5TZYVDIDBCEXBYC555555555,"defgv",home

I have tried to use :

var dataArr = xmlData.split("\n");
var data = dataArr.splice(1,dataArr.length-1);

but it doesn't work..think its because of the space in the character defgv.Could you please help me to convert this.

Expected output:-

["5/27/2019 9:54:09,5/27/2019,GSCOH6EUYN77D5N5HB22222222,defgv,street",
"5/27/2019 20:21:58,5/27/2019,OMAFNGTWEITTD333333333,defgv,apartment"]

Instead m receiving the output as :

0: "5/22/2019 17:10:08,5/22/2019, GSCOH6EUYN77D5N5HB22222222,""
1: "      defgv",street
"
2: "5/22/2019 17:24:19,5/22/2019, OMAFNGTWEITTD333333333,""
3: "      defgv",apartment
"

Body:
It's not clear to me what your input format is.  But taking a guess at it, you might have to split into strings and then combine pairs of them into single strings.  This would do that:

const splitIntoJointRows = (data) =>   data .split ('\n')
       .reduce ((a, s, i, ss) => i % 2 ? [...a, ss[i - 1] + s] : a, [])

//-------------------------------------------------------------------------

const data = `5/27/2019 19:54:09,5/27/2019, GSCOH6EUYN77D5N5HB22222222,
     "defgv",street
5/27/2019 20:21:58,5/27/2019, ZJ2ZOMAFNGTWEITTD333333333,
     "defgv",apartment
5/27/2019 20:33:09,5/27/2019, E3V5MNRGDU4WV4QVD444444444,
     "defgv",address
5/27/2019 20:34:39,5/27/2019, NQ5TZYVDIDBCEXBYC555555555,
     "defgv",home
`;

console .log (
  splitIntoJointRows(data)
)

console .log (
  splitIntoJointRows(data)
    .map(s => s.split(/,\s*/))
)

console .log (
  splitIntoJointRows(data)
    .map(s => s.split(/,\s*/))
    .map(([date, a, b, c, d]) => ({date, a, b, c, d}))
)

Also in that snippet is a call that use this to build an array of arrays of fields and one that further converts this to an array of objects (with invented keys.)


问:
Error: ENOENT: no such file or directory, scandir '.../node_modules/node-sass/vendor'
I am having an issue running my node application on a different computer than the one I usually use. After a lot of troubleshooting:

The error message I'm getting is:

```<code>Error: ENOENT: no such file or directory, scandir '.../node_modules/node-sass/vendor'
</code>```

A posting that I was reading suggested that I run sudo npm install -g node-sass, which gives me the following error:

```<code>Error: EACCES: permission denied, mkdir '...nvm/versions/node/v8.9.0/lib/node_modules/node-sass/build'
</code>```

I then tried to run sudo npm rebuild node-sass but I'm getting the same error message:

```<code>Error: EACCES: permission denied, mkdir '.../node_modules/node-sass/build'
</code>```

I then ran sudo npm install -g node-sass --unsafe-perm=true --allow-root but it also didn't work:

```<code>ENOENT: no such file or directory, scandir '.../node_modules/node-sass/vendor'
</code>```

What am I doing wrong here? Why isn't node-sass working? Why isn't sudo working properly?

答: Your user does not has the rights to write in the folder you are trying. You are using 3 ... so it goes to the folder /Users on the second one you have ...nvm/versions/node/v8.9.0/lib/node_modules

Body:
I am having an issue running my node application on a different computer than the one I usually use. After a lot of troubleshooting:

The error message I'm getting is:

Error: ENOENT: no such file or directory, scandir '.../node_modules/node-sass/vendor'

A posting that I was reading suggested that I run sudo npm install -g node-sass, which gives me the following error:

Error: EACCES: permission denied, mkdir '...nvm/versions/node/v8.9.0/lib/node_modules/node-sass/build'

I then tried to run sudo npm rebuild node-sass but I'm getting the same error message:

Error: EACCES: permission denied, mkdir '.../node_modules/node-sass/build'

I then ran sudo npm install -g node-sass --unsafe-perm=true --allow-root but it also didn't work:

ENOENT: no such file or directory, scandir '.../node_modules/node-sass/vendor'

What am I doing wrong here? Why isn't node-sass working? Why isn't sudo working properly?


问:
Apache POI replaceText() side effect, changes line space
I am using POI 3.15 in Java to replace some text in my .doc template.

```<code>private HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText) {
    Range r = doc.getRange();
    for (int i = 0; i < r.numSections(); ++i) {
        Section s = r.getSection(i);
        for (int j = 0; j < s.numParagraphs(); j++) {
            Paragraph p = s.getParagraph(j);
            for (int k = 0; k < p.numCharacterRuns(); k++) {
                CharacterRun run = p.getCharacterRun(k);
                String text = run.text();
                if (text.contains(findText)) {
                    run.replaceText(findText, replaceText);
                }
            }
        }
    }
    return doc;
}
</code>```

After I save the document. All content inside are correct. But the style of the document is not. The space between lines is changed. The original gap between lines is missing. All line are closely packed together.

Why? How do I keep the style of my template?

答:
The HWPF library may not support all features, which exist in your doc file and this may result in changed formats. It may also result in unreadable files.

Some years ago I created a customized HWPF library, which could properly modify and write a wide variety of doc files for one of my clients and I gained a lot of experience about the doc file format and the HWPF library.

The problem is, that one has to properly support all features in HWPF, which may be present in the doc file. For instance, if clipart is included in the file, there will be separate tables, which maintain position and properties of the cliparts. If the content (text) is changed without adjusting the addresses in the other internal tables, formats etc. can be shifted, ignored or lost. (or in worst case, the document is unreadable)

I am not sure about the status of HWPF these days, but I expect, that it does not fully support the main relevant doc file features.

If you want to use HWPF for modifying / writing doc files, you may succeed with files, which have a reduced "feature set". For instance no tables, no cliparts, no text boxes - things like that. If you need to support almost any document, which a user may provide, I'd recommend to find a different solution.

One option could be to use rtf files, which are named .doc. Or use the XWPF library, which works for .docx files.

Body:
I am using POI 3.15 in Java to replace some text in my .doc template.

private HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText) {
    Range r = doc.getRange();
    for (int i = 0; i < r.numSections(); ++i) {
        Section s = r.getSection(i);
        for (int j = 0; j < s.numParagraphs(); j++) {
            Paragraph p = s.getParagraph(j);
            for (int k = 0; k < p.numCharacterRuns(); k++) {
                CharacterRun run = p.getCharacterRun(k);
                String text = run.text();
                if (text.contains(findText)) {
                    run.replaceText(findText, replaceText);
                }
            }
        }
    }
    return doc;
}

After I save the document. All content inside are correct. But the style of the document is not. The space between lines is changed. The original gap between lines is missing. All line are closely packed together.

Why? How do I keep the style of my template?


问:
How to ensure a chrome extension does not just work on local HTML files
I have been working on a chrome extension which is intended in part to pull public data from certain pages with at a domain similar to https://secure.state.gov/. For development, I have saved some of the HTML files locally and have been testing with those. Now that I have it working, I would like to try the extension with some live public pages. But when I click the extension at that domain, all that appears is the default google extension menu, and not the popup.html that I created which works local pages. This behavior is the same on any webpage other than the local HTML pages.

In the manifest file, I have tried adding "" to both permissions and content_scripts.

```<code>    "name": "APPNAME!",
    "version": "1.0",
    "description": "DESCRIPTION REDACTED!",
    "permissions": ["activeTab", "declarativeContent", "storage" , "*://secure.state.gov/*", "<all_urls>"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "options_page": "formMenu.html",
    "page_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/get_started16.png",
        "32": "images/get_started32.png",
        "48": "images/get_started48.png",
        "128": "images/get_started128.png"
      }
    },
    "icons": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    },
    "manifest_version": 2,
    "content_security_policy": "script-src 'self' https://code.jquery.com https://cdnjs.cloudflare.com https://stackpath.bootstrapcdn.com https://use.fontawesome.com; object-src 'self'",
    "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["payload.js"],
      "run_at": "document_end"
  } ]
  }
</code>```

No error messages result. I simply get the default extension menu ("This site can read and change site data >", "Options", "Remove from Chrome", "Hide in Chrome Menu", "Manage Extensions", Inspect Popup)

答:
To set up your Chrome extension for testing with local HTML files, and with particular domains, set it up your background.js file as follows:

'use strict';

chrome.runtime.onInstalled.addListener(function() {

  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([{
      conditions: [
        new chrome.declarativeContent.PageStateMatcher({
          pageUrl: {
            hostEquals: ''
          },
        }),
        new chrome.declarativeContent.PageStateMatcher({
          pageUrl: {
            hostContains: 'secure.state.gov'
          },
        })
      ],
      actions: [new chrome.declarativeContent.ShowPageAction()]
    }]);
  });
});```

Body:
I have been working on a chrome extension which is intended in part to pull public data from certain pages with at a domain similar to https://secure.state.gov/. For development, I have saved some of the HTML files locally and have been testing with those. Now that I have it working, I would like to try the extension with some live public pages. But when I click the extension at that domain, all that appears is the default google extension menu, and not the popup.html that I created which works local pages. This behavior is the same on any webpage other than the local HTML pages.

In the manifest file, I have tried adding "" to both permissions and content_scripts.

    "name": "APPNAME!",
    "version": "1.0",
    "description": "DESCRIPTION REDACTED!",
    "permissions": ["activeTab", "declarativeContent", "storage" , "*://secure.state.gov/*", "<all_urls>"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "options_page": "formMenu.html",
    "page_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/get_started16.png",
        "32": "images/get_started32.png",
        "48": "images/get_started48.png",
        "128": "images/get_started128.png"
      }
    },
    "icons": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    },
    "manifest_version": 2,
    "content_security_policy": "script-src 'self' https://code.jquery.com https://cdnjs.cloudflare.com https://stackpath.bootstrapcdn.com https://use.fontawesome.com; object-src 'self'",
    "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["payload.js"],
      "run_at": "document_end"
  } ]
  }

No error messages result. I simply get the default extension menu ("This site can read and change site data >", "Options", "Remove from Chrome", "Hide in Chrome Menu", "Manage Extensions", Inspect Popup)


问:
Transactional error while commiting
I am trying to solve this error in Payara41 server Java EE 7, this sample works on WildFly-9 Java 7 EE and on Glassfish-3.1 Java EE 6 (without @Transactional and @TransactionalManagement)

```<code>@Stateful
@Transactional  //default TxType.REQUIRED
@TransactionManagement(TransactionManagementType.BEAN)
public class ImprovementDaoImpl extends AbstractBaseDaoClass implements ImprovementDao {

    /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    @PersistenceContext(unitName = "pu", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @Resource
    private UserTransaction tx;
...
}
</code>```

Here's some stacktrace, what apperas after executing tx.flush();:

javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRED encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
(...)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.

So far I've tried to use interceptor and @TransactionAttribute, but none helped...

Thanks for any advice/help! :)

答:
I know this is old, but hopefully this helps someone out there...

Question 21363423: Throwing an application exception causes TransactionalException says

You are throwing an exception from a method whose invocation will be
  intercepted at runtime and additional logic wrapped around it:

```<code>transaction management;
exception handling.
</code>```

Your exception cannot transparently jump over that logic, and the
  specification (probably) says a TransactionalException will be thrown,
  wrapping your original exception...

Question 18888572: How do you find out what Exception caused the CDI Transaction Rollback?

Shows how to use a CDI Interceptor to catch the exceptions.  I can't tell from the limited info from the OP what his/her specific issue is, but when I received this exception I has to review the WebLogic server log and found the entry where it told me a unique contraint was violated..  Time to add some interceptors...

Title: Transactional error while commiting

Body:
I am trying to solve this error in Payara41 server Java EE 7, this sample works on WildFly-9 Java 7 EE and on Glassfish-3.1 Java EE 6 (without @Transactional and @TransactionalManagement)

@Stateful
@Transactional  //default TxType.REQUIRED
@TransactionManagement(TransactionManagementType.BEAN)
public class ImprovementDaoImpl extends AbstractBaseDaoClass implements ImprovementDao {

    /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    @PersistenceContext(unitName = "pu", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @Resource
    private UserTransaction tx;
...
}

Here's some stacktrace, what apperas after executing tx.flush();:

javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRED encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
(...)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.

So far I've tried to use interceptor and @TransactionAttribute, but none helped...

Thanks for any advice/help! :)

Body:
I know this is old, but hopefully this helps someone out there...

Question 21363423: Throwing an application exception causes TransactionalException says

You are throwing an exception from a method whose invocation will be
  intercepted at runtime and additional logic wrapped around it:

transaction management;
exception handling.

Your exception cannot transparently jump over that logic, and the
  specification (probably) says a TransactionalException will be thrown,
  wrapping your original exception...

Question 18888572: How do you find out what Exception caused the CDI Transaction Rollback?

Shows how to use a CDI Interceptor to catch the exceptions.  I can't tell from the limited info from the OP what his/her specific issue is, but when I received this exception I has to review the WebLogic server log and found the entry where it told me a unique contraint was violated..  Time to add some interceptors...


问:
Playframework + Morphia + MongoDb + ElasticSearch = Disater?
Guys I have a couple of questions:

Q1. I am using Play 1.1.1 with the Morphia-MongoDB module and ElasticSearch for Indexing. Has any one tried this?

Q2. For some reason the morphia plugin (versions beta4 & beta5) are erroring out in the ObjectIdBinder class. Apparently it does not like @Override on the bind method. Has anyone else faced this? What is the fix?

答:
Never tried ElasticSearch before.

To answer your Q2, do you mean you are using morphia beta4 & 5 with play-1.1.1? could you please try the new morhpia beta6?


问:
Perform action when click anywhere else
If I have a div with a class
Then how to perform an action by clicking anywhere else except the specified class
Using jquery </p>

答:
You would probably want to use the not selector: https://api.jquery.com/not-selector. For example:

$(':not(.class)').click(function(){
  //logic
});
```

Title: Perform action when click anywhere else


问:
Change text of local notification in Swift
I developp an application for student. He can create his timetable.
I tried to create a notification how summarize the next day. So I need to change the text notification, how can I do that?

Another example, the student can write his homework. One day before to return the homework, notify him.

I'have already tried to do a simple notification, but the text of the notification is static.

```<code>let content = UNMutableNotificationContent()
content.title = "Changement de semaine"
content.body = "Nous sommes en semaine \(notificationSemaineAB())"
content.sound = UNNotificationSound.default

var dateComponent = DateComponents()
dateComponent.weekday = 2
dateComponent.hour = 11

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)

let request = UNNotificationRequest(identifier: "semaineAB", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
</code>```

For this one, I would like for each week, the text of notification tell me if we are in a even week or odd week. But in output, I have always the same text.

答: You can create a custom class that extends UNMutableNotificationContent. That will determine the content of the notification based on the even/odd week. Then you can use another class to instantiate the notification request usign a method of the class of type UNMutableNotificationContent.</p>

Body:
I developp an application for student. He can create his timetable.
I tried to create a notification how summarize the next day. So I need to change the text notification, how can I do that?

Another example, the student can write his homework. One day before to return the homework, notify him.

I'have already tried to do a simple notification, but the text of the notification is static.

let content = UNMutableNotificationContent()
content.title = "Changement de semaine"
content.body = "Nous sommes en semaine \(notificationSemaineAB())"
content.sound = UNNotificationSound.default

var dateComponent = DateComponents()
dateComponent.weekday = 2
dateComponent.hour = 11

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)

let request = UNNotificationRequest(identifier: "semaineAB", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

For this one, I would like for each week, the text of notification tell me if we are in a even week or odd week. But in output, I have always the same text.


问:
Round a double to x significant figures
If I have a double (234.004223), etc., I would like to round this to x significant digits in C#.

So far I can only find ways to round to x decimal places, but this simply removes the precision if there are any 0s in the number.

For example, 0.086 to one decimal place becomes 0.1, but I would like it to stay at 0.08.

答:
I agree with the spirit of Jon's assessment:

Awful as it sounds, converting to a number of significant digits as a string by converting the number to a "full" string and then finding the first significant digit (and then taking appropriate rounding action after that) may well be the best way to go.

I needed significant-digit rounding for approximate and non-performance-critical computational purposes, and the format-parse round-trip through "G" format is good enough:

```<code>public static double RoundToSignificantDigits(this double value, int numberOfSignificantDigits)
{
    return double.Parse(value.ToString("G" + numberOfSignificantDigits));
}
</code>```

OwnerDisplayName: Rocco

Title: Round a double to x significant figures

Body:
I agree with the spirit of Jon's assessment:

Awful as it sounds, converting to a number of significant digits as a string by converting the number to a "full" string and then finding the first significant digit (and then taking appropriate rounding action after that) may well be the best way to go.

I needed significant-digit rounding for approximate and non-performance-critical computational purposes, and the format-parse round-trip through "G" format is good enough:

public static double RoundToSignificantDigits(this double value, int numberOfSignificantDigits)
{
    return double.Parse(value.ToString("G" + numberOfSignificantDigits));
}


问:
How to include (source) R script in other scripts
I've created a utility R script, util.R, which I want to use from other scripts in my project.
What is the proper way to ensure that the function this script defines are available to function in my other scripts?

I'm looking for something similar to the require function, that loads a package only if it has not been loaded yet. I don't want to call source("util.R") because that will load the script every time it is called.

I know that I will get some answers telling me to create a package, as in Organizing R Source Code :)
But I'm not creating something that will be used elsewhere, it is just a standalone project.

答:
I solved my problem using entire address where my code is:
Before:

```<code>if(!exists("foo", mode="function")) source("utils.r")
</code>```

After:

```<code>if(!exists("foo", mode="function")) source("C:/tests/utils.r")
</code>```

Body:
I solved my problem using entire address where my code is:
Before:

if(!exists("foo", mode="function")) source("utils.r")

After:

if(!exists("foo", mode="function")) source("C:/tests/utils.r")


问:
How to convert JQuery to vanilla Javascript
I'm trying to convert the below JQuery code to a vanilla Javascript version, but got stuck on the loop. This is my current try:

Javascript:

```<code>var x = document.getElementById("Table1"), d = x.getElementByTagName("td");

for (let row of x.rows)
{
    for(let cell of row.cells)
    {
        var td_content = $(this).text();

        if (td_content != "") {
            hide = false;
        }
    }
}
</code>```

And below is the original JQuery code I'm trying to convert.

JQuery:

```<code>$('#Table1 td').each(function()
{
    var td_content = $(this).text();

    if (td_content != "") {
        hide = false;
    }
})
</code>```

答:
I'd use document.querySelectorAll for easy conversion to vanilla JS.

```<code>var hide = true;
var cells = document.querySelectorAll('#Table1 td');
cells.forEach(function(cell) {
  if (cell.innerText !== '') {
    hide = false;
  }
});
console.log(hide);
</code>```

Body:
I'm trying to convert the below JQuery code to a vanilla Javascript version, but got stuck on the loop. This is my current try:

Javascript:

var x = document.getElementById("Table1"), d = x.getElementByTagName("td");

for (let row of x.rows)
{
    for(let cell of row.cells)
    {
        var td_content = $(this).text();

        if (td_content != "") {
            hide = false;
        }
    }
}

And below is the original JQuery code I'm trying to convert.

JQuery:

$('#Table1 td').each(function()
{
    var td_content = $(this).text();

    if (td_content != "") {
        hide = false;
    }
})

Body:
I'd use document.querySelectorAll for easy conversion to vanilla JS.

var hide = true;
var cells = document.querySelectorAll('#Table1 td');
cells.forEach(function(cell) {
  if (cell.innerText !== '') {
    hide = false;
  }
});
console.log(hide);


问:
Jest "No tests found, exiting with code 1" error on Windows 10 in React Redux application
I am attempting to run Jest on my project. I am on a Windows 10. I only have one test in one test file.

In package.json:

```<code>    "test": "jest"
</code>```

My directory structure:

```<code>    src/
        app/
            routeName/
                redux/
                    action.tests.js
</code>```

My output:

```<code>No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\myUsername\Documents\myApp
  47 files checked.
  testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 0 matches
  testPathIgnorePatterns: \\node_modules\\ - 47 matches
  testRegex:  - 0 matches
Pattern:  - 0 matches
npm ERR! Test failed.  See above for more details.
</code>```

According to the documentation here, Jest should look for anything that has test.js in the name.

I have also tried tests.js and that didn't work either.

I created a folder in the root of the project and put a test in there as __tests__/tests.js and that did work, but I do not want it placed there.

I have seen several tickets and questions about questions that are superficially similar, but all of those involve more complex configurations, or bugs that were supposedly patched already. I have no special configurations set. The documentation says this should work. Tutorials I have read for Jest include the exact setup I am currently using.

I am using Babel and Webpack. I installed the jest and babel-jest packages. I also added jest to the ESLint environment.

[edit] updated to properly document my problem, which I answered below. I lost track of my file naming.

答:
I am a bloody idiot and I didn't pay attention to the details.

Jest is looking for test.js specifically. Not testS.js. My files were labeled as tests.js. It worked inside __tests__/ because Jest just looks for anything inside there.

I got it working just fine now, and it shall remain up as a testament to me not looking at the specifics of the regex matches.

Body:
I am attempting to run Jest on my project. I am on a Windows 10. I only have one test in one test file.

In package.json:

    "test": "jest"

My directory structure:

    src/
        app/
            routeName/
                redux/
                    action.tests.js

My output:

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\myUsername\Documents\myApp
  47 files checked.
  testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 0 matches
  testPathIgnorePatterns: \\node_modules\\ - 47 matches
  testRegex:  - 0 matches
Pattern:  - 0 matches
npm ERR! Test failed.  See above for more details.

According to the documentation here, Jest should look for anything that has test.js in the name.

I have also tried tests.js and that didn't work either.

I created a folder in the root of the project and put a test in there as __tests__/tests.js and that did work, but I do not want it placed there.

I have seen several tickets and questions about questions that are superficially similar, but all of those involve more complex configurations, or bugs that were supposedly patched already. I have no special configurations set. The documentation says this should work. Tutorials I have read for Jest include the exact setup I am currently using.

I am using Babel and Webpack. I installed the jest and babel-jest packages. I also added jest to the ESLint environment.

[edit] updated to properly document my problem, which I answered below. I lost track of my file naming.


问:
show page as a popup
is there any solution that when i acces a normal page it will be loaded in a popup if the user has javascript activated?
So,can i make a normal page a popup? Using a jquery plugin for example?

Thank you!

答: shadowbox and fancybox are two of my favorites, free for non-commercial use, and not too expensive otherwise. Look at the 'iframe' options for a popup page.</p>

Title: show page as a popup


问:
Error Code: 1292 Truncated incorrect datetime value
```<code>insert into test_date
select
    shopify_update
from `vw_shopify_json_price`
where cache_id=669
</code>```

Error Code: 1292
  Truncated incorrect datetime value: '2019-05-17T11:34:30-04:00'

```<code>CREATE TABLE `test_date` (
  `t` datetime DEFAULT NULL
)
</code>```

答:
datetime does not allow a timezone or timezone offset. Some reasonable choices:

convert the timestamp to UTC and store that (my recommendation)

convert the timestamp to the timezone of your database and store that

Body:
insert into test_date
select
    shopify_update
from `vw_shopify_json_price`
where cache_id=669

Error Code: 1292
  Truncated incorrect datetime value: '2019-05-17T11:34:30-04:00'

CREATE TABLE `test_date` (
  `t` datetime DEFAULT NULL
)


问:
why msg box is not working when i try to run a loop with VBA
I'm trying to run a loop to test if the length of strings in a column have at least ten characters. I debugged and there was no problem. However, I tested it with a string with less than 10 characters, the msg box wouldn't pop up. I am very new to VBA so could anyone please point out what my problem is? Thank you so much.

Sub MsgBoxforLenLessThanTen()

    Dim wsData As Worksheet
    Set wsData = Worksheets("Sheet1")
    lastRow = ActiveSheet.UsedRange.Rows.count

    Dim i As Integer
    Dim length As Integer

    i = 1
    With wsData.Range("A1:A" & lastRow)
        Do Until i > lastRow
            length = Len(Range("A1").Offset(0, 1))
            If length < 10 Then MsgBox "not enough characters"
            i = i + 1
            Loop
    End With

End Sub
```

答:
Please see below your corrected code, checking column "A" though. See comments for further details:

Option Explicit 'always use this, it will enforce you to declare your variables, which is well.. important.

Sub MsgBoxforLenLessThanTen()

    Dim wsData As Worksheet
    Set wsData = Worksheets("Sheet1")

    Dim lastRow As Long 'Declare your variable
    lastRow = wsData.UsedRange.Rows.Count 'You've declared your variable above for the sheet, use it

    Dim i As Integer
    Dim length As Integer
    Dim msgValue As String: msgValue = "Not enough characters"

    'try the for loop, is much easier
    With wsData
        For i = 1 To lastRow
            length = Len(.Cells(i, "A"))
            If length < 10 Then
                'MsgBox msgValue
                'Debug.Print msgValue & " at: " & .Cells(i, "A").Address
                .Cells(i, "B").Value = msgValue
            Else
                'do something else
            End If
        Next i
    End With
End Sub
```

EDIT: changed msgbox output to column B instead. I recommend you reading about the Immediate Window and Locals Window, they help massively in debugging your code, especially when you step through (F8).

Body:
Please see below your corrected code, checking column "A" though. See comments for further details:

Option Explicit 'always use this, it will enforce you to declare your variables, which is well.. important.

Sub MsgBoxforLenLessThanTen()

    Dim wsData As Worksheet
    Set wsData = Worksheets("Sheet1")

    Dim lastRow As Long 'Declare your variable
    lastRow = wsData.UsedRange.Rows.Count 'You've declared your variable above for the sheet, use it

    Dim i As Integer
    Dim length As Integer
    Dim msgValue As String: msgValue = "Not enough characters"

    'try the for loop, is much easier
    With wsData
        For i = 1 To lastRow
            length = Len(.Cells(i, "A"))
            If length < 10 Then
                'MsgBox msgValue
                'Debug.Print msgValue & " at: " & .Cells(i, "A").Address
                .Cells(i, "B").Value = msgValue
            Else
                'do something else
            End If
        Next i
    End With
End Sub

EDIT: changed msgbox output to column B instead. I recommend you reading about the Immediate Window and Locals Window, they help massively in debugging your code, especially when you step through (F8).


问:
Why does this if-statement combining assignment and an equality check return true?
I've been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

```<code>int i = 0;
if (i = 1 && i == 0) {
    std::cout << i;
}
</code>```

I have seen that the if statement returns true, and it cout's i as 1. If i is assigned 1 in the if statement, why did i == 0 return true?

答:
The actual answer is:

The compiler gives precedence to "i == 0", which evaluates to true.

Then it will evaluate i=1 as TRUE or FALSE, and since compiled assignment operators never fail (otherwise they wouldn't compile), it also evaluates to true.

Since both statements evaluate as true, and TRUE && TRUE evaluates to TRUE, the if statement will evaluate to TRUE.

As proof, just look at the asm output of your compiler for the code you entered (all comments are my own):

```<code>mov     dword ptr [rbp - 8], 0    ; i = 0;
cmp     dword ptr [rbp - 8], 0    ; i == 0?
sete    al                        ; TRUE (=1)
mov     cl, al
and     cl, 1                     ; = operator always TRUE
movzx   edx, cl
mov     dword ptr [rbp - 8], edx  ; set i=TRUE;
test    al, 1                     ; al never changed,
                                  ; so final ans is TRUE
</code>```

The asm output above was from CLANG, but all other compilers I looked at gave similar output. This is true for all the compilers on that site, whether they are pure C or C++ compilers, all without any pragmas to change the mode of the compiler (which by default is C++ for the C++ compilers)

Note that your compiler did not actually set i=1, but i=TRUE (which means any 32-bit not zero integer value). That's because the && operator only evaluates whether a statement is TRUE or FALSE, and then sets the results according to that result. As proof, try changing i=1 to i=2 and you can observe for yourself that nothing will change. See for yourself using any online compiler at Compiler Explorer

Body:
I've been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

int i = 0;
if (i = 1 && i == 0) {
    std::cout << i;
}

I have seen that the if statement returns true, and it cout's i as 1. If i is assigned 1 in the if statement, why did i == 0 return true?

Body:
The actual answer is:

The compiler gives precedence to "i == 0", which evaluates to true.

Then it will evaluate i=1 as TRUE or FALSE, and since compiled assignment operators never fail (otherwise they wouldn't compile), it also evaluates to true.

Since both statements evaluate as true, and TRUE && TRUE evaluates to TRUE, the if statement will evaluate to TRUE.

As proof, just look at the asm output of your compiler for the code you entered (all comments are my own):

mov     dword ptr [rbp - 8], 0    ; i = 0;
cmp     dword ptr [rbp - 8], 0    ; i == 0?
sete    al                        ; TRUE (=1)
mov     cl, al
and     cl, 1                     ; = operator always TRUE
movzx   edx, cl
mov     dword ptr [rbp - 8], edx  ; set i=TRUE;
test    al, 1                     ; al never changed,
                                  ; so final ans is TRUE

The asm output above was from CLANG, but all other compilers I looked at gave similar output. This is true for all the compilers on that site, whether they are pure C or C++ compilers, all without any pragmas to change the mode of the compiler (which by default is C++ for the C++ compilers)

Note that your compiler did not actually set i=1, but i=TRUE (which means any 32-bit not zero integer value). That's because the && operator only evaluates whether a statement is TRUE or FALSE, and then sets the results according to that result. As proof, try changing i=1 to i=2 and you can observe for yourself that nothing will change. See for yourself using any online compiler at Compiler Explorer


问:
how to select from database using an array in condition in laravel
I have an array called $slugs and I need to receive  data form database table called posts in single array how to archive that ?</p>

答:
If am getting this right? You need to fetch your posts to an array called $slugs.
Simply: </p>

```<code>$slugs = Posts::all()->toArray();
</code>```

Body:
If am getting this right? You need to fetch your posts to an array called $slugs.
Simply:

$slugs = Posts::all()->toArray();


问:
How to resize column in row for responsive screen?
I am build app landing page in Flutter for web. I need make page responsive for different screen size.

I am use MediaQuery for change layout for small screen so widget are layout vertical.

But for medium size screen layout is horizontal. So I need resize app screenshot when screen is make smaller. How to do?

For example: reflectly.app

Here my code so far:

```<code>Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  CenterText(),
                                  SizedBox(height: 10),
                                  Row(
                                    children: <Widget>[
                                      DownloadButtons()                                    ],
                                  ),
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  Screenshot(),
                                ],
                              ),
                            ],
                          )
</code>```

答:
You need to know the LayoutBuilder component, which is what you want and fixes your needs.

LayoutBuilder takes two parameters, one is a context, the second is a constraints. With those constraints you can set show different layouts for different screens.

Check this example:

```<code>LayoutBuilder(
        builder: (context, constraints) {
          if(constraints.maxHeight < 768 && constraints.maxWidth < 1270) {
            return smallDesignContent();
          } else {
            return bigDefaultDesignContent();
          }
        },
      )
</code>```

Flutter Widget of the Week - Layout Builder

Documentation

Body:
I am build app landing page in Flutter for web. I need make page responsive for different screen size.

I am use MediaQuery for change layout for small screen so widget are layout vertical.

But for medium size screen layout is horizontal. So I need resize app screenshot when screen is make smaller. How to do?

For example: reflectly.app

Here my code so far:

Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  CenterText(),
                                  SizedBox(height: 10),
                                  Row(
                                    children: <Widget>[
                                      DownloadButtons()                                    ],
                                  ),
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  Screenshot(),
                                ],
                              ),
                            ],
                          )

Body:
You need to know the LayoutBuilder component, which is what you want and fixes your needs.

LayoutBuilder takes two parameters, one is a context, the second is a constraints. With those constraints you can set show different layouts for different screens.

Check this example:

LayoutBuilder(
        builder: (context, constraints) {
          if(constraints.maxHeight < 768 && constraints.maxWidth < 1270) {
            return smallDesignContent();
          } else {
            return bigDefaultDesignContent();
          }
        },
      )

Flutter Widget of the Week - Layout Builder

Documentation


问:
How do i get the py file from this?
I have decompiled a .exe compiled.
I got a .pyz file and some other files:

Extracted them and got this:

How am I able to get the .py file from all those .pyc files?

答:
You can decompile .pyc files yes - see these similar questions:

Is it possible to decompile a compiled .pyc file into a .py file?

https://reverseengineering.stackexchange.com/questions/1701/decompiling-pyc-files

The short of it is that you can use a tool to generate .py files from .pyc:
https://github.com/rocky/python-uncompyle6/

Title: How do i get the py file from this?


问:
Can I filter autocomplete suggestions by return type in Eclipse?
When autocompleting method calls in Eclipse, is it possible to filter the list of suggestions  on these criteria :

return type

class implementing the method

i.e. when I type myArrayList. I would like to find methods returning boolean which are inherited from AbstractCollection ?

答:
If you create a local variable and attempt to assign to it, Eclipse puts the matching return types first in the autocomplete list, e.g.

```<code>AbstractCollection obj;
boolean temp = obj.<autocomplete list>
</code>```

If you declare obj as AbstractCollection, you won't see any other methods.

Body:
If you create a local variable and attempt to assign to it, Eclipse puts the matching return types first in the autocomplete list, e.g.

AbstractCollection obj;
boolean temp = obj.<autocomplete list>

If you declare obj as AbstractCollection, you won't see any other methods.


问:
Excel Formula to Match Items Within a Date Range
I'm trying to match a product sale date with the range date of sales. I have the following so far:

```<code>=INDEX(A3,MATCH(1,((H:H=A3)*(B:B>=I3)*(B:B<=J3)),0))
</code>```

I'm trying to have the formula produce a result if column A matches column H
and if column B is between column I & J, where J may not have occurred yet.

EDIT: column E15 isn't returning any results
See Here

答:
Use this array formula:

```<code>=IF(SUM(($H$3:$H$12=$A3)*($I$3:$I$12<=B3)*(IF($J$3:$J$12<>"",$J$3:$J$12,TODAY()+1)>$B3)),$A$3,"")
</code>```

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Body:
I'm trying to match a product sale date with the range date of sales. I have the following so far:

=INDEX(A3,MATCH(1,((H:H=A3)*(B:B>=I3)*(B:B<=J3)),0))

I'm trying to have the formula produce a result if column A matches column H
and if column B is between column I & J, where J may not have occurred yet.

EDIT: column E15 isn't returning any results
See Here

Body:
Use this array formula:

=IF(SUM(($H$3:$H$12=$A3)*($I$3:$I$12<=B3)*(IF($J$3:$J$12<>"",$J$3:$J$12,TODAY()+1)>$B3)),$A$3,"")

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


问:
Using regular expression extractor to extract a value?
I am trying to extract the value from the following code. Even though my regex expression is fine it is still not extracting the value.

```<code>token" value="(.+?)"
</code>```

this does give me the exact match which I checked using regex101.com

```<code><input type="hidden" name="token" value="GSYGEP2UUWOTMZ2SFV1G5D2M8L247KIG">
</code>```

what the regex expression should be

答:
Your original regular expression is just fine:

```<code>value="(.+?)"
</code>```

It might be additional spaces, or code problems with it. Let's remove the token" or try to escape ", if necessary.

DEMO 1

DEMO 2

Reference:

Regular Expressions

Body:
I am trying to extract the value from the following code. Even though my regex expression is fine it is still not extracting the value.

token" value="(.+?)"

this does give me the exact match which I checked using regex101.com

<input type="hidden" name="token" value="GSYGEP2UUWOTMZ2SFV1G5D2M8L247KIG">

what the regex expression should be

Body:
Your original regular expression is just fine:

value="(.+?)"

It might be additional spaces, or code problems with it. Let's remove the token" or try to escape ", if necessary.

DEMO 1

DEMO 2

Reference:

Regular Expressions


问:
Form in a foreach in laravel blade
I have a form in a @foreach loop in laravel blade but now upon load up, I can't submit the first form.

After inspecting, seen that the form tags for the first form aren't added to the file source code.

```<code>@foreach($images as $row)
    <div class="col-md-3">
        <form method="post" id="image_manipulator" action="{{ url('image/delete/'.$row->id) }}" class="delete_confirm">
        {{ csrf_field() }}
        <input type="hidden" name="delete_filename" value="{{ $row->filename }}">
            <button class="btn btn-danger" type="button">
                <i class="fa fa-trash">DELETE</i>
            </button>
        </form>
    </div>
@endforeach
</code>```

for the first image, i the form tags aren't there and hence I can't submit the first form.

答:
A couple of things will help you.

Add type="submit" to your button code instead of type="button"

Give independent names for each of your inputs to prevent collision, e.g.:

```<code><input type="hidden" name="delete_filename-{{$someLoopVar}}" value="{{ $row->filename }}">
</code>```

Title: Form in a foreach in laravel blade

Body:
I have a form in a @foreach loop in laravel blade but now upon load up, I can't submit the first form.

After inspecting, seen that the form tags for the first form aren't added to the file source code.

@foreach($images as $row)

        <form method="post" id="image_manipulator" action="{{ url('image/delete/'.$row->id) }}" class="delete_confirm">
        {{ csrf_field() }}
        <input type="hidden" name="delete_filename" value="{{ $row->filename }}">
            <button class="btn btn-danger" type="button">
                DELETE
            </button>
        </form>

@endforeach

for the first image, i the form tags aren't there and hence I can't submit the first form.

Body:
A couple of things will help you.

Add type="submit" to your button code instead of type="button"

Give independent names for each of your inputs to prevent collision, e.g.:

<input type="hidden" name="delete_filename-{{$someLoopVar}}" value="{{ $row->filename }}">


问:
How to deserialize two different XML types in to one class
I have two different XML documents. Their structure is almost identical, but they have some different elements.

I would like to deserialize the incoming documents in to one class which is a superset of both classes. There is no need to ever serialize the class, I only need to deserialize the documents.

The XML document types have a different root element, lets say the root of the first is <CLASSA>and the other is <CLASSB>.
I am looking for something like this, where both <CLASSA> and <CLASSB> xml documents are mapped to ClassAandB:

```<code>[XmlRoot(ElementName="CLASSA,CLASSB")]
public class ClassAandB {
    [XmlElement(ElementName="syntaxid")]
    public Syntaxid Syntaxid{ get; set; }
    [XmlElement(ElementName="email")]
    public Email Email { get; set; }
    [XmlElement(ElementName="envelope")]
    public Envelope Envelope { get; set; }
    [XmlElement(ElementName="header")]
    public Header Header { get; set; }
}
</code>```

I can then find out which of the two types it is by reading the Syntaxid property. This helps me because a lot of the processing is the same for both types.
Any suggestions how to do this?

答:
I suggest you to remove XmlRoot attribute and use:

```<code>var doc = new XmlDocument();
doc.Load("file.xml");
XmlElement root = xmlDoc.DocumentElement;
var serializer = new XmlSerializer(typeof(ClassAandB), new XmlRootAttribute(root.ToString()));
</code>```

Body:
I have two different XML documents. Their structure is almost identical, but they have some different elements.

I would like to deserialize the incoming documents in to one class which is a superset of both classes. There is no need to ever serialize the class, I only need to deserialize the documents.

The XML document types have a different root element, lets say the root of the first is <CLASSA>and the other is <CLASSB>.
I am looking for something like this, where both <CLASSA> and <CLASSB> xml documents are mapped to ClassAandB:

[XmlRoot(ElementName="CLASSA,CLASSB")]
public class ClassAandB {
    [XmlElement(ElementName="syntaxid")]
    public Syntaxid Syntaxid{ get; set; }
    [XmlElement(ElementName="email")]
    public Email Email { get; set; }
    [XmlElement(ElementName="envelope")]
    public Envelope Envelope { get; set; }
    [XmlElement(ElementName="header")]
    public Header Header { get; set; }
}

I can then find out which of the two types it is by reading the Syntaxid property. This helps me because a lot of the processing is the same for both types.
Any suggestions how to do this?

Body:
I suggest you to remove XmlRoot attribute and use:

var doc = new XmlDocument();
doc.Load("file.xml");
XmlElement root = xmlDoc.DocumentElement;
var serializer = new XmlSerializer(typeof(ClassAandB), new XmlRootAttribute(root.ToString()));


问:
Set filter options on vue-good-table programmatically
How can one change the value that is displayed in the UI filter elements(input, dropdown etc)  in vue-good-table programmatically?

For example if I call:
this.$set(this.table.columnsFilters, 'name', 'bob')

I want the value in the HTML input field 'name' to display bob.

Unfortunatly the settting the values as i described above does not work

答:
Edit If you are using version 2.16.0 or above, you'll need to do this:

CodePen for v2.16.0 +

```<code>// v2.16.0 or higher
...
changeFilter(field, newFilter) {
      let newCols = JSON.parse(JSON.stringify(this.columns));
      let found = newCols.find(c => {
        return c.field == field;
      });
      console.log(found);
      if (found) {
        if (found.hasOwnProperty("filterOptions")) {
            found.filterOptions.filterValue = newFilter;
            this.columns = newCols;
        } else {
          alert(`Column '${field}' does not have filtering configured!`);
        }
      } else {
        alert(`Field '${field}' does not exist!`);
      }
}
</code>```

Original Answer

If I am understanding this correctly you want to set the filter for a field programmatially... Something like this should work.. Click the button to change the filter programamaticlly... If you change this line to any valid name, it will filter by that name... Change 'Bob' to a valid name...(like Dan)...

```<code><button
  style="width:200px;"
  @click.stop="changeFilter('name', 'Bob')"
>Click To Change Name Filter</button>
</code>```

CodePen Mirror

const vm = new Vue({
  el: "#app",
  name: "my-component",
  data: {
    columns: [
      {
        label: "Name",
        field: "name",
        filterOptions: {
          enabled: true, // enable filter for this column
          placeholder: "Filter Name", // placeholder for filter input
          filterValue: "", // initial populated value for this filter
          filterDropdownItems: [], // dropdown (with selected values) instead of text input
          filterFn: this.columnFilterFn, //custom filter function that
          trigger: "enter" //only trigger on enter not on keyup
        }
      },
      {
        label: "Age",
        field: "age",
        type: "number"
      },
      {
        label: "Created On",
        field: "createdAt",
        type: "date",
        dateInputFormat: "YYYY-MM-DD",
        dateOutputFormat: "MMM Do YY"
      },
      {
        label: "Percent",
        field: "score",
        type: "percentage"
      }
    ],
    rows: [
      {
        id: 1,
        name: "John",
        age: 20,
        createdAt: "201-10-31:9: 35 am",
        score: 0.03343
      },
      {
        id: 2,
        name: "Jane",
        age: 24,
        createdAt: "2011-10-31",
        score: 0.03343
      },
      {
        id: 3,
        name: "Susan",
        age: 16,
        createdAt: "2011-10-30",
        score: 0.03343
      },
      {
        id: 4,
        name: "Bob",
        age: 55,
        createdAt: "2011-10-11",
        score: 0.03343
      },
      {
        id: 5,
        name: "Dan",
        age: 40,
        createdAt: "2011-10-21",
        score: 0.03343
      },
      {
        id: 6,
        name: "John",
        age: 20,
        createdAt: "2011-10-31",
        score: 0.03343
      }
    ]
  },
  methods: {
    clearFilter(field) {
      try {
        let found = this.columns.find((c) => {
          return c.field == field
        });
        found.filterOptions.filterValue = "";
      } catch {
        alert(`Unable to clear ${field} filter`)
      }
    },
    changeFilter(field, newFilter) {
      let found = this.columns.find((c) => {
        return c.field == field
      });
      if(found) {
        if(found.hasOwnProperty("filterOptions")) {
          if(found.filterOptions.hasOwnProperty("filterValue")) {
            found.filterOptions.filterValue = newFilter;
          } else {
            alert(`Column '${field}' does not have filterValue property!`)
          }
        } else {
          alert(`Column '${field}' does not have filtering configured!`)
        }
      } else {
        alert(`Field '${field}' does not exist!`)
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-good-table@2.15.3/dist/vue-good-table.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vue-good-table@2.12.2/dist/vue-good-table.css" rel="stylesheet"/>

<div id="app">
  <div>
    <div style="margin:10px 10px 10px 10px;">
      <button
        style="width:200px;"
        @click.stop="changeFilter('name', 'Bob')"
      >Click To Change Name Filter</button>
      <button
        style="width:200px;"
        @click.stop="clearFilter('name')"
      >Clear Name Filter</button>
    </div>
    <vue-good-table :columns="columns" :rows="rows" />
  </div>
</div></code>```

Body:
Edit If you are using version 2.16.0 or above, you'll need to do this:

CodePen for v2.16.0 +

// v2.16.0 or higher
...
changeFilter(field, newFilter) {
      let newCols = JSON.parse(JSON.stringify(this.columns));
      let found = newCols.find(c => {
        return c.field == field;
      });
      console.log(found);
      if (found) {
        if (found.hasOwnProperty("filterOptions")) {
            found.filterOptions.filterValue = newFilter;
            this.columns = newCols;
        } else {
          alert(`Column '${field}' does not have filtering configured!`);
        }
      } else {
        alert(`Field '${field}' does not exist!`);
      }
}

Original Answer

If I am understanding this correctly you want to set the filter for a field programmatially... Something like this should work.. Click the button to change the filter programamaticlly... If you change this line to any valid name, it will filter by that name... Change 'Bob' to a valid name...(like Dan)...

<button
  style="width:200px;"
  @click.stop="changeFilter('name', 'Bob')"
>Click To Change Name Filter</button>

CodePen Mirror

const vm = new Vue({
  el: "#app",
  name: "my-component",
  data: {
    columns: [
      {
        label: "Name",
        field: "name",
        filterOptions: {
          enabled: true, // enable filter for this column
          placeholder: "Filter Name", // placeholder for filter input
          filterValue: "", // initial populated value for this filter
          filterDropdownItems: [], // dropdown (with selected values) instead of text input
          filterFn: this.columnFilterFn, //custom filter function that
          trigger: "enter" //only trigger on enter not on keyup
        }
      },
      {
        label: "Age",
        field: "age",
        type: "number"
      },
      {
        label: "Created On",
        field: "createdAt",
        type: "date",
        dateInputFormat: "YYYY-MM-DD",
        dateOutputFormat: "MMM Do YY"
      },
      {
        label: "Percent",
        field: "score",
        type: "percentage"
      }
    ],
    rows: [
      {
        id: 1,
        name: "John",
        age: 20,
        createdAt: "201-10-31:9: 35 am",
        score: 0.03343
      },
      {
        id: 2,
        name: "Jane",
        age: 24,
        createdAt: "2011-10-31",
        score: 0.03343
      },
      {
        id: 3,
        name: "Susan",
        age: 16,
        createdAt: "2011-10-30",
        score: 0.03343
      },
      {
        id: 4,
        name: "Bob",
        age: 55,
        createdAt: "2011-10-11",
        score: 0.03343
      },
      {
        id: 5,
        name: "Dan",
        age: 40,
        createdAt: "2011-10-21",
        score: 0.03343
      },
      {
        id: 6,
        name: "John",
        age: 20,
        createdAt: "2011-10-31",
        score: 0.03343
      }
    ]
  },
  methods: {
    clearFilter(field) {
      try {
        let found = this.columns.find((c) => {
          return c.field == field
        });
        found.filterOptions.filterValue = "";
      } catch {
        alert(`Unable to clear ${field} filter`)
      }
    },
    changeFilter(field, newFilter) {
      let found = this.columns.find((c) => {
        return c.field == field
      });
      if(found) {
        if(found.hasOwnProperty("filterOptions")) {
          if(found.filterOptions.hasOwnProperty("filterValue")) {
            found.filterOptions.filterValue = newFilter;
          } else {
            alert(`Column '${field}' does not have filterValue property!`)
          }
        } else {
          alert(`Column '${field}' does not have filtering configured!`)
        }
      } else {
        alert(`Field '${field}' does not exist!`)
      }
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-good-table@2.15.3/dist/vue-good-table.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vue-good-table@2.12.2/dist/vue-good-table.css" rel="stylesheet"/>

<div id="app">
  <div>
    <div style="margin:10px 10px 10px 10px;">
      <button
        style="width:200px;"
        @click.stop="changeFilter('name', 'Bob')"
      >Click To Change Name Filter</button>
      <button
        style="width:200px;"
        @click.stop="clearFilter('name')"
      >Clear Name Filter</button>
    </div>
    <vue-good-table :columns="columns" :rows="rows" />
  </div>
</div>


问:
Selecting from a database from Today onwards
Im trying to select a bunch of stuff from a database. Each have a date and i'd like to only display the ones whose date is equal to today onwards.

$sql="SELECT * FROM bs_events WHERE NOW() ORDER BY eventDate ";

I have tried looking everywhere and cannot find anything.

Thanks for any help guys

答:
Important: Using NOW() and CURDATE() does make your query invalid for the query cache. On many request - f.e. the homepage - this could cause performance loss.

I prefer the following snippet:

```<code>$oDate = new DateTime();
$sQuery = "
    SELECT field1, field2
    FROM bs_events
    WHERE eventDate >= '".$oDate->format("Y-m-d H:i")."'
    ORDER BY eventDate
";
</code>```

This will achieve your goal, but will cause the query cache to be used for a full minute. Ofcourse you can tweak this to a larger or smaller amount of time.

Body:
Important: Using NOW() and CURDATE() does make your query invalid for the query cache. On many request - f.e. the homepage - this could cause performance loss.

I prefer the following snippet:

$oDate = new DateTime();
$sQuery = "
    SELECT field1, field2
    FROM bs_events
    WHERE eventDate >= '".$oDate->format("Y-m-d H:i")."'
    ORDER BY eventDate
";

This will achieve your goal, but will cause the query cache to be used for a full minute. Ofcourse you can tweak this to a larger or smaller amount of time.


问:
Codeigniter next_row() returns null
Im trying to get the next row everytim ei run the function but it always returns 0

Model

```<code>function getNextMuziek($id)
    {
        $this->db->where('id', $id);
        $this->db->limit(1);
        $query = $this->db->get('muziek')->num_rows() == 1;
        return $query->next_row();
    }
</code>```

答:
According to the documentation, next_row() is to be used to navigate through a result set. This will not serve your purposes. If you want your function to return the next row after the row specified by $id, the easiest thing would be to use a greater than comparison and return the first row. You could modify your code to

```<code>$query = $this->db->where('id >', $id)->limit(1)->get('muziek');
if ($query->num_rows() == 1) {
    return $query->row();
}
</code>```

Title: Codeigniter next_row() returns null

Body:
Im trying to get the next row everytim ei run the function but it always returns 0

Model

function getNextMuziek($id)
    {
        $this->db->where('id', $id);
        $this->db->limit(1);
        $query = $this->db->get('muziek')->num_rows() == 1;
        return $query->next_row();
    }

Body:
According to the documentation, next_row() is to be used to navigate through a result set. This will not serve your purposes. If you want your function to return the next row after the row specified by $id, the easiest thing would be to use a greater than comparison and return the first row. You could modify your code to

$query = $this->db->where('id >', $id)->limit(1)->get('muziek');
if ($query->num_rows() == 1) {
    return $query->row();
}