Is there a way to find the pitch for noisy electronic output?

Question: Is there a method available to help differentiate notes on a wide variety of electronic noise sounds (not-quite white/pink noise, heavy buzzing, fuzz, etc.)?
I've taken on an odd project where I am trying to get the pitch of sounds that are not generally particularly musical to try and make something out of it. They are electronically generated from very old computer hardware (old Atari POKEY, if anybody cares). However, the software/devices I have been trying to use fails to pick up notes on so much of the sounds produced, even though I can clearly hear a "note" in the sound. I can hum along and tune that, but I want to chart them to +/- 2 cent accuracy if at all possible, and I am not pitch perfect myself.
Using tuners have not been very successful. I have tried:
FMIT (Free Music Instrument Tuner) for Windows -- has a few options to control the pick up, but many sounds get nothing or jump all over the place
ReaTune for Reaper DAW -- I cannot get this to pick up anything meaningful
Various Snark instrument tuners that I have -- Holding these up to the speakers does nothing, regardless of the volume of the output
Are there methods to help figure out the pitch/frequency that noise is making?
Here are some samples (in WAV, so they are ~1-3MB) that I sustain for a moment, then start changing the pitch to make it obvious:
"White Noise" - I'd be surprised if much can be found here, but I'm asking anyways:
http://junk.zolaerla.com/Media/Stack/Distort0.wav
http://junk.zolaerla.com/Media/Stack/Distort0-Poly9.wav
Buzzy, almost engine-like sounds:
http://junk.zolaerla.com/Media/Stack/Distort4-64.wav
http://junk.zolaerla.com/Media/Stack/Distort4-15-ch0.wav
http://junk.zolaerla.com/Media/Stack/Distort4-15-ch2.wav
Comment: The issue is that questions of the form "please recommend an app for ___" or "what's the best ___" are not covered. If you search in the Meta section you can find some of the arguments that led to that decision; it includes reasons like recommendations becoming outdated quickly, a lack of a "correct answer," etc. Nothing stopping us from giving our opinions in the comments, though; mine is "using a tool to identify pitches is always going to be difficult." Especially if the sound source is not just one discrete pitch, or has a complicated waveform. Much easier just to do it "by ear"
Comment: Compulsory floppotron link - https://www.youtube.com/watch?v=Oym7B7YidKs  ;))
Comment: Samples of the actual sounds would be really helpful
Comment: Welcome! I'm afraid requests for recommendations are not one of the [topics covered here](https://music.stackexchange.com/help/on-topic). But I suggest you experiment with the idea of filters, especially "band pass" filters. It's the idea that you're letting certain frequencies through and suppressing others. Make that range narrow enough and you'll emphasize a particular "note." You can experiment with this idea in lots of DAWs, from Audacity to non-free software, or with old-school hardware.
Comment: (Meanwhile, if the task giving you difficulty is simply identifying a pitch, don't overthink it: if you can perceive an overall pitch, just compare it to another source like a piano until you figure out what pitch it is.)
Comment: I do not understand how "usage of specific music software or hardware" and "music ... composition" do not apply to this, which are listed as topics of this SE. I am trying to compose music with these unique sounds. I'm trying to find software to help with that.
The issue with trying to compare to a source like a piano is that these are not "in tune" with anything in particular. I am trying to track what is in tune and what is not and how far off they are.
Comment: Even if the notes being produced aren't "in tune"—i.e., are "between" piano keyboard notes, you can first figure out what they fall between (e.g. is it "a little higher than A but lower than A#). Then you could use a simple oscillator to try to produce a pitch that matches, and then you'd have the number of Hz.
Comment: I'm not sure you'll ever get good results using a "tuner"—but you could try a number of phone apps that seem pretty good; I like Cleartune; or get a really good physical tuner, one with a needle, and with a pickup and clip that to the speaker.
Comment: So if I restructure the question to instead ask "How do you get the pitch of noise?" and the like without specifically asking for software/hardware recommendations, does this suddenly fit the site properly?
Comment: Sure; that's often a good edit, turning "what tool should I use for X" into "how do I go about X." But note, what you have here isn't just white (/pink) noise, or else you wouldn't be perceiving it as pitched; it's just a messy signal.
Comment: If you know Python, here are some actually working methods for finding the pitch in PCM audio i.e. wav data https://gist.github.com/endolith/255291
Comment: Would an exponential smoothing filter help
Comment: The answer is always  "FFT"
Comment: I added some samples. And yes, Floppotron is certainly part of why I'm interested in making some unique-sounding music!
Answer: Some sounds do have pitch, some don't. In general, pitched sounds will have strong discrete sine components, following harmonic series, while unpitched ones will have continuous spectrum and nonharmonic relations between frequencies, but there is no clear boundary. Pitch belongs to psychoacoustics, not math or physics.
You can try to look at the frequency spectrum of a sound (e.g., using free audacity), and see if there is any dominant frequency in the sound. However, in the end, it's only your ear which can tell you if a sound does have a pitch and what is it.
Here are some examples of synthesizing sounds with a perceivable pitch by applying frequency filters.

Note how the sound gradually changes from unpitched to pitched when the filter strength is increased (3:28–3:59):

Note how the tone changes between two series of examples with broader and narrower filter frequency range. If you tried to increase the filter width more, the pitch would become gradually less apparent (0:11–0:31):

Note how the sound containing multiple frequencies might be perceived as a single sound, or a chord (2:54–3:26):

You can perform similar experiments with audacity or other free software.
Answer: Note: The original question asked for detecting a pitch in a pure noise signal. This is what this answer refers to.
Noise is actually a random waveform. In order to  perceive a signal as a specific note (pitch) the waveform has to be periodic, which is not random. Therefore noise cannot have a defined pitch by definition. If a sound has a pitch it is not noise.
You can also go the opposite way and use a synthesizer software like amsyth to produce a noise at a specific pitch. You will hear no differences in sound regardless of note you use to produce the sound. An A will sound the same as a C or a Bb or anything else.
Comment: This isn't purely white noise. It's generated by hardware and allows changing a divisor value that very clearly modifies the sound. What I was calling white noise SOUNDS like TV static, but you can make it sound higher or lower pitch by changing the divisor value.


I can't get hook_form_alter or hook_form_FORM_ID_alter to add placeholder text to the search input

Question: I know this has been asked but so far none of the accepted answers for this issue are working for me. I am attempting to add placeholder text to the default search form block. I am using a theme we'll call MyTheme, which is a copy of Bartik and is otherwise working exactly as expected.
I have tried adding the following functions to MyTheme.theme:
function MyTheme_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['edit-keys']['#attributes']['placeholder'][] = t('Search');
}

And
function MyTheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        // Add placeholder text
        $form['keys']['#attributes']['placeholder'] = t('Search');
    }
}

And many, many variations on those. I have tried both functions with and without "\Drupal\Core|form..." included. I have tried both with 'keys' and 'edit-keys'. I have tried both with and without the empty '[]' after placeholder. Nothing has worked.
In every case, using hook_form_FORM_ID_alter simply fails to do anything at all, while using hook_form_alter causes a 'white screen of death'.
I don't understand what I'm doing wrong.
UPDATE: Now out of the blue Drupal has decided to change the id for the form input to 'edit-keys--2' for some reason. I've tried using that in the functions as well.
Comment: I assume your theme name is actually "MyTheme" as that part needs to match exactly as your theme's machine name
Comment: I used "MyTheme" as an example here but yes I do understand that those need to match and they do.
Comment: Hey did you find out? I am interested because I have the same issue. I temporarily use some css (.form-search::placeholder {opacity:0}) and Jquery (new placeholder then opacity 1) to change it on the fly but this is not a solution.
Comment: @Tritof Yes, I did get it working. I added my solution and accepted it below. I hope it helps you.
Answer: This is what eventually worked for me. Posting because other people seem to be having the same issue.
I placed this at the very end of the MyTheme.theme file.
/**
 * Add placeholder text to the search forms.
 */
function MyTheme_form_search_block_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Search this site...');
}

Hopefully this will be helpful for some.
Answer: So, I've tried this on my local install and had the exact same issue.
Please try changing $form['keys']['#attributes']['placeholder'] to $form['keys']['#title']
Your function would be -
function MyTheme_form_search_block_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['keys']['#title'] = t("Search");
}

Comment: Welcome to Drupal Answers! This answer doesn't help much the OP, since it isn't telling him with what he should replace `'search_block_form'` in `$form['search_block_form']['#attributes']`.
Comment: See what the OP said in the question. He tried `$form['keys']['#attributes']['placeholder']` and `$form['edit-keys']['#attributes']['placeholder']`. Without telling him what exactly to use instead of *edit-keys* or *keys*, this answer is telling him something he already know.


Is there a way to deactivate the us of created_at and updated_at?

Question: I just want to deactivate the fields created_at and updated_at of my gorm model, haven't been able to find it in the docs.
Getting this errors when trying to create rows in the db:
Error 1054: Unknown column 'created_at' in 'field list'

Answer: The created_at, id, updated_at, deleted_at fields are embedded into your model by embedding the gorm.Model into your struct.
So, to disable them instead of doing
type Product struct {
  gorm.Model
  Code  string
  Price uint
}

do
type Product struct {
  ID    uint `gorm:"primarykey"`
  Code  string
  Price uint
}


$\frac{x^{n+1}}{n+1}$ uniformly converge to $0$ or not

Question: I am learning uniformly convergence of function, I found that $x^{n+1}/n+1$  uniformly converge to $0$ in my note and it did not specify the domain. And I am thinking,
For $ x>1$,
$\frac{x^{n+1}}{n+1} \gt \frac{x}{n+1} $,
then for any $\epsilon$,
$\frac{x}{n+1}\lt \epsilon$  iff $n\gt \frac{x}{\epsilon} -1$
Then when x goes to infinity then n goes to infinity too.
It seems that $$\frac{x^{n+1}}{n+1}$$ does not uniformly converge to zero on any domains contain numbers bigger than or equal to 1.
And it converges to 0 uniformly on $[0,1)$
Comment: If $x>1$, $\dfrac{x^{n+1}}{n+1}$ does not tend to $0$.
Answer: $\sup_{x\in [-1,1]}|\frac{x^{n+1}}{n+1}|=\frac{1}{n+1}\to 0$ as $n\to\infty$. So we indeed have uniform convergence in $[-1,1]$. And as you noted there is no convergence (even point wise) to $0$ if $|x|> 1$.


finding a 'standard pattern' from time series data of daily temperature values

Question: Data : I have a time series of temperature values every 5 minutes for 20 days.
There is a common pattern across each day.
Question : What kind of pattern extraction or machine learning algorithm should be used to obtain a 'standard pattern / profile' of each day from this data ?
The idea is to compare deviations on future days from this 'standard pattern'.
I am unsure what should be the approach to solve this problem.
Sample daily temperatures are as follows:
Comment: Maybe search this site for clustering of time series? And tell us a little more about your data
Comment: Is there a long term trend in your data? Does the average daily temperature increase or decrease or is it stable?
Comment: You don't need machine learning here. A simple correlogram will work
Answer: Assuming you don't have any long term trend in your data, then you extract the daily pattern you are looking for by calculating the average over 20 days for each 5 minute interval. This would smooth out any day-to-day variances and show daily a pattern in your data (if there is one).
Consider a simple example with 3 days of data, measured at 4 hours intervals:
D1-4:00  D1-8:00    D1-12:00    D1-16:00    D1-20:00    D1-24:00
  4        11        15.5         17           8           6
D2-4:00  D2-8:00    D2-12:00    D2-16:00    D2-20:00    D2-24:00
  6        9          16          14          8.5          7
D3-4:00  D3-8:00    D3-12:00    D3-16:00    D3-20:00    D3-24:00.
  5.5     9.5         14          14          14           2

Although some daily pattern is visible in this data, it is not very clear and there is a lot of daily variance. But if you calculate the average over 3 days for each two hour period:
4:00    8:00.   12:00  16:00   20:00   24:00
5.16    9.83    15.16    15    10.16     5

The pattern becomes much clearer.
You can do the same thing with your data, by averaging the value for every 5 minutes across 20 days.
If your data has a trend in it, then you need to detrend it first.


How should I implement point and vector in C?

Question: I am trying to implement mathematical concepts point and vector in C, using struct.
I've seen someone else's C++ implementation of it.
Tuple Point(float x, float y, float z)
{
    return {x, y, z, 1.0f};
}

Tuple Vector(float x, float y, float z)
{
    return { x, y, z, 0.0f };
}

Tuple::Tuple()
    : m_x(0.f)
    , m_y(0.f)
    , m_z(0.f)
    , m_w(0.f)
{
}

Tuple::Tuple(float x, float y, float z, float w)
    : m_x(x)
    , m_y(y)
    , m_z(z)
    , m_w(w)
{
}

I'm not sure how should I be implementing it in C.
Here's what I've done.
typedef struct s_tuple
{
    double x;
    double y;
    double z;
    double w;
}              t_tuple;

typedef struct s_point
{
    double x;
    double y;
    double z;
    double w = 1.0;
}              t_point

typedef struct s_vector
{
    double x;
    double y;
    double z;
    double w = 0.0;
}              t_vector

I'm not sure if I'm doing it right. I'm not even sure if t_tuple exists for a reason in this implementation. How should I fix it?
Comment: Initializers aren't allowed in structure definitions. After removing the initializers, `t_point` and `t_vector` are exactly the same. I think that's why the C++ defines Tuple. Point and Vector are just instances of Tuple with different values for `w`.
Answer: One possible way is to have factory functions that create the tuple structure with the correct values for each "type" of tuple:
typedef struct s_tuple
{
    double x;
    double y;
    double z;
    double w;
}              t_tuple;

t_tuple create_tuple(double x, double y, double z, double w)
{
    t_tuple tuple = {
        x, y, z, w
    };
    return tuple;
}

t_tuple create_point(double x, double y, double z)
{
    return create_tuple(x, y, z, 1.0);
}

t_tuple create_vector(double x, double y, double z)
{
    return create_tuple(x, y, z, 0.0);
}


Completeness for product topolgy

Question: Let $(X_n, d_n)$ be a countable family of metric spaces. Show that
the distance function on the product topology defined by
$$d\big( (x),(y) \big) = \sum_{n\geqslant 1} 2^{-n} \frac{d_n(x_n,y_n)}
{1+d_n(x_n,y_n)}$$ is complete, if all spaces $(X_n, d_n)$ are complete.
Comment: That's pretty straightforward; what have you tried?
Comment: I first looked at every "coordinate" to get a coordinate-wise cauchy sequences. From this I defined $$x^*$$. Then I split the sum to get a finite one and an arbitrary small one. But how do I now that $$x^*$$ converge to something in the product?
Answer: Here's a guide; all you have to do is fill in the details.
Start with a Cauchy sequence in $X=\prod_nX_n$, say $\sigma=\langle x^n:n\in\Bbb N\rangle$, where $x^n=\langle x_k^n:k\in\Bbb N\rangle\in X$. Use the fact that $\sigma$ is $d$-Cauchy to show that $\langle x_k^n:n\in\Bbb N\rangle$ is $d_k$-Cauchy in $X_k$ for each $k\in\Bbb N$. Each $X_k$ is complete, so $\langle x_k^n:n\in\Bbb N\rangle\to y_k$ for some $y_k\in X_k$. Let $y=\langle y_k:k\in\Bbb N\rangle\in X$, and show that the sequence $\sigma$ converges to $y$ in $X$.

Completeness for product topolgy


How to select sub-terms in taxonomy when creating content?

Question: In creating a document management system I've created a taxonomy vocabulary with this structure:
<code>Accounting
  Client 1
  Client 2
Client 1
  Contacts
Client 2
  Contacts
  Correspondance
Leasing
  Client 1
  Client 2
</code>
Then, in my Document content type I've created a term reference field called Tags which uses autocomplete. The autocomplete part works great, but I don't know how to differentiate Accounting:Client 1 from Leasing:Client 1 from Client 1 (parent level). When loading a new document, is there a way to reference these terms properly?
Answer: Simple Hierarchical Select is the module for the job.

Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Just change the widget-type of field Tags to "Simple hierarchical select" after you install the module. This guide might come handy if you're running 7.
Comment: That did it - exactly what I needed.
Answer: You can try using multilevel autocomplete module. If that help you.


Append data to html table using JQuery

Question: How to append json data in table. Json data format :
i want to loop throw this array and append the result to this html table

HTML table :

                        Id

                        Name

                        Description

                        Price

                        Quantity

                        Amount

Comment: What did you try so far?
Comment: i didn't get a  solution so far
Comment: FYI Stakoverflow is to find the code errors not to write code for each other. Please read the help center and find how to ask a well formed question https://stackoverflow.com/help/how-to-ask
Answer: You can use .each to iterate over the array, and .append to add rows:

const data = [
  { ItemId:1, Name:'Item 1', Description:'A', Price:1, Quantity:1, Amount:1},
  { ItemId:2, Name:'Item 2', Description:'B', Price:2, Quantity:2, Amount:2}
];

$.each(data, (index, row) => {
  const rowContent
  = `

       ${row.ItemId}
       ${row.Name}
       ${row.Description}
       ${row.Price}
       ${row.Quantity}
       ${row.Amount}

`;
  $('#tbdata').append(rowContent);
});

    Id
    Name
    Description
    Price
    Quantity
    Amount

Append data to html table using JQuery


How to set proxy_pass on nginx

Question: Bit of an nginx noob here. I'm trying to setup nginx to reverse proxy all web traffic to a locally running web server. Right now it works but it says the IP address of every logged in user is 127.0.0.1. I read some other posts that I need to set the proxy_set_header Host $host; correctly. I set this this, but users IPs are still 127.0.0.1. Can anyone tell by looking at my nginx.conf if I'm setting proxy_set_header Host $host; incorrectly? I think I need to set it in both server blocks, but I don't have a location block in the server that accepts traffic on port 80. Which is where I think it might be getting lost.
    server {
       listen 80;
       server_name www.myapp.com myapp.com;
       return 301 https://myapp.com$request_uri;
    }

    server {
       listen 443;
       server_name _;
       ssl on;
       ssl_certificate /web/ssl/cert.pem;
       ssl_certificate_key /web/ssl/key.pem;

      location / {
         proxy_set_header Host $host;
         proxy_set_header  X-Real-IP  $remote_addr;
         proxy_pass http://localhost:8000;
       }

       location /robots.txt {
         alias /web/static/robots.txt;
      }

      }

Comment: Is your application actually looking for the IP address in the `X-Real-IP` header?
Answer: Use;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
This will add a new header to the backend server which your application will be able to see the original IP addresses.
You're along the right lines with X-Real-IP, in that this will do the same thing (providing that $remote_addr is actually the client's IP address). X-Forwarded-For is more universal though, and if your backend is running a standard off-the-shelf package, it may already know about it. Likewise, if your application isn't looking at X-Real-IP header, then it won't reflect.
Putting it bluntly, there's no way to override the Remote-Addr header at the backend, as this is set internally by most all web servers. You need to get your application to look in other headers if Remote-Addr is a local, private, or otherwise unrouteable IP address (127.0.0.1, 10.x.x.x, etc).
Comment: `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;` causes nginx to fail on restart for me
Comment: Oh, I forgot the semicolon. Still no dice though :(
Comment: More context on your backend setup is required at this point tbh. The configuration works and will pass the relevant information to the backend server. It's now up to how your application is perceiving the user, and whether it's even able to look at the correct headers (or if you're able to change the application's code to get the IP address from an alternate header variable.
Answer: You could check if the backend server software has any tools to take the IP address from X-Forwarded-For or X-Real-IP headers and set it as the remote address. It all depends on your backend server software or application.

How to set proxy_pass on nginx


Pandas DataFrame Scalar Values Index Pass

Question: I have a linear regression test where I am trying to compare the test results in a table. With my current setup I am receiving an error ValueError: If using all scalar values, you must pass an index, which I feel is related to the varying data formats of the values being stored in the DataFrame. What is the proper format I should be using to achieve this comparison table?
Here is my code:
print(type(y_test))
print(type(y_pred))

print(y_test)
print(y_pred)

# compare predictions to actuals
df_full_results = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})

# display results as table
display(HTML(df_full_results.to_html()))

Here is the code triggering the error:
df_full_results = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})

Here is the output:
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>

 b_leads
214      11
148       7
227       9
131      14
....

[63 rows x 1 columns]
[[14.03709801]
 [ 6.58161653]
 [13.02991554]
....

Comment: which line triggers the error message?
Comment: You are trying to set one of the column of your `DataFrames` to be another `DataFrame`. I don't think this is possible, or should ever be done... Likely you want `'Actual': y_test.values.tolist()`
Comment: @Yuca `df_full_results = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})`
Comment: @ALollz good call. I tried your solution, but receive an error `Exception: Data must be 1-dimensional`.
Answer: You could try storing what you're putting into the DataFrame into a variable instead, and then put it into the df_full_results.  In example;
data_stuff = {'Actual': y_test,
              'Predicted': y_pred
             }
df_full_results = pd.DataFrame(data_stuff, columns=['Actual', 'Predicted'])


Cannot read property 'text' of undefined at NodeObject.getText at getRequiredModulePath

Question: Error occurs while generating browser application bundles (phase: setup).
What can cause this error?
Info from console:

Generating browser application bundles (phase: setup)...
TypeError: Cannot read property 'text' of undefined
at NodeObject.getText (/opt/app-root/src/node_modules/typescript/lib/typescript.js:152697:31)
at getRequiredModulePath (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/host/umd_host.js:519:99)
at Object.getImportsOfUmdModule (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/host/umd_host.js:510:23)
at UmdDependencyHost.extractImports (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/dependencies/umd_dependency_host.js:43:54)
at UmdDependencyHost.DependencyHostBase.recursivelyCollectDependencies (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/dependencies/dependency_host.js:85:32)
at UmdDependencyHost.DependencyHostBase.collectDependencies (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/dependencies/dependency_host.js:38:22)
at DependencyResolver.getEntryPointWithDependencies (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/dependencies/dependency_resolver.js:75:22)
at EntryPointCollector.walkDirectoryForPackages (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/entry_point_finder/entry_point_collector.js:47:52)
at EntryPointCollector.walkDirectoryForPackages (/opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/entry_point_finder/entry_point_collector.js:75:103)
at /opt/app-root/src/node_modules/@angular/compiler-cli/ngcc/src/entry_point_finder/program_based_entry_point_finder.js:124:100

Info from angular-errors.log

An error occurred during the build:
Error: NGCC failed.
at NgccProcessor.process (/opt/app-root/src/node_modules/@ngtools/webpack/src/ngcc_processor.js:139:19)
at /opt/app-root/src/node_modules/@ngtools/webpack/src/ivy/plugin.js:129:27
at Hook.eval [as call] (eval at create (/opt/app-root/src/node_modules/tapable/lib/HookCodeFactory.js:19:10), :28:1)
at Hook.CALL_DELEGATE [as _call] (/opt/app-root/src/node_modules/tapable/lib/Hook.js:14:14)
at Compiler.newCompilation (/opt/app-root/src/node_modules/webpack/lib/Compiler.js:1043:30)
at /opt/app-root/src/node_modules/webpack/lib/Compiler.js:1088:29
at Hook.eval [as callAsync] (eval at create (/opt/app-root/src/node_modules/tapable/lib/HookCodeFactory.js:33:10), :22:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/opt/app-root/src/node_modules/tapable/lib/Hook.js:18:14)
at Compiler.compile (/opt/app-root/src/node_modules/webpack/lib/Compiler.js:1083:28)
at /opt/app-root/src/node_modules/webpack/lib/Compiler.js:508:12
at Compiler.readRecords (/opt/app-root/src/node_modules/webpack/lib/Compiler.js:920:11)
at /opt/app-root/src/node_modules/webpack/lib/Compiler.js:505:11
at Hook.eval [as callAsync] (eval at create (/opt/app-root/src/node_modules/tapable/lib/HookCodeFactory.js:33:10), :10:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/opt/app-root/src/node_modules/tapable/lib/Hook.js:18:14)
at /opt/app-root/src/node_modules/webpack/lib/Compiler.js:502:20
at Hook.eval [as callAsync] (eval at create (/opt/app-root/src/node_modules/tapable/lib/HookCodeFactory.js:33:10), :22:1)
An unhandled exception occurred: NGCC failed.
See "/tmp/ng-IZbyMh/angular-errors.log" for further details.
Comment: What is the content of `/tmp/ng-IZbyMh/angular-errors.log`?
Comment: @MaartenDev I edited post to be more clear
Comment: did you try removing the `node_modules` folder and running `npm i` again?
Comment: @MaartenDev yes, i tried
Comment: Are there any typescript issues reported when you run the following command: `./node_modules/typescript/bin/tsc --noEmit -p .`?
Comment: @MaartenDev, no output during executing command (I guess no)
Answer: There is a error in angular version 12.2.12 and 12.2.11 use 12.2.10 it will fix it or you might have to wait for them to release a new version or fix 12.2.12
Note : if you are using ^12.0.1 in your package.json file, replace it with 12.2.10
Comment: It seems to be not fixed in 12.2.13.
Answer:
First move to a latest stable release
remove package-lock.json
npm install
Answer: This seems to be caused by the improved UMD module detection added in 12.2.11, pinning the version to 12.2.10 avoids the issue but doesn't address the root cause which is that a dependency probably needs updating.
For us, the package was @auth0/angular-jwt, but it might be different for you. To find it we had to use Linux tool strace to find out which file was opened just before the build failed:
strace -f npm run build 2>&1 | egrep 'open|Error'

(eventually) produced the output
[pid 29550] open(".../node_modules/@auth0/angular-jwt/package.json", O_RDONLY|O_CLOEXEC) = 19
[pid 29550] open(".../node_modules/@auth0/angular-jwt/bundles/core.umd.js", O_RDONLY|O_CLOEXEC) = 19
[pid 29550] open(".../node_modules/@auth0/angular-jwt/bundles/core.umd.js", O_RDONLY|O_CLOEXEC) = 19
[pid 29550] open(".../node_modules/@angular/compiler-cli/bundles/ngcc/__ngcc_lock_file__", O_RDONLY|O_CLOEXEC) = 19
[pid 29550] write(2, "TypeError: Cannot read property "..., 1535TypeError: Cannot read property 'text' of undefined
[pid 29582] open(".../node_modules/@angular/compiler-cli/bundles/ngcc/__ngcc_lock_file__", O_RDONLY|O_CLOEXEC <unfinished ...>
[pid 29582] <... open resumed> )        = -1 ENOENT (No such file or directory)
[pid 29393] write(2, "(node:29393) UnhandledPromiseRej"..., 914(node:29393) UnhandledPromiseRejectionWarning: Error: NGCC failed.

the offending module is opened in the run up to the error, and updating it resolved the problem. There's probably a more succinct shell command to get the error, but this was enough for us.


Solution for running a 32 bit DLL in a 64 bit process or vise versa

Question: I am running windows vista business 64 bit. I have a web service that was written in .NET using C#. I also have a client-side script on a web page that communicates with the web service. This is a aspx page titled "Default.aspx". I setup IIS and moved my web service folder containing the web service and all of the files that are needed to run it including the default.aspx page into C:\inetpub\wwwroot. I opened IIS manager and configured everything properly. I now get an error message:
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
I was told that this could be a problem with my license key, the app was configured for a different format, or there is a corrupt file somewhere. My license key is fine and I don't believe there is a corrupt file. I think the issue is I'm trying to load a 32 bit DLL into a 64 bit proces or vise versa. The detailed error message is below. If someone could please give me a detailed solution as I have given a detailed description, I'd very much so appreciate it. I have been wrestling with this all day and I'm frustrated. please help me.
Exception Details: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)] Luxand.FSDK.ActivateLibrary(String LicenseKey) +0 FaceRecognition._Default.Page_Load(Object sender, EventArgs e) in D:\Project Details\Layne Projects\DotNet Project\FaceRecognition\FaceRecognition\Default.aspx.cs:60 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42 System.Web.UI.Control.OnLoad(EventArgs e) +132 System.Web.UI.Control.LoadRecursive() +66 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428
Answer: In IIS 7, you can configure application pools to run in 32-bit mode; this is quite useful when you have to access DLLs which are only available for 32-bit systems.
You can modify the default application pool's properties to make your whole web server run in x86 mode, or you can create a new application pool, configure it to be 32-bit and assign specific web sites and/or virtual directories to it.


Como Listar produtos de um só Distribuidora MVC

Question: Tenho uma aplicação que gerencia a Distribuidora e seu Produtos.
Quero listar apenas os produtos da Distribuidora que selecionei, mas no caso esta aparecendo tudo.
Tentei fazer assim:
public ActionResult ListarProdutosDistribuidoras(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Produto produto = db.Produtos.Find(id);
    if (produto == null)
    {
        return HttpNotFound();
    }

    var produtos = db.Produtos.Include(p => p.Pessoa.PessoaID);
    return View(produtos.ToList());
}

Comment: a distribuidora é chave primária?
Comment: Opa, sim a distribuidora é chave primária.
Comment: o código tá nebuloso, o que seria este id que ele recebe como parametro e qual campo é a distribuidora ai? Pessoa seria a distribuidora?
Comment: O produto tem o código da distribuidora em que o mesmo pertence? Poste os Models Produto e Distribuidora, para vermos como está o relacionamento.
Answer: Suponho que seu Model Produto seja algo assim:
public class Produto
{
    [Key]
    public int ProdutoId { get; set; }
    public int DistribuidoraId { get; set; }

    ...

    public virtual Distribuidora Distribuidora { get; set; }
}

Suponho também que sua Action receba um DistribuidoraId como parâmetro:
public ActionResult ListarProdutosDistribuidoras(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var idNaoNulo = (int)id; // Você já conferiu se é nulo, então posso fazer isso.
    var distribuidora = db.Distribuidoras.FirstOrDefault(d => d.DistribuidoraId == idNaoNulo);
    // Produto produto = db.Produtos.Find(id);

    if (distruibuidora == null)
    {
        return HttpNotFound();
    }

    // Não entendi isso aqui. Acho que falta entendimento sobre o Include.
    // var produtos = db.Produtos.Include(p => p.Pessoa.PessoaID);
    var produtos = db.Produtos.Where(p => p.DistribuidoraId == idNaoNulo);
    return View(produtos.ToList());
}


PCA: Out of Sample Variance Explained

Question: The eigenvalues of a PCA model can be used to calculate the variance explained of each principal component.
I'm curious how one might train a PCA model on a subset of data, and then use the eigenvectors of that model to calculate the variance explained on unseen (out-of-sample/ test) data.
Any suggestions for python or R implementations would be highly appreciated.
Comment: Asking for Python or R implementations make this possibly off-topic  (voting to leave open since the actual question seems to be statistical, but you may want to remove the last sentence)
Answer: Unless your train and test data follow the exact same distribution, the eigenvectors of your train data are different from test.
Let's assume that train and test distributions are very similar and we can use the same principle components. If X_train and X_test are two pxn and pxm. (n and m are number of samples).
import numpy as np
X_train = X_train - np.mean(X_train,axis=1)[:,np.newaxis]
X_test  = X_test  - np.mean(X_test, axis=1)[:,np.newaxis]
Sigma_train = np.dot(X_train,X_train.T)/n
V,U = np.linalg.eigh(Sigma_train)

Using the assumption mentioned above, you can calculate the projections of your data:
Y_test = np.dot(U.T,X_test)

The variance of each row is the test variance along the principle components.
Y_var = np.sum(Y_test**2,axis=1)/m

However, PCA is unsupervised, so in practice we don't have to use train eigenvectors for test data.
Note: There's a concept called robust PCA for when test and/or train contain gross outliers. But I don't think you'd be interested in that, especially since those methods don't find the maximum variance.
Comment: Thank you very much for the excellent explanation! Just to clarify, beyond maintaining similar distributions, are we also making any implicit assumptions about the covariance structure? Furthermore, in order to test the stability of two eigenvectors across samples, would it be appropriate to take the dot product of them? Thanks again.
Comment: Re your first question: Yes, by distribution I meant the covariance matrix that specifies the Gaussian distribution. Because, in standard PCA the distribution is always Gaussian.
Re your second question: As long as the order of the eigenvalues (in terms of size) is the same between train and test, the eigenvectors should ideally be parallel. However, if the maximum variance directions are different, there's no way to tell which eigenvectors to compare against each other.
Comment: This is not correct. You're subtracting the mean of the out-of-sample data. But, the mapping PCA defines from the high dimensional to the low dimensional space requires subtracting the mean of the training data. This also implies that you can't just add up the variance of the projections of the out-of-sample data.

PCA: Out of Sample Variance Explained


Starting Jazz Improvisation on Saxophone

Question: I've always wanted to be able to do jazz improvisations and I think I am almost at a point where I should start, though I know little about improvisation.  I would like some pointers on technique and putting together melodies.
How can I put melodies together in a way that sounds good?
What are some common scales that are used?
What are some exercises that would help?
Are there any good licks that I should know before I start?
Are there any techniques specific to jazz I should know?
Answer: This is a very broad question, and each individual subquestion is very broad by itself, but I'll try to point you in the right direction.
You should grab a copy of either Mark Levine's "The Jazz Theory Book" or  Robert Rawlins' "Jazzology". In my experience, those are the most recommended general jazz theory books. Check reviews in Amazon and similar sites to see which one suits you best.

How can I put melodies together in a way that sounds good?

That's a very subjective question, and only experience will tell you what works best for your taste. Jazz theory can give you general recommendations on when, how, and why use specific scales, but in the end it is up to you to grab all that information and use what you want and like.
The specifics would require a question on its own, and even there it might be still a very broad question. It is a very large subject.

What are some common scales that are used?

Depends on the style and context. The major scale and the 6 modes derived from it, pentatonic (minor and major), blues (minor and major), diminished (whole-half and half-whole), augmented, the melodic minor scale and some modes derived from it (including altered and lydian b7), and bebop (dominant, minor, and major) are all very common.

What are some exercises that would help?

There are many, and depends on what exactly you want to practice. For scales you should be doing normal runs for speed, but also stuff like "four directions" and "going up one mode, down the next, etc" as in C D E F G A B C, D C B A G F E D, E F G A B C D E, etc (the details of this can be found in Mark Levine's book, in the "how to practice scales" section.
There are countless more. Ear training is important too.

Are there any good licks that I should know before I start?

Transcribing is a good way to expand your jazz vocabulary. Again, good is subjective. Search for licks that you like and transcribe them. Play them in different keys, expand on them.
If you are into bebop and hardbop, John Coltrane's album Giant Steps has countless exceptional licks. The track "Mr PC" is a good starting point, since the harmony is a simple minor blues. If you are more into cool and modal jazz, Miles Davis' Kind of Blue is also filled with out-of-this-world licks. Those two are probably the most well known jazz albums and both have John Coltrane in the sax, so you will most likely find something that interests you.

Are there any techniques specific to jazz I should know?

That's way too broad a question, and jazz is already too board of a concept. You'll find them as you progress.

You need to start a program. Grab one of the recommended books above, and/or get a teacher. You can find quality teachers online if you can't find one in your area, Berklee has good online improvisation programs. That way you'll answer those questions in detail as they arrive in your program.
There is no shortcut.
A good place to start
Regardless of what path you take, a good starting place is improvising over a common 12 bar blues.
Learn one minor blues scale, whichever you want, and play it over a blues in that key. If you learned C minor blues, you can play it over a common 12 bar blues in C or a common 12 bar minor blues in C minor, through all the song.
When you feel like you can handle that, learn the other minor blues scales that correspond to the chord changes of the blues that you are learning. For example, using the last example of a blues in C, the other chords are F7 and G7, so learn F minor blues and G minor blues scales, and play them with the chord changes.
That's something you can do right now. As you progress you will learn more scales and more stuff you can do over a blues and other harmonies.
Comment: Om just at the beginning and know very little about music theory.   Would the books you suggested help me even at my very basic level?
Comment: @JacobSwanson When you said "I'm at the point where I should start" I assumed that you already knew the basics! Jazz books in general assume that you already have the basics down: you can read music notation, basic functional analysis, how chords and scales are constructed, etc. If you are not familiar with those, you'll have to grab a book (and/or teacher) for the basics first, and once you know the basics move to jazz theory and practice.
Comment: @JacobSwanson **BUT** you can start right now if you want to. You don't need to go full-on jazz theory to improvise. Check the "a good place to start" section in my answer for an example. For going beyond that just google around, there are countless resources regarding basic improvisation and blues out there. All that knowledge will be very useful and will transfer to later, when you learn the basics and go deep into jazz.
Comment: Ok.   Are there any online sources you know of that teach music theory?
Comment: @JacobSwanson One of the most popular (I always see it recommended) is http://www.musictheory.net/lessons. I have never used it, but looking through the material it seems that by going through all of it -as in learning and understanding all of it- (you can skip the last section "neapolitan chords") you should be more than ready to start one of the recommended books. Just make sure you practice reading music and you can read music before you go into the jazz books (you don't have to be super fluent, but you will need the skill to go through the recommended jazz books).
Comment: I'll take a look at that.  I've been playing sax for around 2 years, so I can read music well enough.  It's just the chords and harmony stuff I have no knowledge of.
Comment: @JacobSwanson I think you already have the most difficult part down then. The rest will be very easy to digest.
Comment: And that's discussed on the website you provided?
Comment: @JacobSwanson What are you talking about? l don't know what you are referring to specifically, we have discussed a lot of things here!
Comment: You said the website (musictheory.net) teaches about music theory.   I'm asking if they talk about harmony and chords.
Comment: @JacobSwanson Just click the link
Answer: Improvisations is at its core completion of a melody. That questions you do in your theory exams is there for a reason. If you can get some training in the writing of melodies and take that training into your playing then you will have the basics down to such an extent where you can improvise to any given music.


update string from a dictionary with the values from matching keys

Question: def endcode(msg,secret_d):
    for ch in msg:
        for key,value in secret_d:
             if ch == key:
                 msg[ch] = value
    return msg
encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})

This is my code. What I am trying to do here is for every characters in a string msg, the function should search in the dictionary and replace it with the mapping string if the character ch is a key in the dictionary secret_d.
If ch is not a key in secret_d than keep it unchanged.
For the example, the final result is should be 'C4N YOU R34D 7H15'
Comment: Hey OP, have you come any further with the help of the answers you got?
Answer: Your function name is endcode but you are calling encode.
But more important, I'll give you a hint to what's going on. This isn't going to totally work, but it's going to get you back on track.
def endcode(msg,secret_d):
    newstr=""
    for ch in msg:
        for key,value in secret_d.iteritems():
            if ch == key:
                newstr=newstr+value
    print(msg)
endcode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})

But if you want a complete answer, here is mine.
Answer: A few issues:

As rb612 pointed out, there's a typo in your function definition ("endcode")
you are doing nothing with the return value of your function after calling it
msg[ch] is trying to assign items in a string, but that's not possible, strings are immutable. You'll have to build a new string. You cannot "update" it.
in order to iterate over (key, value) pairs of a dictionary d, you must iterate over d.items(). Iterating over d will iterate over the keys only.

That being said, here's my suggestion how to write this:
>>> def encode(msg, replacers):
...     return ''.join([replacers.get(c, c) for c in msg])
...
>>> result = encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})
>>> result
'C4N YOU R34D 7H15'

Things to note:

dict.get can be called with a fallback value as the second argument. I'm telling it to just return the current character if it cannot be found within the dictionary.
I'm using a list comprehension as the argument for str.join instead of a generator expression for performance reasons, here's an excellent explanation.
Comment: This is definitely a good answer. Mine (now edited) will do the same but overall not nearly as clean and compact.


Laravel 5 Method not found exception

Question: I use Laravel 5 and try to update a form:
 {!! Form::model($user, ['route' => ['edit', $user->id], 'method' => 'PUT']) !!}

 {!! Form::label('titel', 'First Name:'!!}
 {!! Form::text('titel', null,) !!}

<button type="submit">Update</button>
{!! Form::close() !!}

My route:
Route::post('edit/{id}', ['as' => 'edit', 'uses' => 'UserController@editUser']);

My controller:
public function editUser($id){};

When click on the update Button I get MethodNotAllowedHttpException in RouteCollection.php
I checked in the browser source code and saw that Form::model(..) which I use generate the following output:
<form method="POST" action="http://localhost/myProject/public/edit/1" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT"><input name="_token" type="hidden" value="4nZlyfzzAZmTcZfThQ8gcR6cgEgYgR0ip0JZTKck">

Within the form there is the attribute method="POST" and the hidden input has the attribute value="PUT". This seems not correct for me. Any ideas? Thank you
Answer: Your route is not the same as your form.
Laravel uses the hidden inputs to specify the different http methods, as put.
So in your routes you should use a put method not a post.
Route::put();

Answer: You should use 'update' route to actually save the data (validate and persist it to the database). 'edit' route is what you used to generate edit form.
You should use PUT method to run method which saves data.
Also, here is small tip for you. Learn about how RESTful controllers work. They are really easy way to do what you're doing here (defenetly worth to learn them):
https://laravel.com/docs/5.1/controllers
Comment: I'm glad I could help. )

Laravel 5 Method not found exception


Anything else I need to know about the Tarantella before I compose one?

Question: So, the thought just crossed my mind of composing a Tarantella. But the thing is, I have only listened to and played a few of them in my 10 years of piano playing, so I don't know much about what is typical. However I do know this. It is a dance from southern Italy that is typically in 6/8 but sometimes in 12/8 or 4/4. And it has a typical rhythm, namely this rhythm:

Tarantella rhythm
And the tempo is typically very fast, easily Presto. And the pieces themselves are typically short, not much longer than 5 minutes on the outside. And from what I know of the tarantella pieces I have listened to in the past and the ones I am listening to now, the bass is usually constant eighth notes or changes between eighths and dotted quarters whereas the melody has the typical 1 - a 2 - a, 1 & a 2 & a, rhythm(hyphens I'm using to represent that the note takes up 2 eighth notes) and the overall piece has a constant eighth note momentum until the final cadence.
Do I need to know anything besides the typical rhythms of the dance and the tempo and time signature it is in before I compose a Tarantella myself? Just asking because I have never written an Italian dance before. I've written French dances(the Minuet originated from France), I've written Austrian dances(the waltz has Austrian origins), I've even written Polish dances, but never an Italian one.
Comment: I don't understand the original downvote? This looks like a well-asked question, and some work has gone into it.
Comment: The music has to be suitable for reviving the victims of Tarantula bites https://en.wikipedia.org/wiki/Tarantella#Tarantism
Answer: There is quite a tantalizing (brief!) essay, "A Question about the Tarantella", which at minimum may inspire some further research.

Almost all students ... have confused the Tarantella ... with a dance ... by those who have been bitten by the tarantula. It is therefore necessary to point out some differences. The Tarantella is a courtship dance ... and is graceful and elegant ... of fairly brief duration and has its own music. ... The confusion ... comes from the fact that both the courtship Tarantella and [the] "tarantolati" derive their name from the city of Taranto.

The 2004 dissertation "Spider dreams: Ritual and performance in apulian tarantismo and tarantella" appears to have a great deal of information about the history of the spider-inspired version of the dance, including the music and both historical and modern performance practice.

ABSTRACT: The objective of this dissertation is to look at
the relationship between ritual, performance, and
social change in Southern Italy since the end of World
War II. The focus is on Apulian tarantismo, a ritual of
healing involving music and dance. Pivotal, in the
system of tarantismo, is the figure of the taranta, a
local spider, whose bite "possesses" the bitten with
acoustic qualities that match its anthropomorphic
characteristics. The healing for this bite happens
during the pizzica tarantata ritual, in which
professional musicians diagnose the vibration of the
spider venom by performing a repertory of tarantella
tunes. When the right tune is found, the person bitten
begins to dance a cathartic tarantella dance.
Since the 1950s the ritual has slowly changed,
leading some scholars to say that it has disappeared. I
look at the ritual changes and at the ritual revival
that, since the 1990s, have enthralled musicians,
dancers, poets, directors, and filmmakers in Italy and
in the United States. I situate the revival of
tarantella and tarantismo at the tail end of the larger
Italian folk revival of the 1950s, 1960s, and 1970s.
Key concepts such as "originality," "tradition," and
"identity" as they relate to "local" music in a
"global" market are discussed in the context of
Salentine folklore.
The dissertation research includes interviews and
notes gathered during my fieldwork in Salento in the
summer of 2002, analysis of staged performances of
tarantella music and dance, and analysis of the
tarantata ritual through the study of descriptions on
books and articles, as well as the study of historical
video and sound recordings. (emphases mine)
Answer: I've played a bunch of tarantellas - they make pretty cool guitar pieces.  Here's what I've noticed distinguishes them from other styles:

They're always in duple compound meter
They are always in minor keys
They're always lively, vivace or faster
The rhythm you showed does sort of define a tarantella, but in the same way that beats define rhythm: it's the thing that underlies the actual performance.  I haven't seen many tarantellas that use that exact rhythm, but I can "feel" that rhythm in practically any tarantella.
The spider legend referenced in Aaron's response can be extremely important.  Some tarantellas have a molto retardando at the end of the B section followed by an a tempo return to the A - I always picture the victim of the spider bite exhausted from the dancing, and being prodded to keep it up in order to recover.
Comment: You mean almost always in a minor key, this Beethoven tarantella is in major: https://www.youtube.com/watch?v=j42HjfCUClU
Comment: @Caters - Beethoven titled that piece "Presto con fuoco". Several editions make that presto con molto fuoco, but I can't find any that give it the name tarantella, and that seems to be the ONLY video of it on YouTube so titled.  It sounds to me like a similar 6/8 Italian dance, the saltarello https://en.wikipedia.org/wiki/Saltarello.  That would also make sense in context, since it's from his "hunt" sonata, and saltarello (jumping) has more to do with something like a fox hunt than spiders would.
Answer: I think you're being too prescriptive regarding the rhythm.   A Google search for Tarantellas found plenty of examples, but not one followed that exact pattern.   And I'm not hearing many 8ths in the bass lines, just plodding dotted quarters.  So, apart from getting those two points wrong...  :-)  Yes, fast 6/8.   As if trying to sweat the poison of a tarantula spider out of your system!
Comment: Well what about this tarantella by Beethoven: https://www.youtube.com/watch?v=j42HjfCUClU Or this one by Chopin: https://www.youtube.com/watch?v=6q8Ku0vItm0 Lots of eighth notes in the bass in both of them, especially the Chopin one.
Answer: I agree with Laurence as far that there is huge list to find in the wiki article to find and on youtube. So you don't need to have played many tarantellas.
So listen to them, find common features and differences of local styles - there are more than the rhythm.
Or just close your eyes, see the pictures of joyfully dancing people, colorful clothes, the moves and sounds and write just your own style.


Pass parameter to a constructor in the ViewModel

Question: I am building a WPF browser application with MVVM pattern.
I have a first page (ConsultInvoice) with a dataGrid. When I double click on one of the row I want to navigate to another page (EditInvoice) passing the selected row in argument to my constructor.
I know if I want do things properly I should use a dependency injection, but I don't really see how to use it here.
How can I simply pass this constructor?
ConsultInvoiceViewModel
private Invoice _selected;
public Invoice Selected
{
    get
    {
        return _selected;
    }
    set
    {
        _selected = value;
        OnPropertyChanged("Selected");
    }
}

private void Edit()
{
    EditInvoiceViewModel editInvoice = new EditInvoiceViewModel(Selected);
   /* doing something here*/
}

public ICommand EditCommand
{
    get
    {
        return editCommand ?? (editCommand = new RelayCommand(p => this.Edit(), p => this.CanEdit()));
    }
}

EditInvoiceViewModel
public class EditInvoiceViewModel : ViewModelBase
{
    public Context ctx = new Context();
    Invoice invoice;
    PreInvoice preInvoice;
    #region properties
    private ObservableCollection<PreInvoice> collection;
    public ObservableCollection<PreInvoice> Collection
    {
        get
        {
            return collection;
        }
        set
        {
            collection = value;
            OnPropertyChanged("Collection");
        }
    }
    #endregion
    public EditInvoiceViewModel(Invoice inv)
    {
        /* do stuff*/
    }
}

Comment: Maybe it's just me, but I'm slightly confused. Aren't you already passing a parameter (Selected) to a constructor (EditInvoiceViewModel(Invoice inv)) in the ViewModel (ConsultInvoiceViewModel)? What exactly are you asking?
Comment: @Rowbear yeah, but the goal it's to open a new EditInvoiceView.xaml and it does accept only a default constructor. So what I am trying to do doesn't work.
Comment: ah! I see. Are you planning to have EditInvoiceView show as a popup, or a new window? How do you plan to control showing EditInvoiceView? With just .Show()/.ShowDialog()? Would it make sense for all the possible invoices from  ConsultInvoiceViewModel to share one view? Or will you be able to edit multiple invoices at once?
Comment: @Rowbear, I'm planning to show it as a new window, but a popup is fine as well. And after I don't know really how to navigate. This is the point. Between my others pages I use Hyperlink. But now I need to pass 'Invoice' in argument to my constructor so I cannot use Hyperlink anymore. I just want to edit invoices one by one.
Comment: @Cantinou. Is it alright to keep a default constructor in EditInvoiceView and adding a public property of type EditInvoiceViewModel in EditInvoice. So you build withh a default constructor, and assign the property on the following line.
Comment: Using parameterless ViewModel constructor inside Views is pretty bad imho, as you can't easily inject services into it. Consider using Microsoft's Prism approach and resolving the ViewModel via ViewModel locator. Gives way more flexibility and is navigation aware (see answer below, based on Prism but you can reimplement it)
Answer: Basically you should avoid passing such parameters into the ViewModels constructor, as wiring it with Inversion of Control/Dependency Injection becomes a pain. While you can use Abstract Factory pattern to resolve objects with runtime parameters, it's imho not suitable for ViewModels.
Instead I always suggest using a form of navigation pattern, similar to how Microsoft's Patterns & Practices team has done with Prism. There you have an INavigationAware interface which your ViewModels can implement. It has 2 methods, NavigateTo and NavigateFrom.
And there is a navigation service. The navigation service will switch the views and before switching calling NavigateFrom in the current ViewModel (if it implements it. One can use it to check if data is saved and if necessary cancel the navigation. After the new View has been loaded and the ViewModel assigned to it, call NavigateTo in the newly navigated ViewModel.
Here you'd pass the parameters required for the ViewModel, in your case invoiceId. Try avoid passing whole models or complex objects. Use the invoiceid to fetch the invoice data and to populate your editing ViewModel.
A basinc implementation from my former answer (can be found here):
public interface INavigationService
{
    // T is whatever your base ViewModel class is called
    void NavigateTo<T>() where T ViewModel;
    void NavigateToNewWindow<T>();
    void NavigateToNewWindow<T>(object parameter);
    void NavigateTo<T>(object parameter);
}

public class NavigationService : INavigationService
{
    private IUnityContainer container;
    public NavigationService(IUnityContainer container)
    {
        this.container = container;
    }
    public void NavigateToWindow<T>(object parameter) where T : IView
    {
        // configure your IoC container to resolve a View for a given ViewModel
        // i.e. container.Register<IPlotView, PlotWindow>(); in your
        // composition root
        IView view = container.Resolve<T>();

        Window window = view as Window;
        if(window!=null)
            window.Show();

        INavigationAware nav = view as INavigationAware;
        if(nav!= null)
            nav.NavigatedTo(parameter);
    }
}

// IPlotView is an empty interface, only used to be able to resolve
// the PlotWindow w/o needing to reference to it's concrete implementation as
// calling navigationService.NavigateToWindow<PlotWindow>(userId); would violate
// MVVM pattern, where navigationService.NavigateToWindow<IPlotWindow>(userId); doesn't. There are also other ways involving strings or naming
// convention, but this is out of scope for this answer. IView would
// just implement "object DataContext { get; set; }" property, which is already
// implemented Control objects
public class PlotWindow : Window, IView, IPlotView
{
}

public class PlotViewModel : ViewModel, INotifyPropertyChanged, INavigationAware
{
    private int plotId;
    public void NavigatedTo(object parameter) where T : IView
    {
        if(!parameter is int)
            return; // Wrong parameter type passed

        this.plotId = (int)parameter;
        Task.Start( () => {
            // load the data
            PlotData = LoadPlot(plotId);
        });
    }

    private Plot plotData;
    public Plot PlotData {
        get { return plotData; }
        set
        {
            if(plotData != value)
            {
                plotData = value;
                OnPropertyChanged("PlotData");
            }
        }
    }
}

An example of the INavigationAware interface used in Prism can be found on the projects github repository.
This makes it easy to pass parameter and async load your data (where there isn't any clean way to do this via constructor, as you can't await an async operation inside the constructor without locking, and doing this kind of things in the constructor is very discouraged).


Ideas on getting a cell's center and set it as a value of the center of a UIView

Question: I'm currently working on a drag and drop functionality and luckily I found a good tutorial. The goal of this project is to drag and drop "items" from one table view to another with the help of the UILongPressGestureRecognizer. As I have learned from this, you have to get a "snapshot" of a cell you chose in able to get the feel of dragging something out of a table. And I think, below is the method that does this.
- (void)dragAndDropTableViewController:(DragAndDropTableVC *)ddtvc draggingGestureWillBegin:(UIGestureRecognizer *)gesture forCell:(UITableViewCell *)cell
{
    // create a snapshot of the cell
    NSLog(@"draggable delegate method is called");
    UIGraphicsBeginImageContext(cell.contentView.bounds.size);
    [cell.contentView.layer renderInContext: UIGraphicsGetCurrentContext()];
    UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageView *cellImageView = [[UIImageView alloc] initWithImage:cellImage];
    self.dragAndDropView = [[UIView alloc] initWithFrame:cellImageView.frame];
    [self.dragAndDropView addSubview:cellImageView];
    [self.dragAndDropView setBackgroundColor:[UIColor blueColor]];
    [self.dragAndDropView setCenter:[gesture locationInView:self.view.superview]];

    [self.view.superview addSubview:self.dragAndDropView];
}

Basically, upon getting the cell's "snapshot", you have to add it as a subview of a UIView. The thing that bugs me out is this part.
[self.dragAndDropView setCenter:[gesture locationInView:self.view.superview]];
This may sound easy but what I would want to do is when the long press is done, the draggable cell should appear a bit higher than the original location of the selected cell.
Enlighten me please :) Thanks!
Answer: Actually you have to convert center point with respect to your superview then you should use one of these methods convertPoint: fromView: and convertPoint: toView: and for more information see this link.
I think it will be helpful to you.


Stop fragment refresh in bottom nav using navhost

Question: This problem has been asked a few times now, but we are in 2020 now, did anyone find a good usable solution to this yet?
I want to be able to navigate using the bottom navigation control without refreshing the fragment each time they are selected. Here is what I have currently:
navigation/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    app:startDestination="@id/home">

    <fragment
        android:id="@+id/home"
        android:name="com.org.ftech.fragment.HomeFragment"
        android:label="@string/app_name"
        tools:layout="@layout/fragment_home" />
    <fragment
        android:id="@+id/news"
        android:name="com.org.ftech.fragment.NewsFragment"
        android:label="News"
        tools:layout="@layout/fragment_news"/>
    <fragment
        android:id="@+id/markets"
        android:name="com.org.ftech.fragment.MarketsFragment"
        android:label="Markets"
        tools:layout="@layout/fragment_markets"/>
    <fragment
        android:id="@+id/explore"
        android:name="com.org.ftech.ExploreFragment"
        android:label="Explore"
        tools:layout="@layout/fragment_explore"/>
</navigation>

activity_mail.xml:
<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/main" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottomNavigationView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:itemIconTint="@color/nav"
            app:itemTextColor="@color/nav"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/main">

        </com.google.android.material.bottomnavigation.BottomNavigationView>

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        app:menu="@menu/main"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/navigationView"
        android:layout_gravity="start">
    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

MainActivity.kt:
class MainActivity : AppCompatActivity() {

    private var drawerLayout: DrawerLayout? = null
    private var navigationView: NavigationView? = null
    private var bottomNavigationView: BottomNavigationView? = null
    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        drawerLayout = findViewById(R.id.drawer_layout)
        navigationView = findViewById(R.id.navigationView)
        bottomNavigationView = findViewById(R.id.bottomNavigationView)

        val navController = findNavController(R.id.nav_host_fragment)
        appBarConfiguration = AppBarConfiguration(setOf(R.id.markets, R.id.explore, R.id.news, R.id.home), drawerLayout)

        setupActionBarWithNavController(navController, appBarConfiguration)

        findViewById<NavigationView>(R.id.navigationView)
            .setupWithNavController(navController)

        findViewById<BottomNavigationView>(R.id.bottomNavigationView)
            .setupWithNavController(navController)

    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.search) {
            startActivity(Intent(applicationContext, SearchableActivity::class.java))
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.options_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }
}

In the fragment I am making a few calls to my services to fetch the data in onCreateView, when resuming the fragment I am assuming those calls will not longer be executed and the state of the fragment should be preserved.
Comment: what about using nav host for each item in bottom navigation and on clicking of the icon you change their visibility. I have done that and working perfectly.
Comment: @Abdul can you provide a sample on changing the visibility for those of us who use a nav host?
Comment: check this answer, https://stackoverflow.com/a/69325054/4797289 is an accepted answer.
Answer: Try this:
public class MainActivity extends AppCompatActivity {

    final Fragment fragment1 = new HomeFragment();
    final Fragment fragment2 = new DashboardFragment();
    final Fragment fragment3 = new NotificationsFragment();
    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = fragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        fm.beginTransaction().add(R.id.main_container, fragment3, "3").hide(fragment3).commit();
        fm.beginTransaction().add(R.id.main_container, fragment2, "2").hide(fragment2).commit();
        fm.beginTransaction().add(R.id.main_container,fragment1, "1").commit();

    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fm.beginTransaction().hide(active).show(fragment1).commit();
                    active = fragment1;
                    return true;

                case R.id.navigation_dashboard:
                    fm.beginTransaction().hide(active).show(fragment2).commit();
                    active = fragment2;
                    return true;

                case R.id.navigation_notifications:
                    fm.beginTransaction().hide(active).show(fragment3).commit();
                    active = fragment3;
                    return true;
            }
            return false;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

Or You can follow Google's recommended solution: Google Link
Comment: Many of us are using the nav Host xml where our fragments get defined. Any suggestions on applying this solution to that newer version since we wouldn't explicitly create fragments in the activity in code directly
Comment: I have a navigation xml which lists all of my fragments (following latest android pattern for navigation). My activity main xml uses a androidx.navigation.fragment.NavHostFragment element with the key value (app:navGraph="@navigation/my_nav"). The main activity does not create any fragments, only minor setup.
findViewById(R.id.bottomNavigationView).setupWithNavController(findNavController(R.id.fragment)). The R.id.fragment is the NavHostFragment I mentioned earlier. This latest android pattern is different from your provided solution where fragments are manually created
Comment: Created a solution using google's recommended answer: https://stackoverflow.com/a/64142496/3316842
Comment: @baskInEminence what is you requirements? Please explain me.
Comment: @baskInEminence he wants manual process. Btw if you want to more simplify please follow this link: https://www.simplifiedcoding.net/android-navigation-tutorial/
Comment: Yeah thats just a generic tutorial on how to set it up. It doesn't dive into how to ensure the fragment doesn't refresh
Comment: Please any idea on how to upgrade to multiple backstacks?  https://stackoverflow.com/questions/68042591/problem-upgrading-my-fragments-navigation-versionfrom-2-3-5-to-2-4-0-alpha03
Answer: Kotlin 2020 Google's Recommended Solution
Many of these solutions call the Fragment constructor in the Main Activity. However, following Google's recommended pattern, this is not needed.
Setup Navigation Graph Tabs
Firstly create a navigation graph xml for each of your tabs under the res/navigation directory.
Filename: tab0.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/tab0"
    app:startDestination="@id/fragmentA"
    tools:ignore="UnusedNavigation">

    <fragment
        android:id="@+id/fragmentA"
        android:label="@string/fragment_A_title"
        android:name="com.app.subdomain.fragA"
    >
    </fragment>
</navigation>

Repeat the above template for your other tabs. Important all fragments and the navigation graph has an id (e.g. @+id/tab0, @+id/fragmentA).
Setup Bottom Navigation View
Ensure the navigation ids are the same as the ones specified on the bottom menu xml.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:title="@string/fragment_A_title"
        android:id="@+id/tab0"
        android:icon="@drawable/ic_baseline_book_24"/>

    <item android:title="@string/fragment_B_title"
        android:id="@+id/tab1"
        android:icon="@drawable/ic_baseline_add_alert_24"/>

    <item android:title="@string/fragment_C_title"
        android:id="@+id/tab2"
        android:icon="@drawable/ic_baseline_book_24"/>

    <item android:title="@string/fragment_D_title"
        android:id="@+id/tab3"
        android:icon="@drawable/ic_baseline_more_horiz_24"/>

</menu>

Setup Activity Main XML
Ensure FragmentContainerView is being used and not <fragment and do not set the app:navGraph attribute. This will set later in code

<androidx.fragment.app.FragmentContainerView
      android:id="@+id/fragmentContainerView"
      android:name="androidx.navigation.fragment.NavHostFragment"
      android:layout_width="0dp"
      android:layout_height="0dp"
      app:defaultNavHost="true"
      app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@id/main_toolbar"
/>

Main Activity XML
Copy over the following Code into your main activity Kotlin file and call setupBottomNavigationBar within OnCreateView. Ensure you navGraphIds use R.navigation.whatever and not R.id.whatever
private lateinit var currentNavController: LiveData<NavController>

private fun setupBottomNavigationBar() {
  val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
  val navGraphIds = listOf(R.navigation.tab0, R.navigation.tab1, R.navigation.tab2, R.navigation.tab3)
  val controller = bottomNavigationView.setupWithNavController(
      navGraphIds = navGraphIds,
      fragmentManager = supportFragmentManager,
      containerId = R.id.fragmentContainerView,
      intent = intent
  )
  controller.observe(this, { navController ->
      val toolbar = findViewById<Toolbar>(R.id.main_toolbar)
      val appBarConfiguration = AppBarConfiguration(navGraphIds.toSet())
      NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration)
      setSupportActionBar(toolbar)
  })
  currentNavController = controller
}

override fun onSupportNavigateUp(): Boolean {
  return currentNavController?.value?.navigateUp() ?: false
}

Copy NavigationExtensions.kt File
Copy the following file to your codebase
[EDIT] The above link is broken. Found it in a forked repo
Source

Google's Solution
Comment: I have followed your guide, very helpful. Unfortunately navigation works exactly the same as before, all fragments are being recreated. Any suggestions or did I misunderstood what  the google solution was supposed to do.
Comment: @RasoulMiri Although the new alpha version may fix it, it's still an alpha release. They keep publishing a new alpha for this version every 2 weeks. Just keep that in mind when deploying alpha changes with your production code. I am happy to see Google has addressed at least looked into this matter
Comment: This is the right way to go in 2020, I am using this `navigation` component in my application now.
Comment: Can you provide this NavigationExtensions.kt File, given link is broken
Comment: @AnzyShQ Thank you for the comment. Found it in a forked repo. Updated Answer
Comment: don't use this way, you need the update libs. see this answer https://stackoverflow.com/a/69325054/4797289
Answer: The simple solution to stop refreshing on multiple clicks on the same navigation item could be
 binding.navView.setOnNavigationItemSelectedListener { item ->
        if(item.itemId != binding.navView.selectedItemId)
            NavigationUI.onNavDestinationSelected(item, navController)
        true
    }

where binding.navView is the reference for BottomNavigationView using Android Data Binding.
Comment: In this case you can do simply `binding.navView.setOnNavigationItemReselectedListener {  }`
Comment: You can use `navView.setOnItemReselectedListener {  }` instead of deprecated `navView.setOnNavigationItemReselectedListener {  }`
Answer: If you are using Jetpack, the easiest way to solve this is using ViewModel
You have to save all valuable data and not make unnecessary database loads or network calls everytime you go to a fragment from another.
UI controllers such as activities and fragments are primarily intended to display UI data, react to user actions, or handle operating system communication, such as permission requests.
Here is when we use ViewModels
ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance.
So if the fragment is recreated, all your data will be there instantly instead of make another call to database or network. Its important to know that if the activity or fragment that holds the ViewModel is reacreated, you will receive the same ViewModel instance created before.
But in this case you have to specify the ViewModel to have activity scope instead of fragment scope, independently if you are using a shared ViewModel for all the fragments, or a different ViewModel for every fragment.
Here is a little example using LiveData too:
//Using KTX
val model by activityViewModels<MyViewModel>()
model.getData().observe(viewLifecycleOwner, Observer<DataModel>{ data ->
        // update UI
    })

//Not using KTX
val model by lazy {ViewModelProvider(activity as ViewModelStoreOwner)[MyViewModel::class.java]}
model.getData().observe(viewLifecycleOwner, Observer<DataModel>{ data ->
        // update UI
    })

And that's it! Google is actively working on multiple back stack support for bottom tab Navigation and claim that it'll arrive on Navigation 2.4.0 as said here and on this issue tracker if you want and/or your problem is more related to multiple back stack, you can check out those links
Remember fragments still be recreated, usually you don't change component behavior, instead, you adapt your data to them!
I leave you some useful links:
ViewModel Overview Android Developers
How to communicate between fragments and activities with ViewModels - on Medium
Restoring UI State using ViewModels - on Medium
Comment: What if our bottom navigation View fragment keeps showing full screen fragments? Lets say 3 levels deep for that single tab. Then wouldn't you need a viewModel essentially recording which fragment the user is on? And then quickly recreate these fragments on the fly when it gets created again? Seems like a lot of work and needing to mess around with navigation stacks which is less than ideal
Comment: the docs say this is the way to go. though im not really sure if it is. i tried a simple int tracking, it always resets back to its initial value instead of the incremented one. the docs itself is fairly limited it does not even provide a simple working example.
Answer: Quick tip, if you just want to prevent loading the already selected fragment just override setOnNavigationItemReselectedListener and do nothing, but this won't save the fragment states
binding.navBar.setOnNavigationItemReselectedListener {  }

Answer: You use the old version, you just use version 2.4.0-alpha05 or above.
This answer is updated in 2021.
androidx.navigation:navigation-runtime-ktx:2.4.0-alpha05
androidx.navigation:navigation-fragment-ktx:2.4.0-alpha05
androidx.navigation:navigation-ui-ktx:2.4.0-alpha05

Comment: Does this implementations only stops the fragment refresh ? Seems not working. Can you provide any snippet or something working ?
Comment: this works, thanks
Answer: If you use NavigationUI.setupWithNavController(), the NavOptions are defined for you with NavigationUI.onNavDestinationSelected(). These options include launchSingleTop and, if the menu item is not secondary, a popUpTo the root of the graph.
The problem is, that launchSingleTop still replaces the top fragment with a new one. To resolve this issue, you'd have to create your own setupWithNavController() and onNavDestinationSelected() functions. In onNavDestinationSelected() you'd just adapt the NavOptions to your needs.
Comment: Do you have some working sample that demonstrates this approach? I was looking at [here](https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample) and [here](https://github.com/STAR-ZERO/navigation-keep-fragment-sample), would these solve this problem?
Comment: I actually replaced the fragment navigator to only show and hide the fragments. Before I tried to do what I suggested here and it worked as well. But it was a different use-case. You could also use actions to define the behavior then.
Answer: If you are using navigation component,In addition to this answer From version:'2.4.0-alpha01' it has inbuilt support for multiple back stacks.So no navigation extension is needed
refer to this link for more details.  https://medium.com/androiddevelopers/navigation-multiple-back-stacks-6c67ba41952f
Answer: Try something like this
navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)

And
private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.home -> {
            fragmentManager.beginTransaction().hide(active).show(homeFragment).commit()
            active = homeFragment
            return@OnNavigationItemSelectedListener true
        }
        R.id.news -> {
            fragmentManager.beginTransaction().hide(active).show(newsFragment).commit()
            active = newsFragment
            return@OnNavigationItemSelectedListener true
        }
        R.id.markets -> {
            fragmentManager.beginTransaction().hide(active).show(marketsFragment).commit()
            active = marketsFragment
            return@OnNavigationItemSelectedListener true
        }
        R.id.explore -> {
            fragmentManager.beginTransaction().hide(active).show(exploreFragment).commit()
            active = exploreFragment
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

Comment: Do I need to set the `fragments` in `supportFragmentManager` before I try to navigate between them in a listener?
Comment: Yeah. Set all of them in OnCreate(...) of your Activity. Make sure default is Active & rest others are Hidden
Comment: OnViewCreated will be executed either way. It will always be called distegarding how you are using fragmentManager - classic way or via jetpack navigation.
Comment: Make sure you get the references to your fragments by first checking for their existence via `FindFragmentByTag`, and that you track the active fragment tag using onSaveInstanceState / onCreate(Bundle)
Answer: create a class:
@Navigator.Name("keep_state_fragment") // `keep_state_fragment` is used in navigation xml
class KeepStateNavigator(
private val context: Context,
private val manager: FragmentManager, // Should pass childFragmentManager.
private val containerId: Int
) : FragmentNavigator(context, manager, containerId) {

override fun navigate(
    destination: Destination,
    args: Bundle?,
    navOptions: NavOptions?,
    navigatorExtras: Navigator.Extras?
): NavDestination? {
    val tag = destination.id.toString()
    val transaction = manager.beginTransaction()

    var initialNavigate = false
    val currentFragment = manager.primaryNavigationFragment
    if (currentFragment != null) {
        transaction.detach(currentFragment)
    } else {
        initialNavigate = true
    }

    var fragment = manager.findFragmentByTag(tag)
    if (fragment == null) {
        val className = destination.className
        fragment = manager.fragmentFactory.instantiate(context.classLoader, className)
        transaction.add(containerId, fragment, tag)
    } else {
        transaction.attach(fragment)
    }

    transaction.setPrimaryNavigationFragment(fragment)
    transaction.setReorderingAllowed(true)
    transaction.commitNow()

    return if (initialNavigate) {
        destination
    } else {
        null
    }
}
}

Use keep_state_fragment instead of fragment in nav_graph
In Activity:
val navController = findNavController(R.id.nav_host_fragment)

    // get fragment
    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)!!
    // setup custom navigator
    val navigator = KeepStateNavigator(this, navHostFragment.childFragmentManager, R.id.nav_host_fragment)
    navController.navigatorProvider += navigator

    // set navigation graph
    navController.setGraph(R.navigation.nav_graph)
    bottom_navigation.setupWithNavController(navController)

Comment: This doesn't work. The fragment is always null and so a new instance is created even though I used  inside navGraph. Seemed an elegant approach, but not working :/

Besides, navController.navigatorProvider gives warning:

NavController.setNavigatorProvider can only be called from within the same library group (groupId=androidx.navigation)
Answer: Use this snippet:
private fun attachFragment(fragmentTag: String) {
    val fragmentTransaction = supportFragmentManager.beginTransaction()
    supportFragmentManager.findFragmentByTag(fragmentTag)?.let {
        if (supportFragmentManager.backStackEntryCount == 0) return
        val currentFragmentTag = supportFragmentManager.getBackStackEntryAt(supportFragmentManager.backStackEntryCount - 1).name
        (supportFragmentManager.findFragmentByTag(currentFragmentTag) as? FragmentBase)?.let { curFrag ->
            fragmentTransaction.hide(curFrag)
        }
        fragmentTransaction.show(it)
    } ?: run {
        when (fragmentTag) {
            FragmentHome.TAG -> FragmentBase.newInstance<FragmentHome>()
            FragmentAccount.TAG -> FragmentBase.newInstance<FragmentAccount>()
            else -> null
        }?.let {
            fragmentTransaction.add(R.id.container, it, fragmentTag)
            fragmentTransaction.addToBackStack(fragmentTag)
        }
    }
    fragmentTransaction.commit()
}

You can use this pass the tag of specific fragment that you want to show now, using method attachFragment(FragmentHome.TAG)
Answer: Hi friend, it's new solution:
BottomNavigationView navView = findViewById(R.id.nav_view);

NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);

binding.navView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() != binding.navView.getSelectedItemId())
                    NavigationUI.onNavDestinationSelected(item, navController);
                return true;
            }
        });

Answer: I was looking for the best way to handle this and finally i came out with this simple idea : deactivate the MenuItem currently selected.
This way, you cannot click twice on it and therefore reloading the fragment is prevented.
Don't forget to Enable it back when you go to another fragment through your navHost.
The mechanic is based on the NavHostFragment which receives your BottomNavigationView from within a fragment/activity.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    navHostFragment =
        childFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment

    val navView: BottomNavigationView = view.findViewById(R.id.nav_view)
    val navController = navHostFragment.navController

    //Here you link the NavHostFragment's navController to your
    //bottomMenu
    navView.setupWithNavController(navController)

    //Add a listener monitoring the destination changes
    navController.addOnDestinationChangedListener(object : NavController.OnDestinationChangedListener{
        override fun onDestinationChanged(
            controller: NavController,
            destination: NavDestination,
            arguments: Bundle?
        ) {
            /* Disable the selected item and re-enable the others */
            for( item in navView.menu.iterator()){
                item.isEnabled = item.itemId != navView.selectedItemId
            }
        }

    })
}

Hoping it might help
Lenzy
Answer: Try this: For ChipNavigationBar
private void Bottom_navigation() {
        final Fragment fragment1 = new home_fragment();
        final Fragment fragment2 = new bottom_nav1_Bookmark_Fragment();
        final Fragment fragment3 = new bottom_nav1_Search_Fragment();
        final FragmentManager fm = getSupportFragmentManager();

 ChipNavigationBar chipNavigationBar = findViewById(R.id.chipNavigation);
        chipNavigationBar.setItemSelected(R.id.home, true);

        fm.beginTransaction().add(R.id.frame, fragment3, "3").hide(fragment3).commit();
        fm.beginTransaction().add(R.id.frame, fragment2, "2").hide(fragment2).commit();
        fm.beginTransaction().add(R.id.frame,fragment1, "1").commit();

        chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int i) {
                Fragment active = fragment1;
                Fragment fragment = null;
                switch (i) {
                    case R.id.home:
                        fm.beginTransaction().hide(active).show(fragment1).commit();
                        active = fragment1;
                        chipNavigationBar.animate().translationY(0);

                        break;
                    case R.id.tajbi:

                        fm.beginTransaction().hide(active).show(fragment2).commit();
                        active = fragment2;

                        break;
                    case R.id.more_App:
                        fm.beginTransaction().hide(active).show(fragment3).commit();
                        active = fragment3;

                        break;
                }
            }
        });
    }

Answer: You can resolve this issue by using this solution.
First, declare fragments that are used in the bottom navigation view.
val fragment1: Fragment = HomeFragment()
val fragment2: Fragment = ProfileFragment()
val fragment3: Fragment = SettingsFragment()
val fm: FragmentManager = supportFragmentManager
var active = fragment1

Now you need to setup the bottom navigation like this
  private fun setUpBottomNavigation() {
    fm.beginTransaction().add(R.id.mainHostFragment, fragment3, "3").hide(fragment3).commit();
    fm.beginTransaction().add(R.id.mainHostFragment, fragment2, "2").hide(fragment2).commit();
    fm.beginTransaction().add(R.id.mainHostFragment,fragment1, "1").commit();
    val navigation = findViewById<View>(R.id.bottomNavigationView) as BottomNavigationView
    navigation.setOnItemSelectedListener(mOnNavigationItemSelectedListener)
}

private val mOnNavigationItemSelectedListener =
    NavigationBarView.OnItemSelectedListener  { item ->
        when (item.itemId) {
            R.id.homeFragment -> {
                supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                fm.beginTransaction().hide(active).show(fragment1).commit()
                active = fragment1
            }
            R.id.assessmentListFragment -> {
                supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                fm.beginTransaction().hide(active).show(fragment2).commit()
                active = fragment2
            }
            R.id.settingsFragment -> {
                supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                fm.beginTransaction().hide(active).show(fragment3).commit()
                active = fragment3
            }
        }
        false
    }

Comment: How can i achieve to mark bottom navigation view item selected?


Removing elements of list using parent/child

Question: I'm looking to dynamically remove li elements from several connected ul lists.  Right now I am assigning 'dblclick' event behaviors by using $("#sortable1").children().on('dblclick',function() {...})
The items in #sortable1 will be moved to other lists (#sortable2, #sortable3, etc) by the user.
When a list item is double clicked, a dialog box pops up asking if the user would like to delete it.  If the user says yes, I want the list item to be removed from whatever list it is in.  I am trying to do it using something like:
$($(this).parent().childNodes[$(this).index()]).remove()

But that doesn't work.
Advice?
Comment: Show us how the function's working, how are the copied/moved list-items connected to each other? Class-name, a `data-*` attribute? Do you have a live demo we can see, at [JS Fiddle](http://jsfiddle.net), [JS Bin](http://jsbin.com/), or similar?
Comment: Could you please provide some more code? I think you might be over complicating things. This is a simple example of what I believe you are doing: http://jsbin.com/ixemuw/2/edit
Comment: so you want to remove the item that was double clicked on? wouldn't $(this).remove() inside of your handler do it?
Comment: I think he wants it to happen after the popup toggle is clicked.
Comment: @MatthewBlancarte that should be ok, he just needs to store $(this) when double clicked then use it later. Oh maybe he wants to remove it from several ul and not jsut the clicked one. Need to see more markup
Comment: Huangsim - brilliant!!  I don't know why I was overthinking it so much - that was all I had to do.
Answer: Something like this should work.
var showPopup = function( elem ){
  //show your popup with a function like this, as i assume it already does...
  $( '#delete_toggle' ).one( 'click', function(){
    elem.remove();
  });
};

$("#sortable1").children().on('dblclick',function(){
  showPopup( $(this) );
});

Answer: To remove the element that was clicked on, you just use this in the event handler:
$(this).remove();

or if you've saved the element reference to a variable elem, it would be this:
$(elem).remove();

You are trying to make it way more complicated than need be.  The jQuery .remove() method looks at who its current parent is and takes care of all that for you.