问:
GridView ButtonField postback not working in IE7?
I have an ASP.Net Web Site with GridView control that in turn contains a ButtonField column. It's supposed to do a postback when this ButtonField is clicked, but that doesn't happen if I click on the button from within the Internet Explorer window that Visual Studio opens while debugging. I can get it to successfully postback when I bring up and click on the ButtonField from an externally-invoked Internet Explorer window or a Firefox window, but never from the window Visual Studio produces.

I'm using:

Windows Vista Home Premium

Visual Studio 2008, running as Administrator

Internet Explorer 7.0.6000.16809

Firefox 3.0.6

答: I've determined the problem is due to running Visual Studio 2008 as Administrator under Windows Vista. Doing so causes some kind of issue with Javascript that prevents GridView ButtonFields from issuing postbacks. Contrary to Microsoft's advice for the previous version of Visual Studio (2005), debugging with Visual Studio 2008 running under Windows Vista requires that the IDE not be run using "Run as Administrator".

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
java.lang.NoClassDefFoundError with external jars in java applet
I have a Java applet which utilizes multiple external jars.  In Eclipse the project runs fine.  When it is exported and run embedded in a HTML file I get 22 run-time exceptions similar to..

```<code>java.lang.RuntimeException: java.lang.NoClassDefFoundError:
    mil/dcgs/mdf/webservice/ddms/ingest/CatalogIngestService
</code>```

..with various classes.  When I open the exported jar I see no .class files or any other traces from the external jar.

HTML

The HTML is:

```<code><html>
<head>
<title>DIB Applet</title>
</head>
<body>
<applet
    code="org.mitre.inception.Main.class"
    archive="inception.jar"
    WIDTH = "1020"
    HEIGHT = "500">
Applet
</applet>
</body>
</html>
</code>```

.classpath

My .classpath looks like the following.

```<code><?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="lib" path="C:/Users/myUserName/Desktop/jars/dcgs-util.jar"/>
    <!-- more jars removed for space reasons as they look the same as above -->
    <classpathentry kind="output" path="bin"/>
</classpath>
</code>```

答:
The classpath mentions dcgs-util.jar. That should probably be listed in the archive attribute of the applet element.  Perhaps something like:

```<code><html>
<head>
<title>DIB Applet</title>
</head>
<body>
<applet
    code="org.mitre.inception.Main.class"
    archive="inception.jar,jars/dcgs-util.jar"
    WIDTH = "1020"
    HEIGHT = "500">
Applet
</applet>
</body>
</html>
</code>```

That would be assuming inception.jar was in the same directory as the HTML, and that dcgs-util.jar is in the jars sub-directory of the dir. where the HTML is located.

ContentLicense: CC BY-SA 3.0

Body:
I have a Java applet which utilizes multiple external jars.  In Eclipse the project runs fine.  When it is exported and run embedded in a HTML file I get 22 run-time exceptions similar to..

java.lang.RuntimeException: java.lang.NoClassDefFoundError:
    mil/dcgs/mdf/webservice/ddms/ingest/CatalogIngestService

..with various classes.  When I open the exported jar I see no .class files or any other traces from the external jar.

HTML

The HTML is:

<title>DIB Applet</title>

<applet
    code="org.mitre.inception.Main.class"
    archive="inception.jar"
    WIDTH = "1020"
    HEIGHT = "500">
Applet
</applet>

.classpath

My .classpath looks like the following.

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="lib" path="C:/Users/myUserName/Desktop/jars/dcgs-util.jar"/>

    <classpathentry kind="output" path="bin"/>
</classpath>

Body:
The classpath mentions dcgs-util.jar. That should probably be listed in the archive attribute of the applet element.  Perhaps something like:

<html>
<head>
<title>DIB Applet</title>
</head>
<body>
<applet
    code="org.mitre.inception.Main.class"
    archive="inception.jar,jars/dcgs-util.jar"
    WIDTH = "1020"
    HEIGHT = "500">
Applet
</applet>
</body>
</html>

That would be assuming inception.jar was in the same directory as the HTML, and that dcgs-util.jar is in the jars sub-directory of the dir. where the HTML is located.


问:
Custom pagination design on wordpress
now i'm doing wordpress project. i have my own template build with css and html format. the implementation is ok but i'm struggling to integrate WP pagination design to my template.

here's my template pagination code

```<code><div class="page_wrap">
  <ul class="page_list">
    <li class="page_item_prev">
      <a href="column.html">
        <img src="static/images/common/icon_arrow_prev.svg" alt="<">
      </a>
    </li>
    <li class="page_item active">
      <a href="column.html">
        1
      </a>
    </li>
    <li class="page_item">
      <a href="column.html">
        2
      </a>
    </li>
    <li class="page_item">
      <a href="column.html">
        3
      </a>
    </li>
    <li class="dot">
      …
    </li>
    <li class="page_item">
      <a href="column.html">
        10
      </a>
    </li>
    <li class="page_item_next">
      <a href="column.html">
        <img src="static/images/common/icon_arrow_next.svg" alt="＞">
      </a>
    </li>
  </ul>
</div>
</code>```

my template design pagination display like this

and this is how i'm implementing WP pagination. i also build a functions.php.

code on the template

```<code><div class="page_wrap">
  <ul class="page_list">
    <?php list_pagination($loop); ?>
  </ul>
</div>
</code>```

code on functions.php

```<code>function list_pagination($loop)
{
    global $wp_query;
    $big = 99999999;
    $paged = paginate_links(array(
        'base'      => str_replace($big, '%#%', get_pagenum_link($big)),
        'format'    => '?paged=%#%',
        'currenct'  => max(1, get_query_var('paged')),
        'prev_next' => true,
        'prev_text' => __('<img src="'.get_template_directory_uri().'/static/images/common/icon_arrow_prev.svg" alt="＞">'),
        'next_text' => __('<img src="'.get_template_directory_uri().'/static/images/common/icon_arrow_next.svg" alt="＞">'),
        'type'      => 'list',
        'total'     => $loop->max_num_pages
    ));
    echo $paged;
}
</code>```

result like this

and this is wrong.

can i adjust the WP pagination code to follow same as my design?

please help

答:
Adjust your CSS to match the HTML code produced by the paginate_links() function.

Previous Link:

Page Link:

Next Link:

Current Page:

Add display: flex; to

A more complex solution can be found in the Gist here.

ContentLicense: CC BY-SA 4.0

Title: Custom pagination design on wordpress

Body:
now i'm doing wordpress project. i have my own template build with css and html format. the implementation is ok but i'm struggling to integrate WP pagination design to my template.

here's my template pagination code

        <img src="static/images/common/icon_arrow_prev.svg" alt="<">

        1

        2

        3

      …

        10

my template design pagination display like this

and this is how i'm implementing WP pagination. i also build a functions.php.

code on the template

    <?php list_pagination($loop); ?>

code on functions.php

function list_pagination($loop)
{
    global $wp_query;
    $big = 99999999;
    $paged = paginate_links(array(
        'base'      => str_replace($big, '%#%', get_pagenum_link($big)),
        'format'    => '?paged=%#%',
        'currenct'  => max(1, get_query_var('paged')),
        'prev_next' => true,
        'prev_text' => __(''),
        'next_text' => __(''),
        'type'      => 'list',
        'total'     => $loop->max_num_pages
    ));
    echo $paged;
}

result like this

and this is wrong.

can i adjust the WP pagination code to follow same as my design?

please help

Body:
Adjust your CSS to match the HTML code produced by the paginate_links() function.

Previous Link: <a class="prev page-numbers"></a>

Page Link: <a class="page-numbers"></a>

Next Link: <a class="next page-numbers"></a>

Current Page: <span class="page-numbers current"></span>

Add display: flex; to <ul class="page_list"></ul>

A more complex solution can be found in the Gist here.


问:
IndexError: list index out of range (Selenium)
i try to scrap link product in website gramedia bookstore, but I get problem like this

```<code>import selenium
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get('https://www.gramedia.com/categories/buku?based_on=best-seller')
    listOfLinks=[]

    for i in range(3):
        time.sleep(3)
        productInfoList = driver.find_elements_by_class_name('product-list')
        productInfoList[0].text
        for perProduct in productInfoList:
            classPerProduct = perProduct.find_elements_by_tag_name('div')[0]
            linkProduct = classPerProduct.find_element_by_tag_name('a')
            listOfLinks.append(linkProduct.get_property('href'))
        try:
            driver.find_elements_by_class_name('ion-ios-arrow-forward')[1].click()
        except:
            continue

    with open("data_link.txt", "w") as f:
        for s in listOfLinks:
            f.write(str(s) +"\n")
</code>```

I get an error message like this:

```<code>c:\Users\Userz\latihan\scrap.py:6: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(ChromeDriverManager().install())

DevTools listening on ws://127.0.0.1:58426/devtools/browser/a5f69f68-c236-4dd4-9bca-7912a57bb86d
c:\Users\Userz\latihan\scrap.py:12: DeprecationWarning: find_elements_by_* commands are deprecated. Please use find_elements() instead
  productInfoList = driver.find_elements_by_class_name('product-list')
Traceback (most recent call last):
  File "c:\Users\Userz\latihan\scrap.py", line 13, in <module>
    productInfoList[0].text
IndexError: list index out of range
</code>```

Please help me to fix this code

答: product-list class doesn't exist hence productInfoList returns an empty list. that is why you get indexError when you are trying to get 0 index from productInfoList, Try more specific selectors

Body:
i try to scrap link product in website gramedia bookstore, but I get problem like this

import selenium
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get('https://www.gramedia.com/categories/buku?based_on=best-seller')
    listOfLinks=[]

    for i in range(3):
        time.sleep(3)
        productInfoList = driver.find_elements_by_class_name('product-list')
        productInfoList[0].text
        for perProduct in productInfoList:
            classPerProduct = perProduct.find_elements_by_tag_name('div')[0]
            linkProduct = classPerProduct.find_element_by_tag_name('a')
            listOfLinks.append(linkProduct.get_property('href'))
        try:
            driver.find_elements_by_class_name('ion-ios-arrow-forward')[1].click()
        except:
            continue

    with open("data_link.txt", "w") as f:
        for s in listOfLinks:
            f.write(str(s) +"\n")

I get an error message like this:

c:\Users\Userz\latihan\scrap.py:6: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(ChromeDriverManager().install())

DevTools listening on ws://127.0.0.1:58426/devtools/browser/a5f69f68-c236-4dd4-9bca-7912a57bb86d
c:\Users\Userz\latihan\scrap.py:12: DeprecationWarning: find_elements_by_* commands are deprecated. Please use find_elements() instead
  productInfoList = driver.find_elements_by_class_name('product-list')
Traceback (most recent call last):
  File "c:\Users\Userz\latihan\scrap.py", line 13, in <module>
    productInfoList[0].text
IndexError: list index out of range

Please help me to fix this code


问:
Javascript: How to remove empty string values from an array?
I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]```
</div>
</div>
</p>
<p>I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.</p>
<p>I tried this:</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>// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })</code>```

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]```

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.

答:
Replace

```<code>data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })
</code>```

with

```<code>data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.splice(index) // Using splice is enough.
            obj.relevance.splice(index)
            obj.intensity.splice(index)
          }
        })
      })
</code>```

Body:
I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]

I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.

I tried this:

// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.

Body:
Replace

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })

with

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.splice(index) // Using splice is enough.
            obj.relevance.splice(index)
            obj.intensity.splice(index)
          }
        })
      })


问:
Change default location of vimrc
In Vim, is it possible to change the default location of the user vimrc file, i.e., from $HOME/.vimrc to some other location ?</p>

答:
You must start vim with the command vim -u ./path/to/your/vimrcfile

vim -u NONE is a good way to start Vim without any plugin or customisation.

See :help starting.txt for more information.

Title: Change default location of vimrc


问:
How to interpret multicollinearity in a correlation plot?
I created a correlation plot for my dataset in R but I am not sure how to choose which of the following pairs of variables express multicollinearity? An explanation with examples would be really helpful!

答:
Perhaps one way is through a qgraph. First I'll load the Holzinger data from the lavaan package, the correlation function from the correlation package, and the qgraph function with the qgraph package with the following libraries:

```<code>library(correlation)
library(qgraph)
library(lavaan)
</code>```

Create the correlation matrix from the Holzinger data:

```<code>cor_holz <- HolzingerSwineford1939 %>%
  correlation()
</code>```

Then make the qgraph of all the correlations together. The thicker lines are stronger correlations, with green indicating positives and red for negatives. You can see in this graph for example that x4-x6 are highly correlated in the thick green triangle:

```<code>qgraph(cor_holz)
</code>```

Which makes this:

You can fancy it up a bit by establishing cutoffs for correlation values (helpful if you want to pinpoint which have the strongest correlations), add a title, and change the dimensions:

```<code>qgraph(cor_holz, # correlation
       cut=.30, # cutoff value for correlations
       details = T, # shows details
       mar = c(6,10,6,10), # size of graph
       vsize = 8, # size of nodes
       title = "Q Graph of All Correlations") # title
</code>```

A more clear cut example is with the FacialBurns data in the same lavaan package, which shows much more obvious multicollinearity and lack thereof in the respective variables:

```<code>face_cor <- FacialBurns %>%
  correlation()

qgraph(face_cor)
</code>```

Body:
Perhaps one way is through a qgraph. First I'll load the Holzinger data from the lavaan package, the correlation function from the correlation package, and the qgraph function with the qgraph package with the following libraries:

library(correlation)
library(qgraph)
library(lavaan)

Create the correlation matrix from the Holzinger data:

cor_holz <- HolzingerSwineford1939 %>%
  correlation()

Then make the qgraph of all the correlations together. The thicker lines are stronger correlations, with green indicating positives and red for negatives. You can see in this graph for example that x4-x6 are highly correlated in the thick green triangle:

qgraph(cor_holz)

Which makes this:

You can fancy it up a bit by establishing cutoffs for correlation values (helpful if you want to pinpoint which have the strongest correlations), add a title, and change the dimensions:

qgraph(cor_holz, # correlation
       cut=.30, # cutoff value for correlations
       details = T, # shows details
       mar = c(6,10,6,10), # size of graph
       vsize = 8, # size of nodes
       title = "Q Graph of All Correlations") # title

A more clear cut example is with the FacialBurns data in the same lavaan package, which shows much more obvious multicollinearity and lack thereof in the respective variables:

face_cor <- FacialBurns %>%
  correlation()

qgraph(face_cor)


答:
Filters all Falsy values .... :)

const data = [{
        "_id": "plastic",
        "countries": ['Egypt','','Iran'],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia',''],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
 }]

const res = data.map(d => ({ ...d , countries : d.countries.filter(Boolean)}));

console.log(res)```

Title: Javascript: How to remove empty string values from an array?


问:
Can the By strategy tagName be replaced with cssSelector for the same value?
I replaced the locator tagName with cssselector without changing the arguments and the code still worked perfectly.
The previous script was:

```<code>Driver.findElement(By.tagName("*enter tagName*");
</code>```

Replacement code is:

```<code>Driver.findElement(By.cssSelector("*enter tagName*");
</code>```

The code worked despite the fact that I did not use any cssSelector combination.

How is that possible?

答:
This worked correctly since tag name alone is a correct CSS Selector.

Generally CSS Selector is may look like the following: tagName[attributeName='attributeValue'] where you can omit the attribute name and value and locate the element based on tagName only. So tagName lonely will still be a correct CSS Selector.

Body:
I replaced the locator tagName with cssselector without changing the arguments and the code still worked perfectly.
The previous script was:

Driver.findElement(By.tagName("*enter tagName*");

Replacement code is:

Driver.findElement(By.cssSelector("*enter tagName*");

The code worked despite the fact that I did not use any cssSelector combination.

How is that possible?


问:
How do I open my editor while I am selecting a file in project explorer?
When i am selecting a file in the project explorer, it should allow me to open my editor instead it shows text editor.How can we handle this programmatically in eclipse plugin development ?

regards
Mathan

答:
There is also possibility to register your own content type of file. It can be registered as a sub-type of existing content type i.e. XML. To do that you should add an extension point of org.eclipse.core.contenttype.contentTypes

Sample extension point:

```<code><extension
     point="org.eclipse.core.contenttype.contentTypes">
  <content-type
        base-type="org.eclipse.core.runtime.xml"
        default-charset="UTF-8"
        describer="com.example.MyContentDescriber"
        file-extensions="xml"
        id="org.eclipse.core.runtime.xml.exampleContentType"
        name="exampleContentType"
        priority="normal">
  </content-type>
</code>```

As you can see new content type is extending an xml content type. The next step is to implement content describer, which looks into the file and determines if it is of your type. There are two interfaces you can implement to do the job: IContentDescriber or ITextContentDescriber. Path to your implementation of describer must be specified in content type as it is shown in the snippet.

Then your editor can be declared as the one, who will be handling your kind of content types.

```<code><editor class="com.example.MyEditor"
        default="true"
        icon="res/icons/dialog.png"
        id="[some_id]"
        name="Dialog editor">
     <contentTypeBinding
           contentTypeId="org.eclipse.core.runtime.xml.exampleContentType">
     </contentTypeBinding>
  </editor>
</code>```

Important things:

files that have been already opened in eclipse might 'remember' in which editor they were last opened and this one will be chosen,

your describer might be used a lot so you should consider performance issues while implementing it

More in the topic:
ECLIPSE: Contributing content types

OwnerDisplayName: Mathan

Body:
There is also possibility to register your own content type of file. It can be registered as a sub-type of existing content type i.e. XML. To do that you should add an extension point of org.eclipse.core.contenttype.contentTypes

Sample extension point:

<extension
     point="org.eclipse.core.contenttype.contentTypes">
  <content-type
        base-type="org.eclipse.core.runtime.xml"
        default-charset="UTF-8"
        describer="com.example.MyContentDescriber"
        file-extensions="xml"
        id="org.eclipse.core.runtime.xml.exampleContentType"
        name="exampleContentType"
        priority="normal">
  </content-type>

As you can see new content type is extending an xml content type. The next step is to implement content describer, which looks into the file and determines if it is of your type. There are two interfaces you can implement to do the job: IContentDescriber or ITextContentDescriber. Path to your implementation of describer must be specified in content type as it is shown in the snippet.

Then your editor can be declared as the one, who will be handling your kind of content types.

<editor class="com.example.MyEditor"
        default="true"
        icon="res/icons/dialog.png"
        id="[some_id]"
        name="Dialog editor">
     <contentTypeBinding
           contentTypeId="org.eclipse.core.runtime.xml.exampleContentType">
     </contentTypeBinding>
  </editor>

Important things:

files that have been already opened in eclipse might 'remember' in which editor they were last opened and this one will be chosen,

your describer might be used a lot so you should consider performance issues while implementing it

More in the topic:
ECLIPSE: Contributing content types


问:
How to make multi-dementional arrays with array lists wiht axios and vue js
I am quite new to the axios and javascript and I am so confused with making multi-dimentional array.

1. I want my data to look like :

```<code>userList: [
                    {
                        user_no: 1,
                        user_nickname: "hailey",
                    },
                    {
                        user_no: 2,
                        user_nickname: "mandi",
                    },
                    {
                        user_no: 3,
                        user_nickname: "loren",
                    },
                    {
                        user_no: 4,
                        user_nickname: "james",
                    },
],

</code>```

2. But from axios response, I am getting result like this :

```<code>{user_no : 1, user_nickname : "hailey"}
{user_no : 2 , user_nickname : "mandi"}
{user_no : 3 , user_nickname : "loren"}
{user_no : 4 , user_nickname : "james"}
</code>```

How can I wrap those individual lists into multi dimentional array so I can make #2 -> #1 ?
I saw some functions like flat which does the opposite of what I want. So I was wondering if there's any way like those to wrap all arrays with outer array.

答:
I was being stupid.
As the answer above said, there is nothing wrong with my data or code. But when I was getting data, the objects are actually insde the data so the structure was like this :

response.data.data //i was calling it response.data ^^:;
```

Thank you for help :D

Body:
I am quite new to the axios and javascript and I am so confused with making multi-dimentional array.

1. I want my data to look like :

userList: [
                    {
                        user_no: 1,
                        user_nickname: "hailey",
                    },
                    {
                        user_no: 2,
                        user_nickname: "mandi",
                    },
                    {
                        user_no: 3,
                        user_nickname: "loren",
                    },
                    {
                        user_no: 4,
                        user_nickname: "james",
                    },
],

2. But from axios response, I am getting result like this :

{user_no : 1, user_nickname : "hailey"}
{user_no : 2 , user_nickname : "mandi"}
{user_no : 3 , user_nickname : "loren"}
{user_no : 4 , user_nickname : "james"}

How can I wrap those individual lists into multi dimentional array so I can make #2 -> #1 ?
I saw some functions like flat which does the opposite of what I want. So I was wondering if there's any way like those to wrap all arrays with outer array.

Body:
I was being stupid.
As the answer above said, there is nothing wrong with my data or code. But when I was getting data, the objects are actually insde the data so the structure was like this :

response.data.data //i was calling it response.data ^^:;

Thank you for help :D


问:
How to copy a value from one column to a new column if column A > column B?
I am looking to create a new column called true_water_on in the dataframe trial_A.

```<code>  study_ID       randomisation            water_on           water_off
1        5 2021-01-01 11:00:00 2021-01-01 13:00:00 2021-01-01 18:00:00
2        6 2021-01-02 10:00:00 2021-01-02 09:00:00 2021-01-02 18:00:00
3        7 2021-01-03 10:00:00                <NA>                <NA>
4        8 2021-01-04 10:00:00 2021-01-04 09:45:00 2021-01-04 11:00:00
</code>```

The conditions to populate it are as follows

If "water_on" date and time precedes the time and date in "randomisation" then the randomisation data and time for that row is copied across into "true_water_on". This occurs for study_ID 6 and 8; as demonstrated by

```<code>trial_A %>% mutate(TD_ran_waterstart = water_on - randomisation, units="mins")
</code>```

If "water_on" date and time occurs after the time and date in
"randomisation" then the water_on data for that row is copied across
into "water_drug_on"

If there is no data and time recorded in "water_on" then NA is
marked in "true_water_on"

Data

```<code>trial_A <-
  data.frame(study_ID=c(5, 6, 7, 8),
             randomisation=as.POSIXlt(c("2021-01-01 11:00", "2021-01-02 10:00",
                                        "2021-01-03 10:00", "2021-01-04 10:00")),
             water_on=as.POSIXlt(c("2021-01-01 13:00", "2021-01-02 09:00", NA,
                                   "2021-01-04 09:45")),
             water_off=as.POSIXlt(c("2021-01-01 18:00", "2021-01-02 18:00", NA,
                                    "2021-01-04 11:00")))
</code>```

Body:
I am looking to create a new column called true_water_on in the dataframe trial_A.

  study_ID       randomisation            water_on           water_off
1        5 2021-01-01 11:00:00 2021-01-01 13:00:00 2021-01-01 18:00:00
2        6 2021-01-02 10:00:00 2021-01-02 09:00:00 2021-01-02 18:00:00
3        7 2021-01-03 10:00:00                <NA>                <NA>
4        8 2021-01-04 10:00:00 2021-01-04 09:45:00 2021-01-04 11:00:00

The conditions to populate it are as follows

If "water_on" date and time precedes the time and date in "randomisation" then the randomisation data and time for that row is copied across into "true_water_on". This occurs for study_ID 6 and 8; as demonstrated by

trial_A %>% mutate(TD_ran_waterstart = water_on - randomisation, units="mins")

If "water_on" date and time occurs after the time and date in
"randomisation" then the water_on data for that row is copied across
into "water_drug_on"

If there is no data and time recorded in "water_on" then NA is
marked in "true_water_on"

Data

trial_A <-
  data.frame(study_ID=c(5, 6, 7, 8),
             randomisation=as.POSIXlt(c("2021-01-01 11:00", "2021-01-02 10:00",
                                        "2021-01-03 10:00", "2021-01-04 10:00")),
             water_on=as.POSIXlt(c("2021-01-01 13:00", "2021-01-02 09:00", NA,
                                   "2021-01-04 09:45")),
             water_off=as.POSIXlt(c("2021-01-01 18:00", "2021-01-02 18:00", NA,
                                    "2021-01-04 11:00")))

Body:
You could simply use max.

transform(trial_A, true_water_on=apply(trial_A[2:3], 1, max))
#  study_ID       randomisation            water_on           water_off       true_water_on
# 1        5 2021-01-01 11:00:00 2021-01-01 13:00:00 2021-01-01 18:00:00 2021-01-01 13:00:00
# 2        6 2021-01-02 10:00:00 2021-01-02 09:00:00 2021-01-02 18:00:00 2021-01-02 10:00:00
# 3        7 2021-01-03 10:00:00                <NA>                <NA>                <NA>
# 4        8 2021-01-04 10:00:00 2021-01-04 09:45:00 2021-01-04 11:00:00 2021-01-04 10:00:00


问:
Q: How can I split data into multiple workbooks/files based on column in Excel?
I'm very new to VBA so I hope I don't sound too ignorant. Each month I receive a report that contains data in the ranges A:T and about 7000-10000 rows. I need to separate this data into multiple workbooks/files so that I can send them out.

Currently, I manually filter the column and copy + paste the data into a blank excel and save as for each name but that is just insanely inefficient. I'm completely new to VBA or any sort of code so I've been scouring all over to find any that might help. I'm not sure if I can directly filter the data and save them into new workbooks but I am aware that you can do it as worksheets instead. I've come close using code from here: https://www.excelhow.net/split-data-into-multiple-worksheets-based-on-column.html as shown below but I've noticed that the character limitation of worksheet names causes some issues.

```<code>Sub parse_data()
    Dim lr As Long
    Dim ws As Worksheet
    Dim vcol, i As Integer
    Dim icol As Long
    Dim myarr As Variant
    Dim title As String
    Dim titlerow As Integer

    'This macro splits data into multiple worksheets based on the variables on a column found in Excel.
    'An InputBox asks you which columns you'd like to filter by, and it just creates these worksheets.

    Application.ScreenUpdating = False
    vcol = Application.InputBox(prompt:="Which column would you like to filter by?", title:="Filter column", Default:="3", Type:=1)
    Set ws = ActiveSheet
    lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
    title = "A1"
    titlerow = ws.Range(title).Cells(1).Row
    icol = ws.Columns.Count
    ws.Cells(1, icol) = "Unique"
    For i = 2 To lr
        On Error Resume Next
        If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
            ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
        End If
    Next

    myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
    ws.Columns(icol).Clear

    For i = 2 To UBound(myarr)
        ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
        If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
            Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
        Else
            Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
        End If
        ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
        'Sheets(myarr(i) & "").Columns.AutoFit
    Next

    ws.AutoFilterMode = False
    ws.Activate
    Application.ScreenUpdating = True
End Sub
</code>```

I was wondering if anyone can help me split the data into multiple workbooks based on the Name column (C) or bypass/avoid the character limitation that the worksheet name has, save the worksheets as separate workbooks and rename them later? The files that I send out have the name in the title (eg. NameXYZ_report) so preferably the outcome would have it named, based on the column as well.

Summary of the questions:

Split data into multiple workbooks directly based on Name (Column C value, often exceeds 31 characters) with the file name as ‘Name_report0122’ while keeping header (row 1)

Keep column width of original data

Edit; If it's not possible to save them directly as workbooks, would it be possible to save them as worksheets in a shortened form of the names, save those worksheets as workbooks and then mass rename the files properly afterwards?

I apologise for any confusion caused by my questions as I am new to this but I want to improve. Thank you all!

答:
Export Filtered Data to a New Workbook

Option Explicit

Sub ExportToWorkbooks()

    Const aibPrompt As String = "Which column would you like to filter by?"
    Const aibtitle As String = "Filter Column"
    Const aibDefault As Long = 3

    Dim dFileExtension As String: dFileExtension = ".xlsx"
    Dim dFileFormat As XlFileFormat: dFileFormat = xlOpenXMLWorkbook
    Dim dFolderPath As String: dFolderPath = "C:\Test\"

    If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
    If Len(Dir(dFolderPath, vbDirectory)) = 0 Then Exit Sub ' folder not found
    If Left(dFileExtension, 1) <> "." Then dFileExtension = "." & dFileExtension

    Application.ScreenUpdating = False

    Dim sCol As Variant
    sCol = Application.InputBox(aibPrompt, aibtitle, aibDefault, , , , , 1)
    If Len(CStr(sCol)) = 0 Then Exit Sub ' no entry
    If sCol = False Then Exit Sub ' canceled

    Dim sws As Worksheet: Set sws = ActiveSheet
    If sws.AutoFilterMode Then sws.AutoFilterMode = False ' turn off AutoFilter
    Dim srg As Range: Set srg = sws.Range("A1").CurrentRegion
    Dim srCount As Long: srCount = srg.Rows.Count
    If srCount < 3 Then Exit Sub ' not enough rows
    Dim srrg As Range: Set srrg = srg.Rows(1) ' to copy column widths
    Dim scrg As Range: Set scrg = srg.Columns(sCol)
    Dim scData As Variant: scData = scrg.Value

    ' Write the unique values from the 1st column to a dictionary.

    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare ' case insensitive

    Dim Key As Variant
    Dim r As Long

    For r = 2 To srCount
        Key = scData(r, 1)
        If Not IsError(Key) Then ' exclude error values
            If Len(Key) > 0 Then ' exclude blanks
                dict(Key) = Empty
            End If
        End If
    Next r
    If dict.Count = 0 Then Exit Sub ' only error values and blanks
    Erase scData

    Dim dwb As Workbook
    Dim dws As Worksheet
    Dim dfcell As Range
    Dim dFilePath As String

    For Each Key In dict.Keys
        ' Add a new (destination) workbook and reference the first cell.
        Set dwb = Workbooks.Add(xlWBATWorksheet) ' one worksheet
        Set dws = dwb.Worksheets(1)
        Set dfcell = dws.Range("A1")
        ' Copy/Paste
        srrg.Copy
        dfcell.PasteSpecial xlPasteColumnWidths
        srg.AutoFilter sCol, Key
        srg.SpecialCells(xlCellTypeVisible).Copy dfcell
        sws.ShowAllData
        dfcell.Select
        ' Save/Close
        dFilePath = dFolderPath & Key & dFileExtension ' build the file path
        Application.DisplayAlerts = False ' overwrite without confirmation
        dwb.SaveAs dFilePath, xlOpenXMLWorkbook
        Application.DisplayAlerts = True
        dwb.Close SaveChanges:=False
    Next Key

    sws.AutoFilterMode = False
    Application.ScreenUpdating = True

    MsgBox "Data exported.", vbInformation

End Sub
```

Body:
I'm very new to VBA so I hope I don't sound too ignorant. Each month I receive a report that contains data in the ranges A:T and about 7000-10000 rows. I need to separate this data into multiple workbooks/files so that I can send them out.

Currently, I manually filter the column and copy + paste the data into a blank excel and save as for each name but that is just insanely inefficient. I'm completely new to VBA or any sort of code so I've been scouring all over to find any that might help. I'm not sure if I can directly filter the data and save them into new workbooks but I am aware that you can do it as worksheets instead. I've come close using code from here: https://www.excelhow.net/split-data-into-multiple-worksheets-based-on-column.html as shown below but I've noticed that the character limitation of worksheet names causes some issues.

Sub parse_data()
    Dim lr As Long
    Dim ws As Worksheet
    Dim vcol, i As Integer
    Dim icol As Long
    Dim myarr As Variant
    Dim title As String
    Dim titlerow As Integer

    'This macro splits data into multiple worksheets based on the variables on a column found in Excel.
    'An InputBox asks you which columns you'd like to filter by, and it just creates these worksheets.

    Application.ScreenUpdating = False
    vcol = Application.InputBox(prompt:="Which column would you like to filter by?", title:="Filter column", Default:="3", Type:=1)
    Set ws = ActiveSheet
    lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
    title = "A1"
    titlerow = ws.Range(title).Cells(1).Row
    icol = ws.Columns.Count
    ws.Cells(1, icol) = "Unique"
    For i = 2 To lr
        On Error Resume Next
        If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
            ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
        End If
    Next

    myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
    ws.Columns(icol).Clear

    For i = 2 To UBound(myarr)
        ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
        If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
            Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
        Else
            Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
        End If
        ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
        'Sheets(myarr(i) & "").Columns.AutoFit
    Next

    ws.AutoFilterMode = False
    ws.Activate
    Application.ScreenUpdating = True
End Sub

I was wondering if anyone can help me split the data into multiple workbooks based on the Name column (C) or bypass/avoid the character limitation that the worksheet name has, save the worksheets as separate workbooks and rename them later? The files that I send out have the name in the title (eg. NameXYZ_report) so preferably the outcome would have it named, based on the column as well.

Summary of the questions:

Split data into multiple workbooks directly based on Name (Column C value, often exceeds 31 characters) with the file name as ‘Name_report0122’ while keeping header (row 1)

Keep column width of original data

Edit; If it's not possible to save them directly as workbooks, would it be possible to save them as worksheets in a shortened form of the names, save those worksheets as workbooks and then mass rename the files properly afterwards?

I apologise for any confusion caused by my questions as I am new to this but I want to improve. Thank you all!


问:
File download failed in ReactJS
I am trying to download file from src folder in my react app, but file download is failing

file import

```<code>import test from "../../test.json";
</code>```

download

```<code>  const link = document.createElement("a");
  link.href = test;
  link.setAttribute("download", `test.json`);
  document.body.appendChild(link);
  link.click();
  link.parentNode.removeChild(link);
</code>```

File download failed

答:
You can not download files in the src folder.
If you need this file and change it in every build, you can use a script and run it before building for copying files from src to the public folder. If not, you must copy the file to the public folder.</p>

Title: File download failed in ReactJS

Body:
I am trying to download file from src folder in my react app, but file download is failing

file import

import test from "../../test.json";

download

  const link = document.createElement("a");
  link.href = test;
  link.setAttribute("download", `test.json`);
  document.body.appendChild(link);
  link.click();
  link.parentNode.removeChild(link);

File download failed


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
Now that you've given us more specifics, the approach I would take relies upon pre-partitioning, and optionally, sorting before searching for matches.

This should eliminate a substantial amount of comparisons that wouldn't otherwise match anyway in the naive, brute-force approach. For the sake of argument, lets peg both files at 40 million lines each.

Partitioning: Read through file_1 and send all lines starting with mat1 to file_1_mat1, and so on. Do the same for file_2. This is trivial with a little grep, or should you wish to do it programmatically in Java it's a beginner's exercise.

That's one pass through two files for a total of 80million lines read, yielding two sets of 50 files of 800,000 lines each on average.

Sorting: For each partition, sort according to the numeric value in the second column only (the lower bound from file_1 and the actual number from file_2). Even if 800,000 lines can't fit into memory I suppose we can adapt 2-way external merge sort and perform this faster (fewer overall reads) than a sort of the entire unpartitioned space.

Comparison: Now you just have to iterate once through both pairs of file_1_mat1 and file_2_mat1, without need to keep anything in memory, outputting matches to your output file. Repeat for the rest of the partitions in turn. No need for a final 'merge' step (unless you're processing partitions in parallel).

Even without the sorting stage the naive comparison you're already doing should work faster across 50 pairs of files with 800,000 lines each rather than with two files with 40 million lines each.

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
How to check for duplicate images ? C#
So guys that's what i have.

I have a  1 folder with around 30k pictures (a old backup from long time ago)
and second folder used as the current backup.

so I just wanted to check if in the first folder I got pictures that I don't have in the second folder.. and if i got picture in folder 1 that I already have in folder 2 so it will be deleted from folder 1.

I thought maybe I should compare between the size on disk of 1 picture from folder 1 against all the pictures in folder 2. (with 2 for loops)

but I saw that I have 2 different pictures with the exact size (size on disk).
so I can't really use it.

anyone got idea how should i do it? (remember that i got around 30k photos in folder 1 so the algorithm should be efficient)ץ

got diffrent hash for same picture. :

```<code>            using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead("C:/Users/Sam/Desktop/1.jpg"))
            {
                Console.WriteLine(BitConverter.ToString(md5.ComputeHash(stream)));
            }
           using (var stream2 = File.OpenRead("C:/Users/Sam/Desktop/2.jpg"))
            {
                Console.WriteLine(BitConverter.ToString(md5.ComputeHash(stream2)));
            }
        }
</code>```

Hi i did use this algoritem :
Algorithm to compare two images in C#

but it's take too slow. (takes about 2-3 sec to compare 1 image to 100 others so its gonna be forever to compare all the images (around 30k) )..

答:
Here's a couple of open source C# projects that do image comparison.

https://github.com/xnafan/Simple-image-comparison

https://github.com/ukushu/ImgComparator

Title: How to check for duplicate images ? C#

Body:
So guys that's what i have.

I have a  1 folder with around 30k pictures (a old backup from long time ago)
and second folder used as the current backup.

so I just wanted to check if in the first folder I got pictures that I don't have in the second folder.. and if i got picture in folder 1 that I already have in folder 2 so it will be deleted from folder 1.

I thought maybe I should compare between the size on disk of 1 picture from folder 1 against all the pictures in folder 2. (with 2 for loops)

but I saw that I have 2 different pictures with the exact size (size on disk).
so I can't really use it.

anyone got idea how should i do it? (remember that i got around 30k photos in folder 1 so the algorithm should be efficient)ץ

got diffrent hash for same picture. :

            using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead("C:/Users/Sam/Desktop/1.jpg"))
            {
                Console.WriteLine(BitConverter.ToString(md5.ComputeHash(stream)));
            }
           using (var stream2 = File.OpenRead("C:/Users/Sam/Desktop/2.jpg"))
            {
                Console.WriteLine(BitConverter.ToString(md5.ComputeHash(stream2)));
            }
        }

Hi i did use this algoritem :
Algorithm to compare two images in C#

but it's take too slow. (takes about 2-3 sec to compare 1 image to 100 others so its gonna be forever to compare all the images (around 30k) )..


问:
Springboot not returning index.jsp
When I am running my Sprinboot Application, it is just returning index as string. It is not giving me index.jsp page. Also I have tried to add some jstl compiler in it still it is not working

The code of Main file:

```<code>package com.hello.first;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }

}
</code>```

The Controller file:

```<code>package com.hello.first;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class firstpage {

    @RequestMapping("/")
    public String hello(){
        return "index";
    }
}
</code>```

Application.properties:

server.port=8000

spring.mvc.view.prefix=/WEB-INF/

spring.mvc.view.suffix= .jsp

POM.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hello</groupId>
    <artifactId>first</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>first</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

index.jsp:

```<code><%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Hello this is my page!!
</body>
</html>
</code>```

Output I am getting:

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

答:
I was able to solve the problem by replacing the return "index" with return "index.html" and replacing the files from templates folder to static folder as I was simply trying to return simple HTML file.

Also the above code is working fine if I add thymeleaf dependancy

Title: Springboot not returning index.jsp

Body:
When I am running my Sprinboot Application, it is just returning index as string. It is not giving me index.jsp page. Also I have tried to add some jstl compiler in it still it is not working

The code of Main file:

package com.hello.first;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }

}

The Controller file:

package com.hello.first;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class firstpage {

    @RequestMapping("/")
    public String hello(){
        return "index";
    }
}

Application.properties:

server.port=8000

spring.mvc.view.prefix=/WEB-INF/

spring.mvc.view.suffix= .jsp

POM.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>com.hello</groupId>
    <artifactId>first</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>first</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

index.jsp:

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    Hello this is my page!!

Output I am getting:

index


问:
Internal working of inputFiles method in pyspark
I was reading about inputFiles() in  the documentation of pyspark . When I ran the below code it returned me output as 0.

```<code>df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("/data/spark/Spark-The-Definitive-Guide/data/retail-data/all/*.csv")
print(len(df.inputFiles()))
</code>```

Please let me know why the output is zero and also a more verbose explanation of inputFiles() if possible. The explanation in the documentation is pretty dense .

```<code>Returns a best-effort snapshot of the files that compose this DataFrame. This method simply asks each constituent BaseRelation for its respective files and takes the union of all results. Depending on the source relations, this may not find all input files. Duplicates are removed.
</code>```

答:
I ran the same command, got below output:

```<code>>>> df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("file:////github/Spark-The-Definitive-Guide/data/retail-data/all/*.csv")
>>> print(len(df.inputFiles()))
1
>>> df.inputFiles()
['file:///github/Spark-The-Definitive-Guide/data/retail-data/all/online-retail-dataset.csv']
</code>```

inputFiles() should show all input files. I suppose the reason you got 0 is the path is correct. You should use something prefixed with file:///

Body:
I was reading about inputFiles() in  the documentation of pyspark . When I ran the below code it returned me output as 0.

df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("/data/spark/Spark-The-Definitive-Guide/data/retail-data/all/*.csv")
print(len(df.inputFiles()))

Please let me know why the output is zero and also a more verbose explanation of inputFiles() if possible. The explanation in the documentation is pretty dense .

Returns a best-effort snapshot of the files that compose this DataFrame. This method simply asks each constituent BaseRelation for its respective files and takes the union of all results. Depending on the source relations, this may not find all input files. Duplicates are removed.

Body:
I ran the same command, got below output:

>>> df = spark.read.format("csv").option("header", "true").option("inferSchema", "true").load("file:////github/Spark-The-Definitive-Guide/data/retail-data/all/*.csv")
>>> print(len(df.inputFiles()))
1
>>> df.inputFiles()
['file:///github/Spark-The-Definitive-Guide/data/retail-data/all/online-retail-dataset.csv']

inputFiles() should show all input files. I suppose the reason you got 0 is the path is correct. You should use something prefixed with file:///


问:
How to test old linux kernel?
We can change OS kernel, ex: CentOS, by 'yum update kernel-xxxx'

However, I think we can not downgrade the kernel to an old version.

The purpose is to test the old kernel ( ex: 0.11, 0.96, 2.0 ....etc )

Is there any way to test it without OS bundle(ex: CentOS)? ( especially I want to test it with VirtualBox )

答:
Years ago I tacked this problem with a slightly different twist.  I wanted to use the vintage tools on Windows to cross compile and test old Linux kernels.  My goal was to use something that didn’t require Cygwin or WSL, but rather msys and MinGW.  The result of this project is at source forge:

https://sourceforge.net/projects/linux011/

From my own blurb:
While I may have started with Linux 0.11, I've expanded this to include several older relases of the Linux kernel that you can cross compile from Windows, and run on Qemu. I've managed to get the older versions of the software tools running on Windows, so that there is no major invasive source changes, outside of either broken drivers, or massaging the makefiles to find things in the new paths, and calling the appropriate tools where needed.

Linux 0.10 is the first oldest version of Linux that is somewhat usable. While it lacks things like TCP/IP, and robust filesystems, it does offer a small kernel size, perfect for playing around with. You can comfortably make changes on Windows, re-compile and test all from a 'normal' desktop.

Features
GCC 1.40
GCC 2.3.3
GCC 2.5.8
Binutils 1.9
GAS 1.38
Bison 1.16

So from windows the following cross compilers can build working kernels, and it even includes qemu environmental with scripts to run all the old versions.

There is no installer just unzip and edit “env.cmd” to reflect the installed directory.  From there you can look in the source tree and run make and it’ll build the kernel from you.  Inside the qemu directory is a cmd file tailored to run each version that I’ve setup to cross compile.

Naturally you can use any windows editor on the source, which was my original goal to bring Linux kernel development to the casual Windows desktop user.

Source to the tools is also included I used GCC 5 and msys/ Mingw to build everything.  I think GCC 7 may work but it’s been a while.

Title: How to test old linux kernel?


问:
How to sum all Object using index with an arrays
how can I search duplicate data using index key object here is my object :

```<code> const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }
</code>```

and I have an arrays

```<code>const arr = ["product1", "product2" ]
</code>```

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

```<code>const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

</code>```

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

```<code> const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }
</code>```

答:
Non lodash implementation. filtered the array and ran reduce

const arr = ["product1", "product2" ]
const obj2 = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 },
        "product1 Hello4": { name: 'paper', price: 2 }
    }

 let filtered = Object.entries(obj2).filter((el) => arr.includes(el[0].split(" ")[0]))

 const sum = filtered.reduce((acc,curr)=> acc + curr[1].price, 0);
 console.log(sum)```

Body:
how can I search duplicate data using index key object here is my object :

 const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }

and I have an arrays

const arr = ["product1", "product2" ]

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

 const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }


问:
Hide the content based on Children class
I need one help with the code, I have two HTML div blocks with the same class name and there is one extra h2 tag with different class present in one div block. I want to hide if h2 class name is not present in that div and show if the h2 class name is present. Please find the below mentioned code that I have created.

-- First block Div --

```<code><div class="course-content">
    <h2 class="accesshide"></h2>
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="row">
        <p>Content to Display</p>
    </div>
</div>
</code>```

-- Second block Div --

```<code><div class="course-content">
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="single-section">
        <p>Content to Display</p>
    </div>
</div>
</code>```

-- jQuery Code --

$(document).ready(function () {
    if ($(".course-content").find(".accesshide")) {
        $(".course-content").find(".topics").show();
    } else if ($(".course-content").find(".single-section")) {
        $(".course-content").find(".topics").hide();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course-content">
        <h2 class="accesshide"></h2>
        <ul class="topics">
            <li class="data-list">Content not to Display</li>
        </ul>
        <div class="row">
            <p>Content to Display (this statement is inaccurate)</p>
        </div>
    </div>

    <div class="course-content">
        <ul class="topics">
            <li class="data-list">Content not to Display (this statement is inaccurate)</li>
        </ul>
        <div class="single-section">
            <p>Content to Display</p>
        </div>
    </div></code>```

答:
I want to hide if h2 class name is not present in that div and show if the h2 class name is present.

You don't need any JS code, just only CSS with adjacent or general sibling combinator. For example:

.course-content .topics {
  display: none;
}
.course-content .accesshide + .topics {
  display: block;
}
```
<p>When you have to use jQuery then you can use the same logic and the <code>.next()</code> method (or <code>.nextAll()</code>):</p>
<pre class="lang-js prettyprint-override"><code>$(".course-content").find(".topics").hide();
$(".course-content").find(".accesshide").next(".topics").show();
</code>```

If the controlled block can be both before and after the control block, the shortest way is to use the .siblings() method. If you need to show the .topics block if there is an .accesshide block or a .single-section block nearby, you can use this jQuery method for both cases:

$(document).ready(function () {
    $(".course-content").find(".topics").hide();
    $(".course-content").find(".accesshide, .single-section").siblings(".topics").show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="course-content">
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="row">
        <p>There are no special blocks nearby</p>
    </div>
</div>

<div class="course-content">
    <h2 class="accesshide"></h2>
    <ul class="topics">
        <li class="data-list">Show because of the .accesshide block</li>
    </ul>
    <div class="row">
        <p>Case 1</p>
    </div>
</div>

<div class="course-content">
    <ul class="topics">
        <li class="data-list">Show because of the .single-section block</li>
    </ul>
    <div class="single-section">
        <p>Case 2</p>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
I need one help with the code, I have two HTML div blocks with the same class name and there is one extra h2 tag with different class present in one div block. I want to hide if h2 class name is not present in that div and show if the h2 class name is present. Please find the below mentioned code that I have created.

-- First block Div --

Content not to Display

Content to Display

-- Second block Div --

Content not to Display

Content to Display

-- jQuery Code --

$(document).ready(function () {
    if ($(".course-content").find(".accesshide")) {
        $(".course-content").find(".topics").show();
    } else if ($(".course-content").find(".single-section")) {
        $(".course-content").find(".topics").hide();
    }
});

Content not to Display

Content to Display (this statement is inaccurate)

Content not to Display (this statement is inaccurate)

Content to Display

Body:
I want to hide if h2 class name is not present in that div and show if the h2 class name is present.

You don't need any JS code, just only CSS with adjacent or general sibling combinator. For example:

.course-content .topics {
  display: none;
}
.course-content .accesshide + .topics {
  display: block;
}

When you have to use jQuery then you can use the same logic and the .next() method (or .nextAll()):

$(".course-content").find(".topics").hide();
$(".course-content").find(".accesshide").next(".topics").show();

If the controlled block can be both before and after the control block, the shortest way is to use the .siblings() method. If you need to show the .topics block if there is an .accesshide block or a .single-section block nearby, you can use this jQuery method for both cases:

$(document).ready(function () {
    $(".course-content").find(".topics").hide();
    $(".course-content").find(".accesshide, .single-section").siblings(".topics").show();
});

<div class="course-content">
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="row">
        <p>There are no special blocks nearby</p>
    </div>
</div>

<div class="course-content">
    <h2 class="accesshide"></h2>
    <ul class="topics">
        <li class="data-list">Show because of the .accesshide block</li>
    </ul>
    <div class="row">
        <p>Case 1</p>
    </div>
</div>

<div class="course-content">
    <ul class="topics">
        <li class="data-list">Show because of the .single-section block</li>
    </ul>
    <div class="single-section">
        <p>Case 2</p>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


答:
I would use Array.prototype.reduce to iterate through the array and return a single value that is the total price.</p>
```<code>    const products = {
        id1: { name: "paper", price: 4 },
        id2: { name: "ball", price: 2 },
        id3: { name: "ice-cream", price: 9 },
    };

    const productIds = ["id1", "id2"];

    const totalPrice = productIds.reduce((sum, id) => {
        return sum + products[id].price;
    }, 0);
</code>```

Title: How to sum all Object using index with an arrays

Body:
I would use Array.prototype.reduce to iterate through the array and return a single value that is the total price.

    const products = {
        id1: { name: "paper", price: 4 },
        id2: { name: "ball", price: 2 },
        id3: { name: "ice-cream", price: 9 },
    };

    const productIds = ["id1", "id2"];

    const totalPrice = productIds.reduce((sum, id) => {
        return sum + products[id].price;
    }, 0);


问:
The variable declared in for-loop of c++ is not initialised
```<code>#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}
</code>```

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn't make sense to me.

When it comes to the second largest number, k behaves as expected.

答:
```<code>void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) {
            *(start + k) = *(start + k + 1);
        }
        // The problem was here, you wanted to access memory that does not belong to you.
        *(start + length - i - 1) = max;
    }
</code>```

Body:
#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn't make sense to me.

When it comes to the second largest number, k behaves as expected.


问:
Angualar - change object into array with specific structure
Good morning,
could someone help me with changing Object like this

```<code>    {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
    }
</code>```

And i need to get this format of array

```<code>[
 {
  id: item1, value: "this is string field value"
 },
 {
  id: item2, value: "FF FF A2 C4"
 }
]
</code>```

I know how I could solve this, for example, using it
Object.keys() or Object.values().

But I always get only one parameter out of two. And then the combination of these two results I am not able to put together. Therefore, I want to ask if anyone knows about a better / simpler solution. Or if someone could show me what I'm doing wrong and what is solution for this.

Thanks in advance

答:
You can use Object.entries() to get hold of both key and value at same time.

From MDN docs:

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs

Try something as below:

const someArray = Object.entries(someObject).map(([key, value]) => ({id: key, value: value}))
```

Body:
Good morning,
could someone help me with changing Object like this

    {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
    }

And i need to get this format of array

[
 {
  id: item1, value: "this is string field value"
 },
 {
  id: item2, value: "FF FF A2 C4"
 }
]

I know how I could solve this, for example, using it
Object.keys() or Object.values().

But I always get only one parameter out of two. And then the combination of these two results I am not able to put together. Therefore, I want to ask if anyone knows about a better / simpler solution. Or if someone could show me what I'm doing wrong and what is solution for this.

Thanks in advance


问:
Ruby on Rails console - undefined method `assets'
On the project the console ceased to be started, I tried everything that found in Google..

I run rails c and get an error:

```<code>/Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/railtie/configuration.rb:97:in `method_missing': undefined method `assets' for #<Rails::Application::Configuration:0x007fae6a9bdf78>
Did you mean?  asset_host (NoMethodError)
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/popper_js-1.12.9/lib/popper_js/engine.rb:6:in `block in <class:Engine>'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:32:in `instance_exec'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:32:in `run'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:61:in `block in run_initializers'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:347:in `each'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:347:in `call'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:60:in `run_initializers'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/application.rb:361:in `initialize!'
    from /Users/gorbunov/Projects/buktopuha_api/config/environment.rb:5:in `<main>'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:102:in `preload'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:153:in `serve'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:141:in `block in run'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:135:in `loop'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:135:in `run'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application/boot.rb:19:in `<top (required)>'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from -e:1:in `<main>'
</code>```

I don't know what to do. Thanks a lot!

答:
I had this problem and found the solution here, which was to ensure you have the sprockets line in config/application.rb

require "rails"
 require "active_model/railtie"
 require "active_job/railtie"
 require "active_record/railtie"
 require "active_storage/engine"
 require "action_controller/railtie"
 require "action_mailer/railtie"
 require "action_mailbox/engine"
 require "action_text/engine"
 require "action_view/railtie"
 require "action_cable/engine"
 require "sprockets/railtie"  # <--- make sure this line is here
 require "rails/test_unit/railtie"
```

Note that the above lines differ a little between rails versions. Find what it should look like for your rails version at the rails guide for your version. Here's rails 6.1, and here's 7.0.

Funnily enough, I had just removed require "sprockets/railtie" since I was trying to remove sprockets. In any case, I put it back in and rails is happy again.

Body:
On the project the console ceased to be started, I tried everything that found in Google..

I run rails c and get an error:

/Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/railtie/configuration.rb:97:in `method_missing': undefined method `assets' for #<Rails::Application::Configuration:0x007fae6a9bdf78>
Did you mean?  asset_host (NoMethodError)
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/popper_js-1.12.9/lib/popper_js/engine.rb:6:in `block in <class:Engine>'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:32:in `instance_exec'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:32:in `run'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:61:in `block in run_initializers'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:347:in `each'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:347:in `call'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/initializable.rb:60:in `run_initializers'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/railties-5.2.0/lib/rails/application.rb:361:in `initialize!'
    from /Users/gorbunov/Projects/buktopuha_api/config/environment.rb:5:in `'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:102:in `preload'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:153:in `serve'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:141:in `block in run'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:135:in `loop'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application.rb:135:in `run'
    from /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/spring-2.0.2/lib/spring/application/boot.rb:19:in `<top (required)>'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Users/gorbunov/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from -e:1:in `'

I don't know what to do. Thanks a lot!

Body:
I had this problem and found the solution here, which was to ensure you have the sprockets line in config/application.rb

require "rails"
 require "active_model/railtie"
 require "active_job/railtie"
 require "active_record/railtie"
 require "active_storage/engine"
 require "action_controller/railtie"
 require "action_mailer/railtie"
 require "action_mailbox/engine"
 require "action_text/engine"
 require "action_view/railtie"
 require "action_cable/engine"
 require "sprockets/railtie"  # <--- make sure this line is here
 require "rails/test_unit/railtie"

Note that the above lines differ a little between rails versions. Find what it should look like for your rails version at the rails guide for your version. Here's rails 6.1, and here's 7.0.

Funnily enough, I had just removed require "sprockets/railtie" since I was trying to remove sprockets. In any case, I put it back in and rails is happy again.


问:
Cypress : The submit button is disabled even after all the text fields have filled
I was trying to automate a text submit form using cypress. The 'Create student'  button is disabled even after all the fields have been filled

Please see the cypress error

code :

it('should be able to add a new student and update the details, remove from the class and delete the account', function () {
        cy.visit(
            'https://readingeggs.blake-staging.com/district_ui#/reading/manage-schools/students/195286/new'
        )
        cy.findByLabelText('First Name').type('ark')
        cy.get('#first-name').should('have.value', 'ark')
        cy.findByLabelText('Last Name').type('last')
        cy.get('#last-name').should('have.value', 'last')
        cy.get('[data-test-select-grade]').select('1')
        cy.get('#grade-dropdown').should('have.value', '1')
        cy.get('[data-test-select-teacher]').select('Lehner, Abbey')
        cy.get('#teacher-dropdown').should('have.value', '3068134')

        cy.get('[data-test-submit-new-student]').click()
        cy.get('#main')
            .findByRole('alert')
            .should('include.text', `Successfully created a student`)
    })
})
```

答:
Be careful using click({force:true}) as suggested in the error message, there may be another problem that your test will now ignore!

You can first try an assertion that the button is not disabled.

Sometimes the test can run too quickly, and the web page has not yet enabled the button before the test tries to click it.

Adding .should('not.be.disabled') will retry this check for up to 4 seconds, which should be enough time for the page to complete changes.

cy.get('[data-test-submit-new-student]')
  .should('not.be.disabled')
  .click()
```


问:
How to create an instance method based on this object data?
I have some data inside this variable and I want to know how could I write an method to give me the sum of the items price.

Model names and their associations:

```<code>Order
- belongs_to :customer
- has_many :item_orders
- has_many :items, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true, :reject_if => lambda { |a| a['item_id'].blank? }

Item
- has_many :item_orders, :dependent => :destroy
- has_many :orders, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true

ItemOrder
- belongs_to :item
- belongs_to :order
</code>```

doing:

```<code><%= debug @order.items %>

# returns me

- !ruby/object:Item
  attributes:
  id: 31
  title: Golden Ring 2
  price: 13445.0
  labour_cost: 500.0
  item_type_id: 10
  created_at: 2011-08-13 10:53:24.000000000Z
  updated_at: 2011-08-18 06:10:36.000000000Z
  photo: golden_ring.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false
- !ruby/object:Item
 attributes:
  id: 32
  title: Special Pendant
  price: 171.67
  labour_cost: 120.0
  item_type_id: 20
  created_at: 2011-08-13 11:09:43.000000000Z
  updated_at: 2011-08-14 06:03:02.000000000Z
  photo: prd_194_48cd9b21771dd.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false
</code>```

So, I want to write a method in the Order model class to make possible writes something like this on the view.

```<code> <%= @order.items.total_price %>
</code>```

The total_price method will sum all the item prices and multiply by the quantity that contains in @order.items.

My doubt is: from inside the method, how could I have access to the items collection to perform the sum operation.

```<code>def total_price
  self.item_order.each do |i| {
     result += i.quantity * i.items.price
  }
end
</code>```

EDIT: I totally forgot to mention that I have to consider the quantity also to make this math.

答:
As you have has_many :items in your Order model, you should be able to use that items variable easily. All you need to do is write this in your Order model:

```<code>def total_price
  items.to_a.sum {|item| item.price}
end
</code>```

Body:
I have some data inside this variable and I want to know how could I write an method to give me the sum of the items price.

Model names and their associations:

Order
- belongs_to :customer
- has_many :item_orders
- has_many :items, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true, :reject_if => lambda { |a| a['item_id'].blank? }

Item
- has_many :item_orders, :dependent => :destroy
- has_many :orders, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true

ItemOrder
- belongs_to :item
- belongs_to :order

doing:

<%= debug @order.items %>

# returns me

- !ruby/object:Item
  attributes:
  id: 31
  title: Golden Ring 2
  price: 13445.0
  labour_cost: 500.0
  item_type_id: 10
  created_at: 2011-08-13 10:53:24.000000000Z
  updated_at: 2011-08-18 06:10:36.000000000Z
  photo: golden_ring.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false
- !ruby/object:Item
 attributes:
  id: 32
  title: Special Pendant
  price: 171.67
  labour_cost: 120.0
  item_type_id: 20
  created_at: 2011-08-13 11:09:43.000000000Z
  updated_at: 2011-08-14 06:03:02.000000000Z
  photo: prd_194_48cd9b21771dd.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false

So, I want to write a method in the Order model class to make possible writes something like this on the view.

 <%= @order.items.total_price %>

The total_price method will sum all the item prices and multiply by the quantity that contains in @order.items.

My doubt is: from inside the method, how could I have access to the items collection to perform the sum operation.

def total_price
  self.item_order.each do |i| {
     result += i.quantity * i.items.price
  }
end

EDIT: I totally forgot to mention that I have to consider the quantity also to make this math.

Body:
As you have has_many :items in your Order model, you should be able to use that items variable easily. All you need to do is write this in your Order model:

def total_price
  items.to_a.sum {|item| item.price}
end