问:
Why doesn't this work to calculate proportion of mothers with educations at different levels?
I'm taking a python course on Coursera. For one of the assignments the question is:

Write a function called proportion_of_education which returns the proportion of children in the dataset who had a mother with the education levels equal to less than high school (<12), high school (12), more than high school but not a college graduate (>12) and college degree.

This function should return a dictionary in the form of (use the correct numbers, do not round numbers):

```<code>{"less than high school":0.2,
"high school":0.4,
"more than high school but not college":0.2,
"college":0.2}
</code>```

I wrote a code that is probably rather inefficient but should work and I don't understand why I'm getting errors

Here it is:

```<code>def proportion_of_education():
    import pandas as pd
    df = pd.read_csv('assets/NISPUF17.csv.')
    df.loc[:,['SEQNUMC','EDUC1']]
    new_df = df.loc[:,['SEQNUMC','EDUC1']]
    new_df['middle'] = new_df['EDUC1']  == 1
    new_df['highed'] = new_df['EDUC1']  == 2
    new_df['lessthancollege'] = new_df['EDUC1']  == 3
    new_df['college'] = new_df['EDUC1']  == 4
    {"less than high school":new_df.middle[new_df.middle==True].count()/28465,
    "high school":new_df.highed[new_df.highed==True].count()/28465,
    "more than high school but not college":new_df.lessthancollege[new_df.lessthancollege==True].count()/28465,
    "college":new_df.college[new_df.college==True].count()/28465}

    raise NotImplementedError()

</code>```

The course uses this to check it:

```<code>assert type(proportion_of_education())==type({}), "You must return a dictionary."
assert len(proportion_of_education()) == 4, "You have not returned a dictionary with four items in it."
assert "less than high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "more than high school but not college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
</code>```

Now this is what I'm getting in return:

```<code>
NotImplementedError                       Traceback (most recent call last)
<ipython-input-2-2eae51ff42e4> in <module>
----> 1 assert type(proportion_of_education())==type({}), "You must return a dictionary."
      2 assert len(proportion_of_education()) == 4, "You have not returned a dictionary with four items in it."
      3 assert "less than high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
      4 assert "high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
      5 assert "more than high school but not college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."

<ipython-input-1-57ea8a20b116> in proportion_of_education()
     16
     17
---> 18     raise NotImplementedError()

NotImplementedError:

</code>```

Why am I getting these errors? What could I do to make this more efficient?

答:
Regarding to your second question, you may try:

```<code>import pandas as pd
def proportion_of_education():
    df = pd.read_csv('assets/NISPUF17.csv')
    step1 = df['EDUC1'].value_counts()
    step2 = step1/len(df)
    step3 = step2.rename({
        1: 'less than high school',
        2: 'high school',
        3: 'more than high school but not college',
        4: 'college',
    })
    step4 = step3.to_dict()
    return step4
</code>```

step1 gives you the counts, while step2 convert counts into percentage. Now step2 is a pd.Series object, so you can do step3 to rename 1, 2, 3, 4 (which are the indices of the pd.Series) into what they mean, and the last step convert the pd.Series into a dict.

Below is a different version of the same process with less intermediate variables.

```<code>import pandas as pd
def proportion_of_education():
    df = pd.read_csv('assets/NISPUF17.csv')

    return (df['EDUC1'].value_counts() / len(df)).rename({
        1: 'less than high school',
        2: 'high school',
        3: 'more than high school but not college',
        4: 'college',
    }).to_dict()
</code>```

Body:
I'm taking a python course on Coursera. For one of the assignments the question is:

Write a function called proportion_of_education which returns the proportion of children in the dataset who had a mother with the education levels equal to less than high school (<12), high school (12), more than high school but not a college graduate (>12) and college degree.

This function should return a dictionary in the form of (use the correct numbers, do not round numbers):

{"less than high school":0.2,
"high school":0.4,
"more than high school but not college":0.2,
"college":0.2}

I wrote a code that is probably rather inefficient but should work and I don't understand why I'm getting errors

Here it is:

def proportion_of_education():
    import pandas as pd
    df = pd.read_csv('assets/NISPUF17.csv.')
    df.loc[:,['SEQNUMC','EDUC1']]
    new_df = df.loc[:,['SEQNUMC','EDUC1']]
    new_df['middle'] = new_df['EDUC1']  == 1
    new_df['highed'] = new_df['EDUC1']  == 2
    new_df['lessthancollege'] = new_df['EDUC1']  == 3
    new_df['college'] = new_df['EDUC1']  == 4
    {"less than high school":new_df.middle[new_df.middle==True].count()/28465,
    "high school":new_df.highed[new_df.highed==True].count()/28465,
    "more than high school but not college":new_df.lessthancollege[new_df.lessthancollege==True].count()/28465,
    "college":new_df.college[new_df.college==True].count()/28465}

    raise NotImplementedError()

The course uses this to check it:

assert type(proportion_of_education())==type({}), "You must return a dictionary."
assert len(proportion_of_education()) == 4, "You have not returned a dictionary with four items in it."
assert "less than high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "more than high school but not college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."

Now this is what I'm getting in return:

NotImplementedError                       Traceback (most recent call last)
<ipython-input-2-2eae51ff42e4> in <module>
----> 1 assert type(proportion_of_education())==type({}), "You must return a dictionary."
      2 assert len(proportion_of_education()) == 4, "You have not returned a dictionary with four items in it."
      3 assert "less than high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
      4 assert "high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
      5 assert "more than high school but not college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."

<ipython-input-1-57ea8a20b116> in proportion_of_education()
     16
     17
---> 18     raise NotImplementedError()

NotImplementedError:

Why am I getting these errors? What could I do to make this more efficient?

Body:
Regarding to your second question, you may try:

import pandas as pd
def proportion_of_education():
    df = pd.read_csv('assets/NISPUF17.csv')
    step1 = df['EDUC1'].value_counts()
    step2 = step1/len(df)
    step3 = step2.rename({
        1: 'less than high school',
        2: 'high school',
        3: 'more than high school but not college',
        4: 'college',
    })
    step4 = step3.to_dict()
    return step4

step1 gives you the counts, while step2 convert counts into percentage. Now step2 is a pd.Series object, so you can do step3 to rename 1, 2, 3, 4 (which are the indices of the pd.Series) into what they mean, and the last step convert the pd.Series into a dict.

Below is a different version of the same process with less intermediate variables.

import pandas as pd
def proportion_of_education():
    df = pd.read_csv('assets/NISPUF17.csv')

    return (df['EDUC1'].value_counts() / len(df)).rename({
        1: 'less than high school',
        2: 'high school',
        3: 'more than high school but not college',
        4: 'college',
    }).to_dict()


来源: stackexchange

问:
image 404 (not found) Github Pages Vitejs build React app not show the image
I am trying to make a simple React app with ViteJS and GitHub Pages but something is wrong with my images. I can't load them, event although I added them to assets folder. Can you help me how to fix that ?

when vite priview

vite.config.js file

that is my project, please help me
https://github.com/quocbinh-npm9081/React-App-Space-tourism-website

答:
You are not referencing the correct url for your images you are using the path https://quocbinh-npm9081.github.io/assets/destination/image-titan.png where as it should be https://quocbinh-npm9081.github.io/React-App-Space-tourism-website/assets/destination/image-titan.png

Github pages deploys your site in your project sub-directory

You should build your site accordingly to be hosted in a sub-directory

ContentLicense: CC BY-SA 4.0


问:
Display options menu using onClickListener
I was just wondering whether it is possible to display my options menu to be displayed when I click on a image. Now I have displayed my options menu when the menu button is clicked. But I would like to display it when the user clicks on my imageView too. Is this possible?</p>

答:
I found this to be so simple at last. </p>

```<code>imageView.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
        openOptionsMenu();
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I found this to be so simple at last.

imageView.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
        openOptionsMenu();
        }
    });


问:
How to install openGauss on a Python 3.7 environment
when I install openGauss on a python3.7 environment, it reminds me the python version is not support, so how can I do?</p>

答:
Following this step

open the gspylib/common/CheckPythonVersion.py file

change if not pythonVersion = (3, 6): to if not pythonVersion > = (3, 6):

type the "ESC" key to enter the instruction mode, execute: wq save and exit the modification.


问:
How to run bash command without stalling my terminal
I want to run an app that stalls my terminal but then I need to use that terminal again and can't have it stall, is there some sort of prefix I can apply to a command that will allow it to run asynchronously? Example:</p>
```<code>async mousepad
</code>```

答:
You need to run it in the background. The screen tool is recommended

Screen supports session recovery, multi window and session sharing

Session recovery

As long as the screen itself is not terminated, the session running inside it can be resumed. This is especially useful for remote login users - even if the network connection is interrupted, the user will not lose control of the opened command line session. Just log in to the host again and execute screen - r to resume the operation of the session. Similarly, when you leave temporarily, you can also execute the detach command detach to suspend the screen (switch to the background) while ensuring the normal operation of the program inside. This is very similar to VNC in the graphical interface.

Multi window

In the screen environment, all sessions run independently and have their own number, input, output and window cache. Users can switch between different windows through shortcut keys, and can freely redirect the input and output of each window. Screen realizes basic text operations, such as copy and paste; It also provides a function similar to scroll bar, which can view the history of window status. Windows can also be partitioned and named, and the activity of background windows can be monitored.

Session sharing

Screen allows one or more users to log in to a session multiple times from different terminals and share all the features of the session (for example, you can see exactly the same output). It also provides the mechanism of window access permission, which can protect the window with password.

Body:
I want to run an app that stalls my terminal but then I need to use that terminal again and can't have it stall, is there some sort of prefix I can apply to a command that will allow it to run asynchronously? Example:

async mousepad


问:
Adding syntactic sugar to C++

Edit 2:

New edit: it looks like C++20 has a new ranges library, which does what I want from the functional point of view. How would something similar be done on C++17 or earlier? Also, would the Kotlin syntactic sugar be possible? Mainly the person example:

val adam = Person("Adam").apply {
    age = 20 // same as this.age = 20 or adam.age = 20
    city = "London"
}
```
<h3>Edit 1:</h3>
<p>I don't know if my question was that clear, so I'll give an example using Rust's map.</p>
<p>This is how a map is done in rust:</p>
<pre class="lang-rust prettyprint-override"><code>let newVector = myVector.iter().map(|x|, x * 2)
</code>```

This is how it is done in C++

std::string s("hello");
std::vector<std::size_t> ordinals;
std::transform(s.begin(), s.end(), std::back_inserter(ordinals),
     [](unsigned char c) -> std::size_t { return c; });
```
<p>This is a lot more verbose.</p>
<p>I'd like to add some syntactic sugar to do something like this instead:</p>
<pre class="lang-cpp prettyprint-override"><code>std::string s("hello");
auto ordinals = my_ns::map(s,[](unsigned char c) -> std::size_t { return c; });
</code>```

The implementation of my_ns::map could be something like this (I'm sure this will not work, it's just to show how it could be done)

template<typename T, U>
map(T t, std::function f)
{
    std::vector ordinals;
    std::transform(t.begin(), t.end(), std::back_inserter(ordinals),
     [](U c) -> f(c));
    return ordinals;
}
```
<p>In this case <code>ordinals</code> doesn't need to be of type <code>std::vector<std::size_t></code>, it could be of a type <code>map</code> which has a conversion for <code>std::vector<T></code>. The reason for a type map is to be able to chain functions like reduce with map.</p>
<h3>Original Question</h3>
<p>Note: this is for a personal project only, I do not intend to use it in production or when working with C++ most of the time.</p>
<p>I have been using a lot of Kotlin lately and I'm dabbling a little with Rust and I love their higher level features. That got me wondering, can I create some syntactic sugar to emulate some of these features?</p>
<p>Some of the stuff I'd be trying to emulate(just an example)</p>
<p>Rust map:</p>
<pre class="lang-rust prettyprint-override"><code>let newVector = myVector.iter().map(|x|, x * 2)
</code>```

Kotlin let

val adam = Person("Adam").apply {
    age = 20 // same as this.age = 20 or adam.age = 20
    city = "London"
}

val str = "Hello"
str.let {
   println("The string's length is ${it.length}")
}

```
<p>I do not plan on using the exact same syntax, but I'd like to know if it would be possible to do something like:</p>
<pre class="lang-cpp prettyprint-override"><code>int[] arr = {1, 2, 3};
auto d_arr = map(arr, [](int x){return x*2}) // maybe return a map type to be able to use .reduce, etc
</code>```

The first kotlin let example I wouldn't know how to do, but the second could be solved using lambdas as well.

I'm thinking of using new types and create conversions to std::vector and arrays, kind of how C#'s LINQ works.

Any tips on how to do this are appreciated.

Ps: I know about std::transform and other functions(I'd probably use them when implementing this), but I'd like a simpler API than the ones offered (and I also think that it would be a nice personal project).

答:
I'd like to know if it would be possible to do something like:

```<code>int[] arr = {1, 2, 3};
auto d_arr = map(arr, [](int x){return x*2})
</code>```

"map" in this sense is called "transform" in C++ standard library. A working example:

```<code>auto double_ = [](auto x){ return x*2; }; // you may also use a normal function
auto doubled_view = std::views::all(arr)
                  | std::views::transform(double_);
</code>```

to be able to chain functions like reduce with map.

You can reduce ranges. Unfortunately, the C++20 standard ranges don't come with a reduce function, so one has to use either another implementation of ranges, or use the iterator based functions instead. Example of latter:

```<code>auto sum = std::reduce(
     std::execution::unseq, // optional execution policy
     doubled_view.begin(),
     doubled_view.end(),
     0
     // you can use a functor to do something other than add
     );
</code>```

conversions to std::vector

You can also create containers from ranges:

```<code>std::vector doubled_vector(
    doubled_view.begin(), doubled_view.end());
</code>```

Note that creating containers for intermediate stages of range views can have unnecessary overhead.

Title: Adding syntactic sugar to C++

Body:
Edit 2:

New edit: it looks like C++20 has a new ranges library, which does what I want from the functional point of view. How would something similar be done on C++17 or earlier? Also, would the Kotlin syntactic sugar be possible? Mainly the person example:

val adam = Person("Adam").apply {
    age = 20 // same as this.age = 20 or adam.age = 20
    city = "London"
}

Edit 1:

I don't know if my question was that clear, so I'll give an example using Rust's map.

This is how a map is done in rust:

let newVector = myVector.iter().map(|x|, x * 2)

This is how it is done in C++

std::string s("hello");
std::vector<std::size_t> ordinals;
std::transform(s.begin(), s.end(), std::back_inserter(ordinals),
     [](unsigned char c) -> std::size_t { return c; });

This is a lot more verbose.

I'd like to add some syntactic sugar to do something like this instead:

std::string s("hello");
auto ordinals = my_ns::map(s,[](unsigned char c) -> std::size_t { return c; });

The implementation of my_ns::map could be something like this (I'm sure this will not work, it's just to show how it could be done)

template<typename T, U>
map(T t, std::function f)
{
    std::vector ordinals;
    std::transform(t.begin(), t.end(), std::back_inserter(ordinals),
     [](U c) -> f(c));
    return ordinals;
}

In this case ordinals doesn't need to be of type std::vector<std::size_t>, it could be of a type map which has a conversion for std::vector<T>. The reason for a type map is to be able to chain functions like reduce with map.

Original Question

Note: this is for a personal project only, I do not intend to use it in production or when working with C++ most of the time.

I have been using a lot of Kotlin lately and I'm dabbling a little with Rust and I love their higher level features. That got me wondering, can I create some syntactic sugar to emulate some of these features?

Some of the stuff I'd be trying to emulate(just an example)

Rust map:

let newVector = myVector.iter().map(|x|, x * 2)

Kotlin let

val adam = Person("Adam").apply {
    age = 20 // same as this.age = 20 or adam.age = 20
    city = "London"
}

val str = "Hello"
str.let {
   println("The string's length is ${it.length}")
}

I do not plan on using the exact same syntax, but I'd like to know if it would be possible to do something like:

int[] arr = {1, 2, 3};
auto d_arr = map(arr, [](int x){return x*2}) // maybe return a map type to be able to use .reduce, etc

The first kotlin let example I wouldn't know how to do, but the second could be solved using lambdas as well.

I'm thinking of using new types and create conversions to std::vector and arrays, kind of how C#'s LINQ works.

Any tips on how to do this are appreciated.

Ps: I know about std::transform and other functions(I'd probably use them when implementing this), but I'd like a simpler API than the ones offered (and I also think that it would be a nice personal project).

Body:
I'd like to know if it would be possible to do something like:

int[] arr = {1, 2, 3};
auto d_arr = map(arr, [](int x){return x*2})

"map" in this sense is called "transform" in C++ standard library. A working example:

auto double_ = [](auto x){ return x*2; }; // you may also use a normal function
auto doubled_view = std::views::all(arr)
                  | std::views::transform(double_);

to be able to chain functions like reduce with map.

You can reduce ranges. Unfortunately, the C++20 standard ranges don't come with a reduce function, so one has to use either another implementation of ranges, or use the iterator based functions instead. Example of latter:

auto sum = std::reduce(
     std::execution::unseq, // optional execution policy
     doubled_view.begin(),
     doubled_view.end(),
     0
     // you can use a functor to do something other than add
     );

conversions to std::vector

You can also create containers from ranges:

std::vector doubled_vector(
    doubled_view.begin(), doubled_view.end());

Note that creating containers for intermediate stages of range views can have unnecessary overhead.


答:
Your example can be changed to working C++ code fairly easily:

```<code>template <typename T, typename Fun> auto map(T t, Fun f) {
  std::vector<typename T::value_type> ordinals;
  std::transform(t.begin(), t.end(), std::back_inserter(ordinals), f);
  return ordinals;
}
</code>```

This is neither very idiomatic nor optimized for performance, but it works. (Pre-resize the vector instead of using std::back_inserter and pass t by reference for a big performance boost.)

Edit: You can add reduce as follows:

```<code>template <typename T, typename R, typename Fun> auto reduce(T t, R init, Fun f) {
  return std::transform(t.begin(), t.end(), init, f);
}
</code>```

And then combine them: reduce(map(x, [](auto a) {...}), 0, [](int& a, auto b) {...})

The obvious caveat: This is going to be really slow. These functions are fun to learn template concepts, but in practice, ranges or old-style std::reduce/... will be much, much faster.

Edit 2:
If you want to use map as a member function, just make a wrapper class:

```<code>template<class T>
struct Wrapper {
  T d;
  template <typename Fun> auto map(Fun f) {
    std::vector<typename T::value_type> ordinals;
    std::transform(d.begin(), d.end(), std::back_inserter(ordinals), f);
    return wrap(ordinals);
  }
  template <typename R, typename Fun> auto reduce(R init, Fun f) {
    return wrap(std::transform(d.begin(), d.end(), init, f));
  }
};
template<class T> Wrapper<T> wrap(const T& t) { return {t}; }
template<class T> Wrapper<T> wrap(T&& t) { return {t}; }
</code>```

Then you can do wrap(my_vec).map(...).reduce(..., ...)

for loops would be faster here, because you're doing a lot of unnecessary copying: you're unnecessarily creating a new vector in map and copy data lots of times (std::back_inserter, pass-by-value).

Title: Adding syntactic sugar to C++

Body:
Your example can be changed to working C++ code fairly easily:

template <typename T, typename Fun> auto map(T t, Fun f) {
  std::vector<typename T::value_type> ordinals;
  std::transform(t.begin(), t.end(), std::back_inserter(ordinals), f);
  return ordinals;
}

This is neither very idiomatic nor optimized for performance, but it works. (Pre-resize the vector instead of using std::back_inserter and pass t by reference for a big performance boost.)

Edit: You can add reduce as follows:

template <typename T, typename R, typename Fun> auto reduce(T t, R init, Fun f) {
  return std::transform(t.begin(), t.end(), init, f);
}

And then combine them: reduce(map(x, [](auto a) {...}), 0, [](int& a, auto b) {...})

The obvious caveat: This is going to be really slow. These functions are fun to learn template concepts, but in practice, ranges or old-style std::reduce/... will be much, much faster.

Edit 2:
If you want to use map as a member function, just make a wrapper class:

template<class T>
struct Wrapper {
  T d;
  template <typename Fun> auto map(Fun f) {
    std::vector<typename T::value_type> ordinals;
    std::transform(d.begin(), d.end(), std::back_inserter(ordinals), f);
    return wrap(ordinals);
  }
  template <typename R, typename Fun> auto reduce(R init, Fun f) {
    return wrap(std::transform(d.begin(), d.end(), init, f));
  }
};
template<class T> Wrapper<T> wrap(const T& t) { return {t}; }
template<class T> Wrapper<T> wrap(T&& t) { return {t}; }

Then you can do wrap(my_vec).map(...).reduce(..., ...)

for loops would be faster here, because you're doing a lot of unnecessary copying: you're unnecessarily creating a new vector in map and copy data lots of times (std::back_inserter, pass-by-value).


问:
How to get Django StaticFileStorage to 500 when Debug is True
I'm trying to get our Django app to throw 500s when an asset is not available - rather than somewhat silently throwing 404s. We want this so that our end-to-end tests catch an asset missing before it goes to prod and starts failing.

I have WHITENOISE_MANIFEST_STRICT set to True, and I believe that Whitenoise is working - I'm using the --nostatic flag, and see the WHITENOISE_MAX_AGE in the Cache-Control Response Headers (although the assets themselves don't have the hash that we see in production or when Debug is set to false).

However I'm still getting 404s for an asset that doesn't exist. Unfortunately we can't use DEBUG = False because the tests themselves depend on Debug being true, so any advice would be super appreciated!

答:
It turns out this behavior is different because when DEBUG is enabled, Django does not do the hash file resolution that is standard.

You can override the behavior using the file resolution: Force Django ManifestStaticFilesStorage to always return urls with hashes


问:
How do I drop to the IRB prompt from a running script?
Can I drop to an IRB prompt from a running Ruby script?

I want to run a script, but then have it give me an IRB prompt at a point in the program with the current state of the program, but not just by running rdebug and having a breakpoint.

答:
Pry (an IRB alternative) also lets you do this, in fact it was designed from the ground up for exactly this use case :)

It's as easy as putting binding.pry at the point you want to start the session:

```<code>require 'pry'
x = 10
binding.pry
</code>```

And inside the session:

```<code>pry(main)> puts x
=> 10
</code>```

Check out the website: http://pry.github.com

Pry let's you:

drop into a session at any point in your code

view method source code

view method documentation (not using RI so you dont have to pre-generate it)

pop in and out of different contexts

syntax highlighting

gist integration

view and replay history

open editors to edit methods using edit obj.my_method syntax

A tonne more great and original features

Body:
Pry (an IRB alternative) also lets you do this, in fact it was designed from the ground up for exactly this use case :)

It's as easy as putting binding.pry at the point you want to start the session:

require 'pry'
x = 10
binding.pry

And inside the session:

pry(main)> puts x
=> 10

Check out the website: http://pry.github.com

Pry let's you:

drop into a session at any point in your code

view method source code

view method documentation (not using RI so you dont have to pre-generate it)

pop in and out of different contexts

syntax highlighting

gist integration

view and replay history

open editors to edit methods using edit obj.my_method syntax

A tonne more great and original features


问:
Is there any ways to make this code shorter?
Is there any ways to make this code shorter?
I'm coding with jQuery.

```
<pre class="lang-js prettyprint-override"><code>
$('.js-unchecked').click(function() {
    $(this).slideUp(0);
    $(this).parent('.js-check-container').find('.js-checked').slideDown(0);
})
$('.js-checked').click(function() {
    $(this).slideUp(0);
    $(this).parent('.js-check-container').find('.js-unchecked').slideDown(0);
})
</code>```

答:
You can add the same handler to both, and inside the handler, check whether the clicked element has the js-checked or js-unchecked class, from which you can generate the string to pass into .find.

```<code>$('.js-checked, .js-unchecked').click(function() {
    const justClickedChecked = this.classList.contains('js-checked);
    $(this).slideUp(0);
    $(this)
        .parent('.js-check-container')
        .find(`.js-${justClickedChecked ? 'un' : ''}checked`)
        .slideDown(0);
})
</code>```

Body:
Is there any ways to make this code shorter?
I'm coding with jQuery.

$('.js-unchecked').click(function() {
    $(this).slideUp(0);
    $(this).parent('.js-check-container').find('.js-checked').slideDown(0);
})
$('.js-checked').click(function() {
    $(this).slideUp(0);
    $(this).parent('.js-check-container').find('.js-unchecked').slideDown(0);
})

Body:
You can add the same handler to both, and inside the handler, check whether the clicked element has the js-checked or js-unchecked class, from which you can generate the string to pass into .find.

$('.js-checked, .js-unchecked').click(function() {
    const justClickedChecked = this.classList.contains('js-checked);
    $(this).slideUp(0);
    $(this)
        .parent('.js-check-container')
        .find(`.js-${justClickedChecked ? 'un' : ''}checked`)
        .slideDown(0);
})


问:
How I can change the mimetype to render in VSCode Jupyter Notebook
How I can change the mimetype to render in VSCode Jupyter Notebook like jupyter notebook or colab?

in VSCode Jupyter Notebook show only output like this picture
enter image description here

but in jupyter notebook/colab show like this
enter image description here

I want to change like jupyter notebook/colab. please help me

答:
For now, the jupyter notebook in VSCode only can accept the inputs in the input box.

So you can switch to python file and execute it in the terminal(right-click -> Run Python File in Terminal).


问:
Specialising Range or overloading ".."
I have a little library where I can define integer types. These are intended for type-safe indexing into arrays and strings in the kind of algorithms I often write. For example, I can use it to define an offset type, Offset and an index type, Idx such that you can get an Offset by subtracting two Idx, you can get Idx by adding or subtracting Offset, but you cannot for example multiple or add Idx.

let (i,j): (Idx,Idx) = ...;
let offset: Offset = j - i; // Subtracting indices gives an offset
let k: Idx = j + offset; // Adding an offset to an index gives an index
// let _ = i + j; -- You can't add indices
```
<p>I managed (with some difficulty) to implement <code>std::iter::Step</code> so I can also iterate through a range of indices</p>
<pre class="lang-rust prettyprint-override"><code>for k in i .. j { /* ... */ }
</code>```

but now I've set my eyes on a higher goal: I also want to use ranges of these types to slice into sequences

let v: Vec<sometype> = vec![...];
let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
```
<p>This should be a simple matter of implementing <code>std::ops::Index</code> and <code>std::ops::IndexMut</code>, except that the type system won't let me implement</p>
<pre class="lang-rust prettyprint-override"><code>impl<I,T> std::ops::Index<std::ops::Range<I>> for Vec<T>
where I: /* my types */
{ ... }
</code>```

for a wrapper type, or a generic

impl std::ops::Index<std::ops::Range<Wrapper>> for Vec<T>
where I: /* my types */
{ ... }
```
<p>where <code>Wrapper</code> is the type I actually use and <code>I</code> a trait that helps me write generic code.</p>
<p>The problem is that both <code>Index</code> and <code>Range</code> are defined outside of my crate, so this kind of specialisation is not allowed. Or is it?</p>
<p>Is there any way that I can implement a trait for a generic type outside my crate when its generic parameters are from within my crate?</p>
<p>Or, better still, is there any way to tap into the syntactic sugar of the <code>..</code> operator, so I can get a wrapped type? What I <em>really</em> want is to wrap <code>Range</code> to get the same behaviour and then some. I can do that by wrapping <code>Range</code> and implementing <code>Deref</code>, but if I go that route, I lose the syntactic sugar of the <code>..</code> operator.</p>
<p>It is not a big problem, but I can imagine some confusion when you could write</p>
<pre class="lang-rust prettyprint-override"><code>for k in i .. j { /* ... */ }
</code>```

like you can for the built-in types, but you have to use

let w: &[type] = &v[range(i,j)];
```

for slicing. It gets even more cumbersome if I want to allow slices such as i.., ..j to be wrapped. (The .. slice doesn't matter here, it won't get my types anyway). If I did that, I would need constructors for three types of ranges, or some ugly wrapping using Option, I think.

The .. syntactic sugar is really neat, but from what I have explored you just cannot use that much for ranges of your own types. You can define ranges and you can, with some hacking, iterate through them, but you can't index with them.

Tell me I'm wrong, or let me know if there are any tricks that gets the job done, or even half-done. Or, if this is indeed impossible, let me know so I can stop wasting time on it and write a wrapper class and give up on the .. operator.

Update I have put a simplified example in playgrounds

答:
No, you can't.

By definition of the orphan rules:

Given impl<P1..=Pn> Trait<T1..=Tn> for T0, an impl is valid only if at least one of the following is true:

Trait is a local trait

All of

At least one of the types T0..=Tn must be a local type. Let Ti be the first such type.

No uncovered type parameters P1..=Pn may appear in T0..Ti (excluding Ti)

Only the appearance of uncovered type parameters is restricted. Note that for the purposes of coherence, fundamental types are special. The T in Box is not considered covered, and Box is considered local.

Local trait

A trait which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given trait Foo<T, U>, Foo is always local, regardless of the types substituted for T and U.

Local type

A struct, enum, or union which was defined in the current crate. This is not affected by applied type arguments. struct Foo is considered local, but Vec<Foo> is not. LocalType<ForeignType> is local. Type aliases do not affect locality.

As neither Index nor Range nor Vec are local, and Range is not a fundamental type, you cannot impl<T> Index<Range<...>> for Vec<T>, no matter what you put in the place of the ....

The reason for these rules is that nothing prevents Range or Vec from implementing impl<T, Idx> Index<Range<Idx>> for Vec<T>. Such impl does not exist, and probably never will, but the rules are the same among all types, and in the general case this definitely can happen.

You cannot overload the range operator either - it always creates a Range (or RangeInclusive, RangeFull, etc.).

The only solution I can think about is to create a newtype wrapper for Vec, as suggested in the comments.

If you want your vector to return a wrapped slice, you can use a bit of unsafe code:

use std::ops::{Index, IndexMut, Range, Deref, DerefMut};

#[repr(transparent)] // Because of this we can soundly cast `&{mut }[T]` to `&{mut }MySlice<T>`.
pub struct MySlice<T>([T]);

impl<'a, T> From<&'a [T]> for &'a MySlice<T> {
    fn from(v: &'a [T]) -> &'a MySlice<T> {
        unsafe { &*(v as *const [T] as *const MySlice<T>) }
    }
}
impl<'a, T> From<&'a mut [T]> for &'a mut MySlice<T> {
    fn from(v: &'a mut [T]) -> &'a mut MySlice<T> {
        unsafe { &mut *(v as *mut [T] as *mut MySlice<T>) }
    }
}

impl<T> Index<usize> for MySlice<T> {
    type Output = T;
    fn index(&self, idx: usize) -> &Self::Output { &self.0[idx] }
}
impl<T> IndexMut<usize> for MySlice<T> {
    fn index_mut(&mut self, idx: usize) -> &mut Self::Output { &mut self.0[idx] }
}

impl<T> Index<Range<usize>> for MySlice<T> {
    type Output = MySlice<T>;
    fn index(&self, idx: Range<usize>) -> &Self::Output { self.0[idx].into() }
}
impl<T> IndexMut<Range<usize>> for MySlice<T> {
    fn index_mut(&mut self, idx: Range<usize>) -> &mut Self::Output { (&mut self.0[idx]).into() }
}
// And so on, for all range types...

pub struct MyVec<T>(pub Vec<T>);

impl<T> Deref for MyVec<T> {
    type Target = MySlice<T>;
    fn deref(&self) -> &Self::Target { self.0.as_slice().into() }
}
impl<T> DerefMut for MyVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target { self.0.as_mut_slice().into() }
}
```

Title: Specialising Range or overloading ".."

Body:
I have a little library where I can define integer types. These are intended for type-safe indexing into arrays and strings in the kind of algorithms I often write. For example, I can use it to define an offset type, Offset and an index type, Idx such that you can get an Offset by subtracting two Idx, you can get Idx by adding or subtracting Offset, but you cannot for example multiple or add Idx.

let (i,j): (Idx,Idx) = ...;
let offset: Offset = j - i; // Subtracting indices gives an offset
let k: Idx = j + offset; // Adding an offset to an index gives an index
// let _ = i + j; -- You can't add indices

I managed (with some difficulty) to implement std::iter::Step so I can also iterate through a range of indices

for k in i .. j { /* ... */ }

but now I've set my eyes on a higher goal: I also want to use ranges of these types to slice into sequences

let v: Vec<sometype> = vec![...];
let w: &[sometype] = &v[i..j]; // Slice with a range of Idx

This should be a simple matter of implementing std::ops::Index and std::ops::IndexMut, except that the type system won't let me implement

impl std::ops::Index<std::ops::Range> for Vec<T>
where I: /* my types */
{ ... }

for a wrapper type, or a generic

impl std::ops::Index<std::ops::Range<Wrapper>> for Vec<T>
where I: /* my types */
{ ... }

where Wrapper is the type I actually use and I a trait that helps me write generic code.

The problem is that both Index and Range are defined outside of my crate, so this kind of specialisation is not allowed. Or is it?

Is there any way that I can implement a trait for a generic type outside my crate when its generic parameters are from within my crate?

Or, better still, is there any way to tap into the syntactic sugar of the .. operator, so I can get a wrapped type? What I really want is to wrap Range to get the same behaviour and then some. I can do that by wrapping Range and implementing Deref, but if I go that route, I lose the syntactic sugar of the .. operator.

It is not a big problem, but I can imagine some confusion when you could write

for k in i .. j { /* ... */ }

like you can for the built-in types, but you have to use

let w: &[type] = &v[range(i,j)];

for slicing. It gets even more cumbersome if I want to allow slices such as i.., ..j to be wrapped. (The .. slice doesn't matter here, it won't get my types anyway). If I did that, I would need constructors for three types of ranges, or some ugly wrapping using Option, I think.

The .. syntactic sugar is really neat, but from what I have explored you just cannot use that much for ranges of your own types. You can define ranges and you can, with some hacking, iterate through them, but you can't index with them.

Tell me I'm wrong, or let me know if there are any tricks that gets the job done, or even half-done. Or, if this is indeed impossible, let me know so I can stop wasting time on it and write a wrapper class and give up on the .. operator.

Update I have put a simplified example in playgrounds


问:
Removing multiple headers in a single excel sheet
Similar to Remove header row in Excel using pandas

I wish to remove headers from an excel sheet.

Using the same example but edited:

```<code>Company ABC

Account Name 1
Account No.1
Description    group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
totals                               sum values

Account Name 2
Account No.2
Description    group     pair          amount    ...  result
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
totals                               sum values

Sales
00234
Description    group     pair          amount    ...  result
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
totals                               sum values

Inventory
00012345
Description    group     pair          amount    ...  result
value7         value7    value7        value7    ...  value7
value8         value8    value8        value8    ...  value8
value9         value9    value9        value9    ...  value9
totals                               sum values
</code>```

I wish to concatenate it to become like

```<code>cabinet_name   group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
value7         value7    value7        value7    ...  value7
value8         value8    value8        value8    ...  value8
value9         value9    value9        value9    ...  value9
</code>```

I've managed to remove the top header by skipping rows e.g.(skiprows = 4). However, This still leaves the other headers and totals which append like so:

```<code>cabinet_name   group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
totals                               sum values
Account Name 2
Account No.2
cabinet_name   group     pair          amount    ...  result
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
totals                               sum values
Sales
00234
Description    group     pair          amount    ...  result
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
totals                               sum values
Inventory
00012345
Description    group     pair          amount    ...  result
value7         value7    value7        value7    ...  value7
value8         value8    value8        value8    ...  value8
value9         value9    value9        value9    ...  value9
totals                               sum values
</code>```

Would be extremely grateful if someone could enlighten me on how to clean this sheet with pandas as all I've seen online are working on only 1 table in a single excel sheet.

Let me know if I've missed anything out, I would gladly edit this question.

I thought this might be useful,

My usual process for cleaning the files in excel, is to firstly delete the first 4 rows, only leaving

```<code>cabinet_name   group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
totals         *blank*   *blank*       sum values

Account Name 2
Account No.2
cabinet_name   group     pair          amount    ...  result
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
totals         *blank*   *blank*       sum values

Account Name 3
Account No.3
cabinet_name   group     pair          amount    ...  result
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
totals         *blank*   *blank*       sum values
</code>```

Then I will filter group or pair to look for blank values in said column and deleting it.

This is the result of

```<code>print(df_total.head(8).to_dict())
</code>```
```<code>import datetime
from numpy import nan
{'Date': {0: nan, 1: datetime.datetime(2021, 1, 1, 0, 0), 2: datetime.datetime(2021, 1, 1, 0, 0), 3: datetime.datetime(2021, 1, 29, 0, 0), 4: datetime.datetime(2021, 1, 31, 0, 0), 5:
'Totals', 6: 'Net difference', 7: nan},
'Journal number': {0: nan, 1: 'AX009473', 2: 'AX009473', 3: 'AX003312', 4: 'AX009641', 5: nan, 6: nan, 7: nan},
'Voucher': {0: nan, 1: 'TSPN-2021-3', 2: 'TSPN-2021-3', 3: 'GBJ-2021-1', 4: 'VIT-2021-1', 5: nan, 6: nan, 7: nan},
'Posting type': {0: nan, 1: nan, 2: nan, 3: 'Ledger journal', 4: 'Ledger journal', 5: nan, 6: nan, 7: nan},
'Ledger account': {0: nan, 1: '00388211', 2: '00388211', 3: '00388211', 4: '00388211', 5: nan, 6: nan, 7: nan},
'Description': {0: nan, 1: nan, 2: nan, 3: 'DISBERSMENT FOR PETROL', 4: 'TAXI FAIR', 5: nan, 6: nan, 7: nan},
'Unnamed: 6': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan},
'Unnamed: 7': {0: nan, 1: 'SGD', 2: 'USD', 3: 'SGD', 4: 'SGD', 5: nan, 6: nan, 7: nan},
'Amount in transaction currency': {0: 'Debit', 1: 13.55, 2: 0, 3: 0, 4: 5, 5: nan, 6: nan, 7: nan}, 'Unnamed: 9': {0: 'Credit', 1: 0, 2: 25, 3: 52, 4: 0, 5: nan, 6: nan, 7: nan},
'Amount in accounting currency': {0: 'Debit', 1: 13.55, 2: 0, 3: 0, 4: 5, 5: 18.55, 6: nan, 7: nan}, 'Unnamed: 11': {0: 'Credit', 1: 0, 2: 33.42, 3: 52, 4: 0, 5: 85.42, 6: 66.87, 7: nan},
'Amount in reporting currency': {0: 'Debit', 1: 13.55, 2: 0, 3: 0, 4: 5, 5: 18.55, 6: nan, 7: nan}, 'Unnamed: 13': {0: 'Credit', 1: 0, 2: 33.42, 3: 52, 4: 0, 5: 85.42, 6: nan, 7: nan},
'Unnamed: 14': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan}, 'Unnamed: 15': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan}, 'Unnamed: 16': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan}}
</code>```

Created a specimen excel of what I have

VS

An excel of transformed data

答:
Presumably, the first 3 rows and the rows with "totals" and "sum values" have empty cells, so dropna should eliminate those rows. Then drop_duplicates with keep=False parameter should drop the the duplicate column names:

```<code>out = df.replace('', np.nan).replace(' ', np.nan).dropna().drop_duplicates()
</code>```

I just can't test it because your read_clipboard complains about the format of your data.

Body:
Similar to Remove header row in Excel using pandas

I wish to remove headers from an excel sheet.

Using the same example but edited:

Company ABC

Account Name 1
Account No.1
Description    group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
totals                               sum values

Account Name 2
Account No.2
Description    group     pair          amount    ...  result
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
totals                               sum values

Sales
00234
Description    group     pair          amount    ...  result
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
totals                               sum values

Inventory
00012345
Description    group     pair          amount    ...  result
value7         value7    value7        value7    ...  value7
value8         value8    value8        value8    ...  value8
value9         value9    value9        value9    ...  value9
totals                               sum values

I wish to concatenate it to become like

cabinet_name   group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
value7         value7    value7        value7    ...  value7
value8         value8    value8        value8    ...  value8
value9         value9    value9        value9    ...  value9

I've managed to remove the top header by skipping rows e.g.(skiprows = 4). However, This still leaves the other headers and totals which append like so:

cabinet_name   group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
totals                               sum values
Account Name 2
Account No.2
cabinet_name   group     pair          amount    ...  result
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
totals                               sum values
Sales
00234
Description    group     pair          amount    ...  result
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
totals                               sum values
Inventory
00012345
Description    group     pair          amount    ...  result
value7         value7    value7        value7    ...  value7
value8         value8    value8        value8    ...  value8
value9         value9    value9        value9    ...  value9
totals                               sum values

Would be extremely grateful if someone could enlighten me on how to clean this sheet with pandas as all I've seen online are working on only 1 table in a single excel sheet.

Let me know if I've missed anything out, I would gladly edit this question.

I thought this might be useful,

My usual process for cleaning the files in excel, is to firstly delete the first 4 rows, only leaving

cabinet_name   group     pair          amount    ...  result
value1         value1    value1        value1    ...  value1
value2         value2    value2        value2    ...  value2
totals         *blank*   *blank*       sum values

Account Name 2
Account No.2
cabinet_name   group     pair          amount    ...  result
value3         value3    value3        value3    ...  value3
value4         value4    value4        value4    ...  value4
totals         *blank*   *blank*       sum values

Account Name 3
Account No.3
cabinet_name   group     pair          amount    ...  result
value5         value5    value5        value5    ...  value5
value6         value6    value6        value6    ...  value6
totals         *blank*   *blank*       sum values

Then I will filter group or pair to look for blank values in said column and deleting it.

This is the result of

print(df_total.head(8).to_dict())

import datetime
from numpy import nan
{'Date': {0: nan, 1: datetime.datetime(2021, 1, 1, 0, 0), 2: datetime.datetime(2021, 1, 1, 0, 0), 3: datetime.datetime(2021, 1, 29, 0, 0), 4: datetime.datetime(2021, 1, 31, 0, 0), 5:
'Totals', 6: 'Net difference', 7: nan},
'Journal number': {0: nan, 1: 'AX009473', 2: 'AX009473', 3: 'AX003312', 4: 'AX009641', 5: nan, 6: nan, 7: nan},
'Voucher': {0: nan, 1: 'TSPN-2021-3', 2: 'TSPN-2021-3', 3: 'GBJ-2021-1', 4: 'VIT-2021-1', 5: nan, 6: nan, 7: nan},
'Posting type': {0: nan, 1: nan, 2: nan, 3: 'Ledger journal', 4: 'Ledger journal', 5: nan, 6: nan, 7: nan},
'Ledger account': {0: nan, 1: '00388211', 2: '00388211', 3: '00388211', 4: '00388211', 5: nan, 6: nan, 7: nan},
'Description': {0: nan, 1: nan, 2: nan, 3: 'DISBERSMENT FOR PETROL', 4: 'TAXI FAIR', 5: nan, 6: nan, 7: nan},
'Unnamed: 6': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan},
'Unnamed: 7': {0: nan, 1: 'SGD', 2: 'USD', 3: 'SGD', 4: 'SGD', 5: nan, 6: nan, 7: nan},
'Amount in transaction currency': {0: 'Debit', 1: 13.55, 2: 0, 3: 0, 4: 5, 5: nan, 6: nan, 7: nan}, 'Unnamed: 9': {0: 'Credit', 1: 0, 2: 25, 3: 52, 4: 0, 5: nan, 6: nan, 7: nan},
'Amount in accounting currency': {0: 'Debit', 1: 13.55, 2: 0, 3: 0, 4: 5, 5: 18.55, 6: nan, 7: nan}, 'Unnamed: 11': {0: 'Credit', 1: 0, 2: 33.42, 3: 52, 4: 0, 5: 85.42, 6: 66.87, 7: nan},
'Amount in reporting currency': {0: 'Debit', 1: 13.55, 2: 0, 3: 0, 4: 5, 5: 18.55, 6: nan, 7: nan}, 'Unnamed: 13': {0: 'Credit', 1: 0, 2: 33.42, 3: 52, 4: 0, 5: 85.42, 6: nan, 7: nan},
'Unnamed: 14': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan}, 'Unnamed: 15': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan}, 'Unnamed: 16': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan, 6: nan, 7: nan}}

Created a specimen excel of what I have

VS

An excel of transformed data

Body:
Presumably, the first 3 rows and the rows with "totals" and "sum values" have empty cells, so dropna should eliminate those rows. Then drop_duplicates with keep=False parameter should drop the the duplicate column names:

out = df.replace('', np.nan).replace(' ', np.nan).dropna().drop_duplicates()

I just can't test it because your read_clipboard complains about the format of your data.


问:
Problems using circular array to take inputs and stop/print the last 10 elements once "-1" is entered
I have a Java program that should be doing what the above title describes. Unfortunately, I am now having the issue of having nothing but zeros and a Error message no matter what I input into Scanner.

The code:

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

  //Set variable
  int count = 0;
  int numInput = 0;
  int arrSize = 10;

  //Set and initialize string
  int[] numArray = new int[arrSize];

  //Set and initialize Scanner
  Scanner sc = new Scanner(System.in);
  System.out.println("Please input some numbers. Stop by typing -1:");

  while (numInput != -1) {
     numInput = sc.nextInt();
     //Check if input is integer or not
     if (numInput == (int)numInput) {
        if (count == -1) {
           count = numArray.length - 1;
        } else if (count == numArray.length) {
           //Append input to array
           numArray[count] = numInput;
           count++;
        }//End of conditional
     } else {
        //Error message
        System.out.println("Enter a valid integer:");
     }//End of conditional
  }//End of while loop

  //Print array with for loop
  for (int i = 0; i <= 10; i++) {
     System.out.print(numArray[i] + " ");
  }//End of for loop

  System.out.println("\n");

  sc.close();

}// End of main
</code>```

The output:

```<code>0 0 0 0 0 0 0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at last10.main(last10.java:42)
</code>```

答:
Circular array? Here is an example.

public class Main
{
    public static void main(String[] args)
    {
        final byte[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        System.out.println(array[cycle(-1,10)]); // 9
    }

    public static final int cycle(final int index, final int quantity)
    {
        return ((index % quantity) + quantity) % quantity;
    }
}
```

Body:
I have a Java program that should be doing what the above title describes. Unfortunately, I am now having the issue of having nothing but zeros and a Error message no matter what I input into Scanner.

The code:

 public static void main(String[] args) {

  //Set variable
  int count = 0;
  int numInput = 0;
  int arrSize = 10;

  //Set and initialize string
  int[] numArray = new int[arrSize];

  //Set and initialize Scanner
  Scanner sc = new Scanner(System.in);
  System.out.println("Please input some numbers. Stop by typing -1:");

  while (numInput != -1) {
     numInput = sc.nextInt();
     //Check if input is integer or not
     if (numInput == (int)numInput) {
        if (count == -1) {
           count = numArray.length - 1;
        } else if (count == numArray.length) {
           //Append input to array
           numArray[count] = numInput;
           count++;
        }//End of conditional
     } else {
        //Error message
        System.out.println("Enter a valid integer:");
     }//End of conditional
  }//End of while loop

  //Print array with for loop
  for (int i = 0; i <= 10; i++) {
     System.out.print(numArray[i] + " ");
  }//End of for loop

  System.out.println("\n");

  sc.close();

}// End of main

The output:

0 0 0 0 0 0 0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at last10.main(last10.java:42)


问:
NullPointerException on JdbcTemplate when calling SqlServer
I'm trying to make a query into a SqlServer, but it's always returning a NullPointerException. I don't know if it's possible that the url is incorrect (I don't think so), but here is my application.properties:

```<code>spring.datasource.url=jdbc:sqlserver://my_database_url;databaseName=my_database_name
spring.datasource.username=my_username
spring.datasource.password=my_password
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
</code>```

This is my controller:

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

Implementation implementation = new Implementation();

@GetMapping("/something")
public List<User> something(){
    return implementation.getSomething();
}
</code>```

And this is my implementation class:

```<code>@Autowired
private JdbcTemplate jdbcTemplate;

public List<User> getSomething(){
    return jdbcTemplate.query("SELECT * FROM users", BeanPropertyRowMapper.newInstance(User.class));
}
</code>```

Here is the error:

```<code>2022-02-07 21:22:12.207 ERROR 13476 --- [nio-8080-exec-1] o.a.c.c.C.[.[.
[/].[dispatcherServlet]    : Servlet.service() for servlet
[dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is java.lang.NullPointerException]
with root cause

java.lang.NullPointerException: null
    at
com.back.project.Implementation.getSomething(Implementation.java:23) ~
[classes/:na]
    at com.back.project.Controller.something(Controller.java:15) ~
[classes/:na]
</code>```

Thanks for your time and your help

答: You should make sure that the Implementation is a Spring bean and inject the object using @Autowired instead of using new.

Body:
I'm trying to make a query into a SqlServer, but it's always returning a NullPointerException. I don't know if it's possible that the url is incorrect (I don't think so), but here is my application.properties:

spring.datasource.url=jdbc:sqlserver://my_database_url;databaseName=my_database_name
spring.datasource.username=my_username
spring.datasource.password=my_password
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

This is my controller:

@RestController
public class Controller {

Implementation implementation = new Implementation();

@GetMapping("/something")
public List<User> something(){
    return implementation.getSomething();
}

And this is my implementation class:

@Autowired
private JdbcTemplate jdbcTemplate;

public List<User> getSomething(){
    return jdbcTemplate.query("SELECT * FROM users", BeanPropertyRowMapper.newInstance(User.class));
}

Here is the error:

2022-02-07 21:22:12.207 ERROR 13476 --- [nio-8080-exec-1] o.a.c.c.C.[.[.
[/].[dispatcherServlet]    : Servlet.service() for servlet
[dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is java.lang.NullPointerException]
with root cause

java.lang.NullPointerException: null
    at
com.back.project.Implementation.getSomething(Implementation.java:23) ~
[classes/:na]
    at com.back.project.Controller.something(Controller.java:15) ~
[classes/:na]

Thanks for your time and your help


问:
Add Data To a New Sheet
I have a data validation list value which my macro will copy data to a specific place in the workbook based on this value. However, when a value is selected from the data validation list the macro skips the IF statement, as if the statement is false. Could you please help me understand why this is happening? If I remove the data validation, the macro works as expected. Thank You!

Sub AddToList()

    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim lRow1 As Long
    Dim lRow2 As Long
    Dim lRow3 As Long
    Dim lRow4 As Long

    Application.ScreenUpdating = False

    Set ws1 = ThisWorkbook.Worksheets("DILUTION CALCULATOR")
    Set ws2 = ThisWorkbook.Worksheets("SETUP")

    lRow1 = ws2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    lRow2 = ws2.Cells(Rows.Count, 5).End(xlUp).Offset(1, 0).Row
    lRow3 = ws2.Cells(Rows.Count, 9).End(xlUp).Offset(1, 0).Row
    lRow4 = ws2.Cells(Rows.Count, 13).End(xlUp).Offset(1, 0).Row

    If ws1.Range("M4") = "" Or ws1.Range("O4") = "" Or ws1.Range("Q4") = "" Then
        MsgBox "Please Enter Data In All Fields", vbCritical
        Exit Sub
    ElseIf ws1.Range("M4") = "Customer" Then
        ws1.Range("O4 , Q4").Copy
        ws2.Cells(lRow1, 1).PasteSpecial Paste:=xlValues
    ElseIf ws1.Range("M4") = "Order Number" Then
        ws1.Range("O4 , Q4").Copy
        ws2.Cells(lRow2, 5).PasteSpecial Paste:=xlValues
    ElseIf ws1.Range("M4") = "Quantity" Then
        ws1.Range("O4 , Q4").Copy
        ws2.Cells(lRow3, 9).PasteSpecial Paste:=xlValues
    ElseIf ws1.Range("M4") = "Status" Then
        ws1.Range("O4 , Q4").Copy
        ws2.Cells(lRow4, 13).PasteSpecial Paste:=xlValues
    End If

    ws1.Range("M4, O4, Q4").ClearContents

    Application.ScreenUpdating = True

End Sub
```

答:
Copy to Another Worksheet

Option Explicit

Sub AddToList()

    Const sName As String = "DILUTION CALCULATOR"
    Const srgAddress As String = "M4,O4,Q4" ' at least two cells

    Const dName As String = "SETUP"
    ' Both arrays have to have the same number of elements.
    Dim dCols As Variant: dCols = VBA.Array(1, 5, 9, 13)
    Dim Criteria As Variant
    Criteria = VBA.Array("Customer", "Order Number", "Quantity", "Status")

    Dim wb As Workbook: Set wb = ThisWorkbook

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim srg As Range: Set srg = sws.Range(srgAddress)
    Dim cCount As Long: cCount = srg.Cells.Count

    Dim sCell As Range

    For Each sCell In srg.Cells
        If Len(CStr(sCell.Value)) = 0 Then
            MsgBox "Please enter data in all fields.", vbCritical
            Exit Sub
        End If
    Next sCell

    Dim cIndex As Variant
    cIndex = Application.Match(CStr(srg.Cells(1).Value), Criteria, 0)

    If IsError(cIndex) Then
        MsgBox "Criteria not found.", vbCritical
        Exit Sub
    End If

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    Dim drg As Range: Set drg = dws.Cells(dws.Rows.Count, dCols(cIndex - 1)) _
        .End(xlUp).Offset(1).Resize(, cCount - 1)

    Dim dc As Long

    For Each sCell In srg.Cells
        If dc > 0 Then
            drg.Cells(dc).Value = sCell.Value
        End If
        dc = dc + 1
    Next sCell

    srg.ClearContents

End Sub
```

Title: Add Data To a New Sheet


问:
Javascript click event not running on all class elements
I have a button of class 'add' which, when clicked simply clones itself and its other div siblings.  The cloning works fine, however the click functionality only works on the first instance of the button (the one that loads with the page) and not on any subsequent instances.

Any help would be great.

```<code>$('.add').click(function(){
        cloneDiv();
    });
</code>```

答:
Use the live method for dynamically added elements:

```<code>$('.add').live('click', function(){
    // your code...
});
</code>```

Body:
I have a button of class 'add' which, when clicked simply clones itself and its other div siblings.  The cloning works fine, however the click functionality only works on the first instance of the button (the one that loads with the page) and not on any subsequent instances.

Any help would be great.

$('.add').click(function(){
        cloneDiv();
    });

Body:
Use the live method for dynamically added elements:

$('.add').live('click', function(){
    // your code...
});


问:
How to find intersection point between circle and line(2 points) using Mapbox(Turf)
I'm finding how to find intersection point between circle and line(2 points) using Mapbox(Turf).

Turfjs provides "intersect" function but Turf in java doesn't provide that function.

I wonder how to calculate intersection point(longitude and latitude).

My code below:

public void circleIntersectionPointTest() {
        Point circleCenter = Point.fromLngLat(1.0, 1.0);
        double circleRadius = 35; //nautical mile
        Polygon circle = TurfTransformation.circle(circleCenter, circleRadius, TurfConstants.UNIT_NAUTICAL_MILES);

        Point innerPoint = Point.fromLngLat(1.0, 0.5);
        Point outerPoint = Point.fromLngLat(2.0, 1.5);

        //how to find between circle and line with innerPoint and outerPoint
        Point intersectionPoint;
    }
```

答:
So here's how you do it:

Find the angle: The angle (in radians) is

```<code> double xdiff = x1 - x2;
 double ydiff = y1 - y2;
 //double tan = xdiff / ydiff;
 double atan = Math.atan2(ydiff, xdiff);
 return atan;
</code>```

Now you can find the point on the circle, via

```<code>circleCenter.x + sin(angle) * circleRadius, circleCenter.y + cos(angle) * circleRadius
</code>```

It's been a while and you should check that I am invoking atan2 the right way, and cosine should be applied to the x parameter and sin to the y parameter - the way trigonometry is taught in school, angles go the opposite way as how we think of them on a compass, so there's some confusion here. But this should give you the idea of how to solve this.

For more, you can check

https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/MathUtils.java

Body:
So here's how you do it:

Find the angle: The angle (in radians) is

 double xdiff = x1 - x2;
 double ydiff = y1 - y2;
 //double tan = xdiff / ydiff;
 double atan = Math.atan2(ydiff, xdiff);
 return atan;

Now you can find the point on the circle, via

circleCenter.x + sin(angle) * circleRadius, circleCenter.y + cos(angle) * circleRadius

It's been a while and you should check that I am invoking atan2 the right way, and cosine should be applied to the x parameter and sin to the y parameter - the way trigonometry is taught in school, angles go the opposite way as how we think of them on a compass, so there's some confusion here. But this should give you the idea of how to solve this.

For more, you can check

https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/MathUtils.java


问:
C language how to call a member of multi-dimensional array in corresponding to a structure
I have a problem with how to call a member of a structure. For example, there is a struct

```<code>typedef struct FAVORITE_TBL_S
{
    UI32_T apple;
    UI32_T banana;
    UI16_T puzzle;
    UI16_T car;
}FAVORITE_TBL_T;
</code>```

And in the function, I have created a multi-dimensional array about this struct.

```<code>FUNCTION_NO_T
call_myFavoriteTbl(
    const UI32_T unit,
    const UI32_T value)
{
    FUNCTION_NO_T ret = FUNCTION_E_GOOD;
    UI8_T num_of_list = 4;
    UI32_T i = 0;
    FAVORITE_TBL_T *ptr_fav = NULL;

    ptr_fav = priviate_alloc(sizeof(FAVORITE_TBL_T ) * num_of_list );
    priviate_memset(ptr_fav, 0, sizeof(FAVORITE_TBL_T ) * num_of_list );

    /* In this function, if I want to use member in the multi-dim array */
    for (i = 0, i < value, i++)
    {
        if (BRAND_PINKLADY == ptr_fav[i]->apple)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }

        if (BRAND_COSTAPICA == ptr_fav[i].banana)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }
    }

    return ret;
}
</code>```

So why ptr_fav[i]->apple is wrong and ptr_fav[i].banana is right?

答:
As ptr_fav is an array of FAVORITE_TBL_T values, ptr_fav[i] is a  FAVORITE_TBL_T value. It is not a pointer to FAVORITE_TBL_T.

As such, the . notation is correct.

Now, because ptr_fav[i] is equivalent to *(ptr + i), you might write: (ptr_fav + i)->apple, though I'm not sure why you'd want to do that.

The -> operator is used to access a field on a pointer to a structure.

Body:
I have a problem with how to call a member of a structure. For example, there is a struct

typedef struct FAVORITE_TBL_S
{
    UI32_T apple;
    UI32_T banana;
    UI16_T puzzle;
    UI16_T car;
}FAVORITE_TBL_T;

And in the function, I have created a multi-dimensional array about this struct.

FUNCTION_NO_T
call_myFavoriteTbl(
    const UI32_T unit,
    const UI32_T value)
{
    FUNCTION_NO_T ret = FUNCTION_E_GOOD;
    UI8_T num_of_list = 4;
    UI32_T i = 0;
    FAVORITE_TBL_T *ptr_fav = NULL;

    ptr_fav = priviate_alloc(sizeof(FAVORITE_TBL_T ) * num_of_list );
    priviate_memset(ptr_fav, 0, sizeof(FAVORITE_TBL_T ) * num_of_list );

    /* In this function, if I want to use member in the multi-dim array */
    for (i = 0, i < value, i++)
    {
        if (BRAND_PINKLADY == ptr_fav[i]->apple)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }

        if (BRAND_COSTAPICA == ptr_fav[i].banana)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }
    }

    return ret;
}

So why ptr_fav[i]->apple is wrong and ptr_fav[i].banana is right?


问:
Choosing DB model for an app similar to Notion, Block-based ("paragraphs") or document-based?

1. The problem

Lately, it seems that many note managers with "infinite" tree structure are choosing a block model (where each paragraph is an entry in the DB), instead of a document or file model.

Blocks
Documents

Notion
 Workflowy
 Remnote
 Dynalist
 Roam Research
Evernote
 Obsidian
 Bear app

If you find any errors in the table, please let me know.

We have been developing an app very similar to Notion for 8 months now, also using the block model, but we are considering making a radical change and switching to the document model. The structure of our blocks in MongoDB currently looks like this:

```<code>_id: "61fd3ede7f6d2cc7a53ca669"
children: Array
    0: "61fd3ee87f6d2cc7a53ca66b"
    1: "61fd3ef37f6d2cc7a53ca671"
    2: "61fd3ef77f6d2cc7a53ca673"
backlinks: Array
type: "bullet"
parentPage: Array
    _id: "61fd3ede7f6e2ccra53ca664"
    userParent: "german-jablo"
    permisionParent: "edit, comment, read"
parentParagraph: "61fd3ede7f6d2cc7a53ca668"
content: "<p>This is a paragraph</p>"
isCollapsed: false
createdAt: 2022-02-04T14:57:34.280+00:00
updatedAt: 2022-02-04T14:57:59.585+00:00
</code>```

Many pages talk about the differences of both approaches (example) although in a very vague way, so we decided to open this thread to find a more scientific answer to the question.

Features of our app

app
Blocks that can be opened as documents
Blocks that can collapse or expand their children

Notion
Page type blocks
Toggle type blocks

Workflowy
All
All

Evernote
Documents
None

Our app
Page type blocks
All others

Our app has two types of "blocks". The page type (which, like in Notion, can be inserted into any note and generate a document "inside" the current document), and the rest of the blocks, which are equivalent to the "toggle" block type in Notion (i.e. they can be collapsed or their nested children can be expanded).

2. What we have tried

In trying to answer our question (which DB model would work best for our application), we've realized that the answer is probably "it depends". Perhaps both models have strengths or weaknesses in different types of operations or situations. That is why we formulated this comparison table describing how we believe the performance of both models would be for each of these operations.

Operation
Blocks
Documents
Apparent Winner

Fetch the contents of a page
Find all paragraphs in the DB.
Search the document in the DB.
Document

Render the content of a page**
Build the tree from the paragraphs recursively. You can omit the children of paragraphs whose isCollapsed property is true
Render the document
Document

Update the content of a paragraph in the DB
Only the modified paragraph is rewritten
The whole document is rewritten
Block

Alternatives for rendering very large documents *
Blocks can be fetched or rendered as you scroll (as Workflowy does), or as you expand child paragraphs that were collapsed.
I thought that Grifds could achieve similar behavior, breaking the document into smaller chunks and bringing them in piecemeal, but it doesn't support updating an individual chunk, or even the entire document. It could also corrupt an HTML by splitting it into binary format.
Block

Import or paste content
In addition to converting the clipboard to HTML and/or sanitizing it, you must set up paragraphs with tree structure recursively. Note: Roam Research e.g. supports importing in JSON format, but generally users do not handle this format beforehand.
Only convert the clipboard to HTML and/or sanitize the clipboard
Document

Copy content**
Clipboard must be sanitized and/or transformed
Correct by default**
Document

Real-Time Collaboration
At the document level, could use some tree-based (Json) library like Automerge, or combine with some CRDT library for paragraph level.
Could use tinymce solution.
Tie? Both seem to have their advantages and disadvantages.

*Render very large documents: Most users probably do not use notes larger than 250 kb (considering that multimedia files are referenced in a separate collection). Still, in the document model, the question arises: how can we load, render or edit large documents in manageable chunks? One idea we came up with is to split HTML documents that reach large dimensions into portions of a certain size in kb, instead of splitting them into paragraphs. (It would be like a kind of Gridfs that allows you to modify the file in parts.) Could this be a good idea?

**Should the DOM be nested? In order to be able to collapse or expand nested child paragraphs, note managers with a block model structure the DOM in a nested way (paragraphs are in divs, inside their parent divs, etc.). However, an alternative in the document model could be that when the user presses tab, only that block (HTML tag such as
 or
) is assigned an attribute with a number less than or equal to 1, representing the nesting levels relative to the previous block. This way when you press tab to nest or shift-tab to un-nest, you only have to modify one attribute of an HTML element instead of many elements; and the DOM stays simple, without having nested blocks.

3. Our conclusions

We believe that for each of the rows in the comparison table, benchmarks could be done measuring the performance of both models.
Other people have done something similar here and here, comparing the performance of note managers using both models. The problem with those tests is that it is difficult to draw an accurate conclusion about the goodness of both models. Obsidian uses documents locally, so you don't have to sync notes. Roam Research is a very new and poorly optimized app. Standard Notes encrypts notes locally. In other words, it's not always apples to apples.

And even if tests could be done, we believe that the answer may even depend on how each user uses the application. Suppose user A usually organizes his notes in long documents using paragraph nesting (to collapse or expand them). On the other hand user B usually organizes his notes by creating new documents within documents. It is likely that a block model based manager would work better for user A while a document based one would work better for B.

So, we tried to push our doubt as far as we could, but we are still not sure of the answer Which of the two models do you think would offer better performance for our app and why?

4. Update

I just found some very interesting information. It seems that both TinyMCE and CKEditor (up to version 4), the view and the model converge with the HTML being based on content-editable. However, CKEditor 5 switched to MVC [source 1], [source 2].

I've done a short test pasting a large clipboard of a few MB in TinyMCE 5, CKEditor 4 and CKEditor 5, and the latter has been a bit slower. I hope soon to be able to do more tests with other things like dragging blocks or rendering large documents.

In a GitHub thread about CKEditor 5's performance when working with large documents, one of the contributors said "It works slower than the native content-editable element obviously, but the typing experience is pretty well".

答:
You seem to be making your choice based on what is easier to model or develop.

If you intend to compete in this increasingly crowded market, you need to consider what will give you an edge, and what will be sustainable in the long run.

Two of the main issues Evernote (longtime user and former employee) faced were:

a very badly designed back-end that was very expensive to scale and made sharing and collaboration a nightmare (engineering-wise)

a too loose document model that made it very hard to add new features to the editor (real time collaboration) and made collaboration very finicky even for simple features (checkboxes would often generate so many note conflicts as to be unusable)

On the other hand, block-based tools usually have really bad web clippers, because it's very hard to go from HTML to blocks.

Solve some of these hard problems!

Body:
1. The problem

Lately, it seems that many note managers with "infinite" tree structure are choosing a block model (where each paragraph is an entry in the DB), instead of a document or file model.

Blocks
Documents

Notion
 Workflowy
 Remnote
 Dynalist
 Roam Research
Evernote
 Obsidian
 Bear app

If you find any errors in the table, please let me know.

We have been developing an app very similar to Notion for 8 months now, also using the block model, but we are considering making a radical change and switching to the document model. The structure of our blocks in MongoDB currently looks like this:

_id: "61fd3ede7f6d2cc7a53ca669"
children: Array
    0: "61fd3ee87f6d2cc7a53ca66b"
    1: "61fd3ef37f6d2cc7a53ca671"
    2: "61fd3ef77f6d2cc7a53ca673"
backlinks: Array
type: "bullet"
parentPage: Array
    _id: "61fd3ede7f6e2ccra53ca664"
    userParent: "german-jablo"
    permisionParent: "edit, comment, read"
parentParagraph: "61fd3ede7f6d2cc7a53ca668"
content: "
This is a paragraph
"
isCollapsed: false
createdAt: 2022-02-04T14:57:34.280+00:00
updatedAt: 2022-02-04T14:57:59.585+00:00

Many pages talk about the differences of both approaches (example) although in a very vague way, so we decided to open this thread to find a more scientific answer to the question.

Features of our app

app
Blocks that can be opened as documents
Blocks that can collapse or expand their children

Notion
Page type blocks
Toggle type blocks

Workflowy
All
All

Evernote
Documents
None

Our app
Page type blocks
All others

Our app has two types of "blocks". The page type (which, like in Notion, can be inserted into any note and generate a document "inside" the current document), and the rest of the blocks, which are equivalent to the "toggle" block type in Notion (i.e. they can be collapsed or their nested children can be expanded).

2. What we have tried

In trying to answer our question (which DB model would work best for our application), we've realized that the answer is probably "it depends". Perhaps both models have strengths or weaknesses in different types of operations or situations. That is why we formulated this comparison table describing how we believe the performance of both models would be for each of these operations.

Operation
Blocks
Documents
Apparent Winner

Fetch the contents of a page
Find all paragraphs in the DB.
Search the document in the DB.
Document

Render the content of a page**
Build the tree from the paragraphs recursively. You can omit the children of paragraphs whose isCollapsed property is true
Render the document
Document

Update the content of a paragraph in the DB
Only the modified paragraph is rewritten
The whole document is rewritten
Block

Alternatives for rendering very large documents *
Blocks can be fetched or rendered as you scroll (as Workflowy does), or as you expand child paragraphs that were collapsed.
I thought that Grifds could achieve similar behavior, breaking the document into smaller chunks and bringing them in piecemeal, but it doesn't support updating an individual chunk, or even the entire document. It could also corrupt an HTML by splitting it into binary format.
Block

Import or paste content
In addition to converting the clipboard to HTML and/or sanitizing it, you must set up paragraphs with tree structure recursively. Note: Roam Research e.g. supports importing in JSON format, but generally users do not handle this format beforehand.
Only convert the clipboard to HTML and/or sanitize the clipboard
Document

Copy content**
Clipboard must be sanitized and/or transformed
Correct by default**
Document

Real-Time Collaboration
At the document level, could use some tree-based (Json) library like Automerge, or combine with some CRDT library for paragraph level.
Could use tinymce solution.
Tie? Both seem to have their advantages and disadvantages.

*Render very large documents: Most users probably do not use notes larger than 250 kb (considering that multimedia files are referenced in a separate collection). Still, in the document model, the question arises: how can we load, render or edit large documents in manageable chunks? One idea we came up with is to split HTML documents that reach large dimensions into portions of a certain size in kb, instead of splitting them into paragraphs. (It would be like a kind of Gridfs that allows you to modify the file in parts.) Could this be a good idea?

**Should the DOM be nested? In order to be able to collapse or expand nested child paragraphs, note managers with a block model structure the DOM in a nested way (paragraphs are in divs, inside their parent divs, etc.). However, an alternative in the document model could be that when the user presses tab, only that block (HTML tag such as
 or
) is assigned an attribute with a number less than or equal to 1, representing the nesting levels relative to the previous block. This way when you press tab to nest or shift-tab to un-nest, you only have to modify one attribute of an HTML element instead of many elements; and the DOM stays simple, without having nested blocks.

3. Our conclusions

We believe that for each of the rows in the comparison table, benchmarks could be done measuring the performance of both models.
Other people have done something similar here and here, comparing the performance of note managers using both models. The problem with those tests is that it is difficult to draw an accurate conclusion about the goodness of both models. Obsidian uses documents locally, so you don't have to sync notes. Roam Research is a very new and poorly optimized app. Standard Notes encrypts notes locally. In other words, it's not always apples to apples.

And even if tests could be done, we believe that the answer may even depend on how each user uses the application. Suppose user A usually organizes his notes in long documents using paragraph nesting (to collapse or expand them). On the other hand user B usually organizes his notes by creating new documents within documents. It is likely that a block model based manager would work better for user A while a document based one would work better for B.

So, we tried to push our doubt as far as we could, but we are still not sure of the answer Which of the two models do you think would offer better performance for our app and why?

4. Update

I just found some very interesting information. It seems that both TinyMCE and CKEditor (up to version 4), the view and the model converge with the HTML being based on content-editable. However, CKEditor 5 switched to MVC [source 1], [source 2].

I've done a short test pasting a large clipboard of a few MB in TinyMCE 5, CKEditor 4 and CKEditor 5, and the latter has been a bit slower. I hope soon to be able to do more tests with other things like dragging blocks or rendering large documents.

In a GitHub thread about CKEditor 5's performance when working with large documents, one of the contributors said "It works slower than the native content-editable element obviously, but the typing experience is pretty well".


问:
How can I test this function using Jest framework?
I have function below. I can't test this function using Jest framework.

The function:

```<code>const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

exports.xhrExample = function() {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'url' , true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            console.log('Some text');
            console.log('Some text');
        }
    };

    xhr.send(/*body*/);
}
</code>```

The test:

```<code>/**
 * @jest-environment jsdom
 */
const { xhrExample } = require('../function/exampleXHR');

const open = jest.fn();
const setRequestHeader = jest.fn();
const send = jest.fn();
const status = 200;
const readyState = 4;

const xhrMockClass = function () {
        return {
        open,
        setRequestHeader,
        send,
        status,
        readyState
    };
};

global.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);

test('Should make a request', () => {
    xhrExample();
})
</code>```

In particular I can't cover if branch. How can I write the right test? I've seen many solutions but they don't work. I also used the xhr-mock utility but it still not working. Thanks to all.

答:
I will create an HTTP server to test it instead of mocking. Your code doesn't make sense, I did some refactoring and added opts parameters for xhrExample function. It's more generic and easier to test.

E.g.

exampleXHR.js:

const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

exports.xhrExample = function (opts) {
  var xhr = new XMLHttpRequest();
  xhr.open(opts.method, opts.url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = JSON.parse(xhr.responseText);
      opts.onSuccess(response);
    }
  };
  xhr.send();
};
```
<p><code>exampleXHR.test.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>const http = require('http');
const { xhrExample } = require('./exampleXHR');

describe('71021143', () => {
  let server;
  beforeEach((done) => {
    server = http
      .createServer((req, res) => {
        const body = JSON.stringify({ name: 'amelia' });
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(body),
        });
        res.write(body);
        res.end();
      })
      .listen(8000, done);
  });
  afterEach((done) => {
    server.close(done);
  });
  test('should pass', (done) => {
    expect.assertions(1);
    xhrExample({
      method: 'POST',
      url: 'http://localhost:8000',
      onSuccess: (res) => {
        console.log(res);
        expect(res).toEqual({ name: 'amelia' });
        done();
      },
    });
  });
});
</code>```

Test result:

 PASS  stackoverflow/71021143/exampleXHR.test.js (7.859 s)
  71021143
    ✓ should pass (37 ms)

  console.log
    { name: 'amelia' }

      at Object.onSuccess (stackoverflow/71021143/exampleXHR.test.js:28:17)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |
 exampleXHR.js |     100 |      100 |     100 |     100 |
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.41 s
```

Body:
I have function below. I can't test this function using Jest framework.

The function:

const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

exports.xhrExample = function() {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'url' , true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            console.log('Some text');
            console.log('Some text');
        }
    };

    xhr.send(/*body*/);
}

The test:

/**
 * @jest-environment jsdom
 */
const { xhrExample } = require('../function/exampleXHR');

const open = jest.fn();
const setRequestHeader = jest.fn();
const send = jest.fn();
const status = 200;
const readyState = 4;

const xhrMockClass = function () {
        return {
        open,
        setRequestHeader,
        send,
        status,
        readyState
    };
};

global.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);

test('Should make a request', () => {
    xhrExample();
})

In particular I can't cover if branch. How can I write the right test? I've seen many solutions but they don't work. I also used the xhr-mock utility but it still not working. Thanks to all.

Body:
I will create an HTTP server to test it instead of mocking. Your code doesn't make sense, I did some refactoring and added opts parameters for xhrExample function. It's more generic and easier to test.

E.g.

exampleXHR.js:

const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

exports.xhrExample = function (opts) {
  var xhr = new XMLHttpRequest();
  xhr.open(opts.method, opts.url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = JSON.parse(xhr.responseText);
      opts.onSuccess(response);
    }
  };
  xhr.send();
};

exampleXHR.test.js:

const http = require('http');
const { xhrExample } = require('./exampleXHR');

describe('71021143', () => {
  let server;
  beforeEach((done) => {
    server = http
      .createServer((req, res) => {
        const body = JSON.stringify({ name: 'amelia' });
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(body),
        });
        res.write(body);
        res.end();
      })
      .listen(8000, done);
  });
  afterEach((done) => {
    server.close(done);
  });
  test('should pass', (done) => {
    expect.assertions(1);
    xhrExample({
      method: 'POST',
      url: 'http://localhost:8000',
      onSuccess: (res) => {
        console.log(res);
        expect(res).toEqual({ name: 'amelia' });
        done();
      },
    });
  });
});

Test result:

 PASS  stackoverflow/71021143/exampleXHR.test.js (7.859 s)
  71021143
    ✓ should pass (37 ms)

  console.log
    { name: 'amelia' }

      at Object.onSuccess (stackoverflow/71021143/exampleXHR.test.js:28:17)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |
 exampleXHR.js |     100 |      100 |     100 |     100 |
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.41 s


问:
Using sh -c if comparisons inside an SSH command
I'm having some trouble with the != section of the if statement. Essentially this statement is valid as far as I'm aware, however executing this gives [: 1: !=: unexpected operator. I've tried executing using -n but for whatever reason, even if the output is blank, using -n still runs the echo command.

Any help on this is appreciated. I've attached the code snippet below.

```<code>#!/bin/sh

HOST=$1
USER="/scripts/whoowns $HOST | tr -d '\r'"

ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != "\`$USER\`" ]; then echo "Username for $HOST: \`$USER\`"; fi' ; bash -login"
</code>```

答:
In regards to your "however executing this gives [: 1: !=: unexpected operator" problem, here is a solution:

Use bash -c instead of sh -c. The bash program seems to be better than sh at handling square brackets. For example:

```<code>ubuntu@ubuntu:/$ echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
match
ubuntu@ubuntu:/$ echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
no
ubuntu@ubuntu:/$ sh -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$ bash -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
match
ubuntu@ubuntu:/$ bash -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
no
ubuntu@ubuntu:/$ sh -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$
</code>```

So ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != ... would become ssh -t $HOST -p 22 -l deehem "bash -c 'if [ "" != ....

Thanks to pLumo at https://askubuntu.com/questions/1310106/sh-c-sh-not-working-when-using-if-statement-and-having-in-the-filena ("command line - sh -c '...' sh {} not working when using if statement and having ' in the filename - Ask Ubuntu").

Body:
I'm having some trouble with the != section of the if statement. Essentially this statement is valid as far as I'm aware, however executing this gives [: 1: !=: unexpected operator. I've tried executing using -n but for whatever reason, even if the output is blank, using -n still runs the echo command.

Any help on this is appreciated. I've attached the code snippet below.

#!/bin/sh

HOST=$1
USER="/scripts/whoowns $HOST | tr -d '\r'"

ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != "\`$USER\`" ]; then echo "Username for $HOST: \`$USER\`"; fi' ; bash -login"

Body:
In regards to your "however executing this gives [: 1: !=: unexpected operator" problem, here is a solution:

Use bash -c instead of sh -c. The bash program seems to be better than sh at handling square brackets. For example:

ubuntu@ubuntu:/$ echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
match
ubuntu@ubuntu:/$ echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
no
ubuntu@ubuntu:/$ sh -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$ bash -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
match
ubuntu@ubuntu:/$ bash -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
no
ubuntu@ubuntu:/$ sh -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$

So ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != ... would become ssh -t $HOST -p 22 -l deehem "bash -c 'if [ "" != ....

Thanks to pLumo at https://askubuntu.com/questions/1310106/sh-c-sh-not-working-when-using-if-statement-and-having-in-the-filena ("command line - sh -c '...' sh {} not working when using if statement and having ' in the filename - Ask Ubuntu").