Animate UIView setFrame to force drawRect on each animatable frame

Question: I've got a UIView with a UILabel on top. I have the UILabel's content mode set to 'UIContentModeLeft'. As expected, when I animate the frame of the UIView to be smaller than the original size, the label 'jumps' to the final frame without animating nicely.
As far as I can see, UIContentModeRedraw does not force 'drawRect' to be called on every 'animated frame'. I've tried using a custom CALayer as well but can't seem to cause the frame to resize smoothly.
Is there any way to do this? The animation as it stands is extremely glitchy. UIContentModes are not useful and I can't use a frame for contentStretch as well as none of the edges of the label can be stretched. What I really need is a 'refresh' of the label every time the parent view resizes.
Comment: Just a thought of the top of my head, have you looked into the key-frame animation methods? You probably get better granularity and control.
Comment: No that's essentially the same thing - as it internally uses a presentationLayer to do the actual animation and UIViewContentMode remains in effect. The only seems to be a NSTimer based animation (so that I explicitly call setFrame on each interval fired) but that's laggy and ugly.
Answer: There's no way of doing this unfortunately, so I've learnt. The only other way is to actually run a timer that updates the frame every time it's invoked. This results in a very jerky animation given a resize of a complex view is time consuming. I ended up achieving the same thing with some pre-rendered onscreen elements and a whole lotta 'magical effects' behind the scene.


KeyError: 'mae' when plotting Keras model training progress

Question: I'm following the exact same code as shown on the Kearas regression models tutorial but am unable to access the tfdocs.plots.HistoryPlotter() method. (New to Google Colab and TensorFlow). The rest of the cells work beside the training progress plots.
Code snippet triggering the error:
plotter.plot({'Basic': history}, metric = 'mae') plt.ylim([0, 10])
plt.ylabel('MAE [MPG]')

And the error:
KeyError                                  Traceback (most recent call last)
<ipython-input-25-deee24f0bc59> in <module>()
----> 1 plotter.plot({'Basic': history}, metric = 'mae')
      2 plt.ylim([0, 10])
      3 plt.ylabel('MAE [MPG]')

/usr/local/lib/python3.6/dist-packages/tensorflow_docs/plots/__init__.py in plot(self, histories, metric, smoothing_std)
     86         self.color_table[name] = color
     87
---> 88       train_value = history.history[metric]
     89       val_value = history.history['val_' + metric]
     90       if smoothing_std is not None:

KeyError: 'mae'

And also importing the necessary functions from tensorflow_docs (as showed on tutorial page) without any errors:
!pip install -q git+https://github.com/tensorflow/docs

Any help is very appreciated!
Comment: I believe 'mae' is not included in the history, have you initialized the variable properly as the docs suggest?
Comment: Thank you. @tharina11 suggestion fixed the issue.
Answer: replace 'mae' in your code with 'mean_absolute_error'.
Comment: Thanks, @tharina11! That worked! Could you elaborate more on why `mae` doesn't work? Is it a keras version issue?
Comment: It is not a keras error. I ran the exact code provided in the colab notebook (https://www.tensorflow.org/tutorials/keras/regression) provided in the video description. Two cells before you plot this graph, there is an output table which is the data source of your plotting code. There I saw  'mean_absolute_error' instead of 'mae' (that is the parameter you are plotting in the graph). :)


Postfix catch-all for all domains/users and send mail to external mailserver

Question: I am configuring a mailserver that has to save all email for any domain and any user and store it in the mailfolder of one specific user. For this I have used the following configuration:
virtual_alias_maps = pcre:/etc/postfix/virtual

# cat /etc/postfix/virtual
/.*/    specificuser

This works perfectly, but the only issue is that I cannot send out email; I want to sent the cron output to, for example, a gmail account. The outgoing cron email is also mapped to the virtual account and saved in the mailfolder of the specific user.
I have tried making the wildcard smaller by adding a domain (e.g. /.*@somedomain/, but that did not do the trick. I have also tried adding an extra line to the /etc/postfix/virtual file:
/root.*/    firstname.lastname@example.com

But then the email is still delivered to the specificuser mailfolder. The address rewrite of root@localserver is correct the first run and rewritten to email@example.com, but then the rewrite is performed again and email@example.comis eventually mapped on the specificuser catchall. See the relevant logging below.
postfix/cleanup[399895]: maps_find: virtual_alias_maps: pcre:/etc/postfix/virtual(0,lock|fold_fix|utf8_request): email@example.com = firstname.lastname@example.com
postfix/cleanup[399895]: mail_addr_find: email@example.com -> email@example.com
[...]
postfix/cleanup[399895]: maps_find: virtual_alias_maps: pcre:/etc/postfix/virtual(0,lock|fold_fix|utf8_request): firstname.lastname@example.com = specificuser
postfix/cleanup[399895]: mail_addr_find: firstname.lastname@example.com -> specificuser

Can someone point me to the correct configuration?
Comment: "I have also tried adding an extra line" - lines are processed IN ORDER until a match is found. That line should have been at the top of the file.
Comment: @symcbean Thanks for the quick reply; I did put it at the top and the **root** email-address is mapped to the configured email-address but than that email-address is again mapped against to the virtual users file  on the **specificuser** catchall. I have added logging to the original post.
Answer: Do something like this
virtual_mailbox_domains = example.com
virtual_mailbox_maps = hash:/etc/postfix/virtual_mailbox
virtual_transport = lmtp:unix:private/dovecot-lmtp

According to the Postfix documentation, a virtual mailbox domain is a domain that does not correspond to a UNIX system account. Instead, each recipient is mapped to a virtual mailbox location of the form /path/name, where /path is a directory (for example, /var/mail/vhosts) and name is a file or directory name under /path. The virtual mailbox location can be different for each recipient in the same domain.
To enable virtual mailbox domains, you need to set the following parameters in your /etc/postfix/main.cf file:
virtual_mailbox_domains = example.com
virtual_mailbox_maps = hash:/etc/postfix/virtual_mailbox
virtual_transport = lmtp:unix:private/dovecot-lmtp

The first parameter specifies the list of virtual mailbox domains that Postfix will accept mail for. You can use a comma-separated list, a hash table, or a regular expression to define the domains. In this case, you have only one domain: example.com.
The second parameter specifies the mapping of virtual mailbox recipients to their virtual mailbox locations. You need to create a file called /etc/postfix/virtual_mailbox and list the recipients and their locations in the following format:
firstname.lastname@example.com    example.com/user1
firstname.lastname@example.com    example.com/user2
...

You can use any directory structure under /var/mail/vhosts as long as it matches the virtual mailbox locations. You need to run postmap /etc/postfix/virtual_mailbox after editing the file.
The third parameter specifies the delivery agent that will handle the mail for the virtual mailbox recipients. In this case, you are using Dovecot's LMTP server, which listens on a UNIX socket called private/dovecot-lmtp. You need to configure Dovecot to enable LMTP and set the mail location for the virtual mailboxes.
According to the Dovecot documentation, you need to add the following lines to your /etc/dovecot/conf.d/10-master.conf file:
service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    mode = 0600
    user = postfix
    group = postfix
  }
}

And you need to add the following lines to your /etc/dovecot/conf.d/10-mail.conf file:
mail_location = maildir:/var/mail/vhosts/%d/%n
mail_uid = vmail
mail_gid = vmail

The first line tells Dovecot where to store the mail for the virtual mailboxes. It uses the same directory structure as Postfix. The %d and %n variables are replaced by the domain and user name of the recipient.
The second and third lines tell Dovecot which user and group to use for accessing the mail files. You need to create a system user and group called vmail with no login shell and no home directory, and make sure that they own the /var/mail/vhosts directory and its subdirectories.
After making these changes, you need to restart Postfix and Dovecot for them to take effect.
Comment: Can you elaborate on your answer; would I then use **gmail.com** as **virtual_mailbox_domains**? And what would I put in the **virtual_mailbox_maps**?
Comment: No, you need to add the domain where you you want to save the mail for. This makes sure that only for that domain the mail is saved and all other domains are handled as usually. I will update my post with some extra information
Comment: I wouldn't do it for all domains, that could be a security risk, and easily become an open relay


"Mean" & "median" comparison and zero variance confusions when making inferences in Bayesian model

Question: Background:
In Chapter8 of this great book, the authors build a Bayesian model and use  to show the posterior distributions of the latent state $N_{t}$ and its credible intervals. The model is written as below:
\begin{aligned}
\left[N,\beta,\sigma_p^2|y\right]\propto&\prod normal(y_{t}|N_{t},\sigma_{data,t}^2)\\
\times&\prod lognormal(N_{t}|log(g(\beta,N_{t-1},x_{t})),\sigma_{p}^2))\\
\times &normal(\beta_{0}|0.234,0.0185)\prod_{i=1}^3normal(\beta_{i}|0,100)\\
\times&inverse\ gamma(\sigma_{p}^2|0.01,0.01)\\
\times&normal(N_{1}|y_{1},\sigma_{data,t}^2)
\end{aligned}
where: $N_{t}$ is the unobserved, true abundance of wildebeest in year t; $x_{t}$ is a measure of the annual rainfall; $\beta$ is the coefficients; $\sigma_{p}^2$ is the process variance; $\sigma_{data,t}^2$ is a variance for the total population based on the sample of paragraphs.
My questions are:
(1) In Fig.1, why do we compare "mean" observed number of animals with "median" of the marginal posterior distribution of the population size (see the Figure's caption)? Why not use "mean" of the marginal posterior distribution to be consistent with dots (i.e., mean)?
(2) The authors remind us that:

The fit of the model medians is not smooth but, rather, tends to jump a bit between time steps. ... if we assumed that observation variance was 0, such that the true state was exactly the same as the observed state, then the medians would go through every data point.

Then they emphasize that:

It may be counterintuitive that a model like this one that does hit every point, or close to it, is probably not a very good model. What this says is that process variance is high relative to observation variance. The predictive value of such a model will be low.

Why would the solid line go through every data point if the observation variance was 0?
Answer: Regarding the second  question, it might be helpful to remember that there is an estimation procedure involved. If the variance of the measured data drops to zero, there is only one estimation result possible -- the one that is exactly the same as the measured one.
This is a feature of any estimation procedure that accounts for the variance of observations. This however is absolutely no indication of whether it is a "good" model.
For the first question, I might need to edit/delete the next part of my answer:
There might be some information missing or being assumed about the true and unobserved (unobservable!) population size. My guess would be, that the quantiles of the median are either smaller or better defined than the mean and its variance. It might even be, that the mean cannot easily be calculated in this particular case.
However, for the estimation procedure (the original task) it makes no difference what the plot is showing.
Comment: Sorry for the delayed answer; hopefully I can clarify a bit. Regarding (1): it's speculative, I don't know. The idea is simply that the "median" might be favorable to the "mean". Both are valid and well-defined measures, and a priori it's not clear which might be better suited. Regarding (2), again: without more knowledge it's only speculation. For this particular case this idea is probably not applicable. What I was thinking is: the underlying distribution might have no mean; but with every estimation method one can extract a mean, but it is neither accurate nor meaningful (no pun intended).
Comment: Thanks so much! I think I get your point: sometimes "mean" is not meaningful, for example "average wage". One more confirmation, you said "the quantiles of the median are smaller than the mean and its variance", do you mean "the variance of median is smaller than the variance of mean" in some cases, so we might choose median because it has a smaller variance?
Comment: To the last question: yes. But the important bit is to interpret "variance of mean/median" in terms of "accuracy" of said value. There are few words in statistics that do not have a specific meaning. For example "variance" is usually the second central moment of a distribution and only in special cases it has something to do with the uncertainty of the mean.
Comment: I am a little confused in two places in your answer. (1) Why " the quantiles of the median are smaller than the mean and its variance" makes us choose median instead of mean? Should we choose "a smaller value"? (2) Why "the mean cannot easily be calculated" in some cases? I think we can calulate its value through MCMC estimations.


Side effects to switching MatchParen off in vim Insert Mode

Question: I want vim to highlight the paren/bracket/brace that matches the one under the cursor in normal mode. When I switch to insert mode, though, I want the matching to stop. (It makes it impossible to see my bar cursor when there's a highlighted block cursor right next to it.)
This is easy enough to do:

au InsertEnter * :NoMatchParen
  au InsertLeave * :DoMatchParen

However, this combination of autocmds introduces a weird behavior that I can't live with: if I'm in a vsplit on the right, or a split on the bottom, and switch to the split at the left/top, and then enter insert mode, focus reverts to the other pane. This happens whether I enter insert mode immediately, or move the cursor around in normal mode first.
An especially weird thing is that focus is NOT jumping to the most recent pane. If I enter insert mode in the bottom/right pane, the cursor remains where it is.
I have tried a few combinations of WinEnter, CursorMoved and other events, but haven't found anything that doesn't either leave this behavior or introduce something even worse.
So, to phrase in the form of a question: how can I make this stop?
Comment: Are you looking for `set noshowmatch` ?
Comment: No. The showmatch functionality is different.
Answer: The commands :DoMatchParen and NoMatchParen of the matchparen plugin work internally using the :windo command, which unfortunatly leaves the cursor in the wrong window. This has been discussed in the vim-dev list previously. There is no solution currently. You need to save the cursor position before calling those commands and then restore it afterwards.
Comment: That's good to know. Instead of turning MatchParen on and off, I can leave it on all the time, and just change the highlight color to match the background color in Insert Mode.


Response.write vs Document.write

Question: Inside a classic asp page, I'm told that you can use vbscript or jscript.  And jscript is just javascript.
So I'm not sure what the difference is between Response.Write, Response.Write(), response.write(), and document.write()
Does the capitalization matter, and sometimes I seem to see no parentheses after the method name, and sometimes I do.  It's all devolving into a mess inside my newbie head.
If I'm writing classic asp using JScript (and not VBScript), should everything inside <%    %>  be considered javascript, just on the server side?
Prior to classic asp, I was sure that javascript was a client-side scripting language only.
Comment: @Raynos - don't jump to conclusions, this could be a minor maintenance job.
Answer: You can use VBScript or JScript as your language when writing classic ASP server-side code.
From Wikipedia:

JScript is Microsoft's implementation of the ECMAScript standard that
  is used in Microsoft's Internet Explorer.

You can also use it in classic ASP, and it has some additional objects available (Response, Request, Application, Session, etc) so that you can do server-side web programming.
If I was required to write classic ASP, I would definitely choose JScript. Each language has its own syntax requirements that you will need to learn whichever you choose.
document.write() is not used server-side to send data back to the client, you always use the Response object for that.

If I'm writing classic asp using JScript (and not VBScript), should everything inside <% %>be considered javascript, just on the server side?

Depends on the context—generally the syntax is the same. Stick with Microsoft's JScript documentation and you'll be fine.
Answer:
So I'm not sure what the difference is between Response.Write,
  Response.Write(), response.write(), and document.write()

If they all work, then I would suggest to just pick one and go with it. Though, I remember reading that you should not use document on the server side.
No, you don't have to worry about the capitalization in vbscript. It really comes down to personal preference. I like to use Response.Write() myself, but I've seen response.write littered throughout source code as well.
Methods with parentheses vs methods without parentheses.
The difference is the type of method. Vbscript supports sub and function methods. A sub is used when no data is meant to be returned and a function is used when data is to be returned. A sub method takes it's parameters without parentheses (the server will complain if you try to call a sub with parentheses and more than one parameter). A function takes it's parameters with parentheses. Don't ask me why the creators chose to do it this way, it annoys the heck out of me.
JavaScript can be used on the server with classic asp. It actually can come in handy if you are wanting to pass JSON around https://stackoverflow.com/a/1021848/296889.
Answer: Yes capitalization does matter. VB tends to lean towards pascal casing for methods, so .Write() would be correct in vb. But .write() would be correct in javascript. If it is a predefined function that is.
No everything inside the <% %> tags would not be considered javascript, it would be considered asp.
Comment: ASP is not its own language. JavaScript can be executed anywhere that there is a compatible interpreter (including class ASP).
Comment: There actually are ways to run javascript on the server... it's just a programming language. http://www.codeproject.com/Articles/4271/Sharing-JavaScript-source-code-between-client-side
Comment: -1: ASP is not a language. The languages are VBScript and JScript, the latter which you seem unaware of.

Response.write vs Document.write


Get the first instance of a field where it's not null from rows

Question: I've got a view page, which is pulling together quite a few content types. All of these content types have a field called field_image, however some are not required and/or are missing.
I basically need to grab the first (latest - sorting by author date in my view settings) row, check if there's a field_image, if there is, we can just return that field, if not, repeat.
I thought about a few different ways of doing this, and I thought that I'd make it a Twig command for ease. My issue is that I can't seem to get the single field I'm looking for.
My Twig function is currently:
public function get_first_instance($field, $rows) {
  foreach($rows[0]['#rows'] as $row) {
    dump($row['#row']);
    exit;
  }
}

I'm running the Twig command from my views-view--my-content-type--page.html.twig template, passing a string, and rows.
I can see that the field_image is located in _entity > #fields > field_image, I'm just not sure how to reference this, or what function to use to load the entity?
Thanks for any help in advance.
Answer: Solved it, makes sense now!
public function get_first_instance($field, $rows) {

  foreach($rows[0]['#rows'] as $row) {
    $entity = $row['#row']->_entity;

    if($entity->hasField($field)) {
      $value = $entity->get($field)->getValue();

      if(! empty($value)) {
        return $value;
      }
    }
  }

  return dump('Field not found: '.$field);
}


Why does the variance of a sample change if the observations are duplicated?

Question: The variance is said to be a measure of spread. So, I had thought that the variance of 3,5 is equal to the variance of 3,3,5,5 since the numbers are equally spread. But this is not the case, the variance of 3,5 is 2 while the variance of 3,3,5,5 is 1 1/3.
This puzzles me, given the explanation that variance is supposed to be a measure of spread.
So, in that context, what does measure of spread mean?
Answer: If you define variance as $s^2_{n}=$$\,\text{MSE}\,$$=\frac1n \sum_{i=1}^n (x_i-\bar{x})^2$ -- similar to population variance but with sample mean for $\mu$, then both your samples would have the same variance.
So the difference is purely because of Bessel's correction in the usual formula for the sample variance ($s^2_{n-1}=\frac{n}{n-1}\cdot \text{MSE}=\frac{n}{n-1}\cdot \frac1n \sum_{i=1}^n (x_i-\bar{x})^2=\frac{1}{n-1}\sum_{i=1}^n (x_i-\bar{x})^2$, which adjusts for the fact that the sample mean is closer to the data than the population mean is, in order to make it unbiased (taking the right value "on average").
The effect gradually goes away with increasing sample size, as $\frac{n-1}{n}$ goes to 1 as $n\to\infty$.
There's no particular reason you have to use the unbiased estimator for variance, by the way -- $s^2_n$ is a perfectly valid estimator, and in some cases may arguably have advantages over the more common form (unbiasedness isn't necessarily that big a deal).
Variance itself isn't directly a measure of spread. If I double all the values in my data set, I contend they're twice as "spread". But variance increases by a factor of 4. So more usually, it is said that standard deviation, rather than variance is a measure of spread.
Of course, the same issue occurs with standard deviation (the usual $s_{n-1}$ version) as with variance -- when you double up the points the standard deviation changes, for the same reason as happens with the variance.
In small samples the Bessel correction makes standard deviation somewhat less intuitive as a measure of spread because of that effect (that duplicating the sample changes the value). But many measures of spread do retain the the same value when duplicating the sample; I'll mention a few --

$s_n$ (of course)
the mean (absolute) deviation from the mean
the median (absolute) deviation from the median
the interquartile range (at least for some definitions of sample quartiles)
Comment: "There's no particular reason you have to use the unbiased estimator" -- indeed you shouldn't necessarily *estimate* anything. The variance of `{3, 5}` itself is 1, per the first formula. As you point out, the questioner has attempted to estimate the variance of a population from which this is presumed to be a sample, but who knows whether it is or not.
Answer: As some sort of mnemonic, $V\,X = E\,V\,X + V\,E\,X$.  So the expected value of a sample's variance is too low, with the difference being the variance of the sample's mean.
The usual sample variance formula compensates for that, and the variance of the sample's mean scales inversely with sample size.
As an extreme example, taking a single sample will always show a sample variance of 0, obviously not indicating a variance of 0 for the underlying distribution.
Now for 2 and 4 evenly weighted samples, the corrective factors are $2/1$ and $4/3$, respectively.  So your calculated expected variances differ by a factor of $2/3$.  The variance of the sample itself is $1$ in either case.  But the first case presents a weaker case for $4$ being the mean of the base distribution, and every other value would mean a larger variance.
Comment: By conflating *estimators* with *statistics*, this answer confuses, rather than clarifies, the question. Please read Glen_b's original answer in this thread. The argument in the first two paragraphs is mysterious because it seems to be irrelevant to the question.


How to come over nervousness while stage performance?

Question:
Possible Duplicate:
How can I overcome the fear of performing in front of an audience?

I have played guitar several time on stage. But every time I start performing I feel a lot nervous. I may call it stage fear but I want to defeat this feeling now. Please let me know what I can do or make myself comfortable while playing music on stage.
(It only happens when I am playing music on stage. It never really happened while giving a presentation in office. :P)
Comment: Related: http://music.stackexchange.com/q/505/249
Answer: One thing to keep in mind is that you should know it is not the end of the world if you do mistakes. Most mistakes that you do will not even be noticed by the audience, even if you think it's a big mistake.
Because of this, you must continue as nothing happened.
Knowing this fact, you can also have more confidence, because you will know that it is not important to play 100% perfect (or 83% perfect). Even if you do mistakes that are so obvious that the audience will notice, it will be no issue if you just ignore it yourself.
If you make faces or stop and comment it or something, the audience will most likely remember the mistake after the performance, but if you ignore it and just play on, the audience will have forgot it after 32 seconds (more or less...).


Can I use the "unused" Bb Key on the flute?

Question: While positioning your fingers on the flute, there is one key left out between the left hand 2nd and 3rd finger. I've noticed that it does the same thing as the Bb Thumb Key. I prefer to use it while trilling between Bb and B, and in pieces like "Radetzky March", where the notes after the Bb and the B are below it. It there any downside to doing so? I can change the 3rd finger to the A key relatively fast.
Answer: This is a classic example of "Get thee to a teacher."  The flute family, like the clarinet family, sax family, and AFAIK the double reeds, have many alternate fingerings available by design.  Which fingering to use depends on the passage as a whole: what fingerings must be used before and after the note in question, and what minimizes finger motion?   It's always best (until you become a semi-pro quality player) to discuss fingering patterns with an experienced teacher.
As a point of possible interest: clarinets in particular have keys set up so that several notes (bottom of each range) can be played with either little finger; once in a while a passage comes along which requires one to use first one finger, then "transfer" to the other little finger within a single note!
Comment: @NullCoderExists  "Never trust what you learn on the Internet" --Abraham Lincoln.      If you're self-taught, I frankly shudder to think what your embouchure looks like.  Self-teaching any musical instrument is at best a highly risky venture.
Comment: Have to disagree (again!) with 'highly risky venture'. There are many many players, of many instruments, out there who are superb players, perhaps *despite* the fact that they are self-taught. On guitar and bass, I'm completely self-taught, but that hasn't stopped me facilitating hundreds, of other players, not only to play well, but showing  very good exam results - if that could be considered a criterion. But I'm with you on the internet bit!  Are you certain it was Abe..?
Comment: I don't have a teacher. I'm self taught. That's why its not "Get thee to a teacher." Its  "Get thee to the internet."
Answer: Don't see any downside if it's comfortable for you, and doesn't get you confused. The standard fingerings for Bb are of course going to be better for fast scale passages, etc.
Answer: I think this is not a good choice. With flute, your grip on the instrument is already a bit tenuous, and shifting the hand to play it in a nonstandard way could cause problems. Why not just use the normal T1--|1-- fingering?

Can I use the “unused” Bb Key on the flute?


is $\mathbb{Q} ^{|\mathbb{R}|} \times \{1 \}$ divisible subgroup of $ \mathbb{Q} ^{|\mathbb{R}|} \times \mathbb{Z}_2$?

Question: According to Unit Groups of Classical Rings by Karpilovsky, p.107 we know that:
If $F$ is a real-closed field, then $F^*\simeq \mathbb{Q} ^{|F|} \times \mathbb{Z}_2$.
Now, we know that $\mathbb{R}$ is a real-closed field. So we should have $\mathbb{R}^*\simeq \mathbb{Q} ^{|\mathbb{R}|} \times \mathbb{Z}_2$.
Also we know that $\mathbb{R}^*$ is not divisible but there is a divisible maximal subgroup $(\mathbb{R}^*)^+$ of $\mathbb{R}^*$. So there must exists a divisible maximal subgroup of $\mathbb{Q} ^{|\mathbb{R}|} \times \mathbb{Z}_2$ corresponding to $R^+$.
I think this divisible maximal subgroup is $\mathbb{Q} ^{|\mathbb{R}|} \times \{1 \}$, but I don't know how I should prove the divisibility of $\mathbb{Q} ^{|\mathbb{R}|} \times \{1 \}$.
Comment: What is $F^*$ here?
Answer: Being a direct product of copies of $\mathbb{Q}$, the subgroup you are considering is divisible. Given $y=(x_c)_{c\in \mathbb{R}}$ in the group and an integer $n$, define $y'=(x_c/n)_{c\in\mathbb{R}}$. Then $ny'=y$, so the divisibility condition is satisfied. Indeed, the $\mathbb{Q}^{|\mathbb{R}|}$ factor is $\mathbb{R}^+$, and the $\mathbb{Z}_2$ factor is $\{-1,1\}$.
Comment: Divisible means: for all $a\in F$ and $n\in \mathbb{N}$, there exists $b\in F$ such that $b^n=a$. So we should prove that if $y=(x_c)_{c\in\mathbb{R}}$, then there exists $y'$ such that $y'^n=y$. How?
Comment: @khoda I used additive notation. The operation in the group is addition, so $(y')^n=y'+y'+\cdots+y'=ny'$.
Comment: @khoda The isomorphism is a bit confusing, on the left the operation is multiplication, on the right it is addition.
Comment: But I mean by $\mathbb{R} ^*$ the multiplicative group of $\mathbb{R}$.
Comment: @khoda Yes, but $\mathbb{Q}^{|\mathbb{R}|}\times\mathbb{Z}_2$ is not the multiplicative monoid because that is not a group, it is an additive group.
Comment: I agree with you. I had a mistake because I thought that the operation of right hand side is multiplication and it is wrong because it has zero element. Thank you.
Comment: @khoda No problem.


"Lebesgue" measurabillity on Riemannian manifolds

Question: Let $X$ be a smooth oriented manifold of positive dimension; Let $g_1,g_2$  be two Riemannian metrics on $X$. Define $\Lambda_1,\Lambda_2:C_c(X) \to \mathbb{R}$ by
$$ \Lambda_i(f)=\int_X f \, Vol_{g_i},$$ where $Vol_{g_i}$ is the Riemannian volume form of $g_i$.
The discussion here implies that for each $i$, there is a unique $\sigma$-algebra $\mathfrak B_i$, and a unique measure $\mu_i$ such that $I(f)=\int_X f d \mu$ for all $f \in C_c(X)$, and the conditions (a)-(f)** are satisfied. (This is essentially Riesz Representation theorem, with the additional observation that $X$ is $\sigma$-compact $\Rightarrow$ uniqueness of the $\mathfrak B_i$).
Questions:
(1) Is it true that $\mathfrak B_1= \mathfrak B_2$? (independence of the metric chosen)
Assuming this is true, is there a way to define $\mathfrak B_i$ without passing through a Riemannian metric? (This is a natural expectation now since $\mathfrak B_i$ is an invariant of $X$ as a differentiable manifold, thus unrelated to the added Riemannian structure)
My guess is that $\mathfrak B_i$ will be the completion of the Borel $\sigma$-algebra w.r.t a suitable measure (which should be any one of the "Lebesgue" measures $\mu_i$ mentioned above. On a first glance, this does seem to go through a Riemannian metric, since the $\mu_i$ was induced by it.
However, the completion w.r.t a measure $\mu$ is dependent only on the  subsets that have $\mu$-measure zero, and this is independent of the Riemannian metric chosen, and can be defined invariantly (see Lee's book on smooth manifolds, chapter 6: A subset of a manifold has measure zero if its image under every coordinate chart has measure zero  in $\mathbb{R}^n$)
(2) A function $f:X \to \mathbb{R}$ is measurable w.tr.t $\mathfrak B_i$ if and only if it is measurable after (pre)composing with a coordinate chart diffeomorphism?
(3) Is this the standard way to define $L^p(X)$ spaces (from the perspective of measurability, are the elements of $L^p(X)$ exactly the measurable functions in the sense above, with the additional requirement of finiteness of the integral?)

**
(a) $\mathfrak{B_i}$ contains all Borel sets,
(b) $\mu(V)=\sup \{I(f): f \in C_c(X), 0\leq f \leq 1, \operatorname{supp} f \subset V\}$ for each open $V$,
(c) $\mu(K) < \infty$  for compact $K$,
(d) $\mu(E)=\inf \{\mu(V): E \subset V, \ V \mbox{ open}\}$ for each $E \in \mathfrak{B}$,
(e) $\mu(E)=\sup \{\mu(K): K \subset E, \ K \mbox{ compact} \}$ for each open $E$ and for each $E\in \mathfrak{B}$ such that $\mu(E)< \infty$,
(f) $\mu$ is a complete measure on $\mathfrak{B}$.
Comment: Because the integrability is restrained by the charts and by your word "smooth". If $\phi$ is a smooth diffeomorphism and $f$ is a function integrable on $U$, then $\phi^{*}f\cdot J$ is Lebesgue integrable on $U$ iff $f$ is Lebesgue integrable on $\phi(U)$ where $J$ is the jacobian of $\phi$. You buy the charts and topology, you buy the measurable sets.
Comment: The term "smooth oriented manifold" includes the topology and the atlas of charts. If you change topology, then it's a different set of charts, and a different manifold.  Does this help?
Comment: I am not sure what is the relevance of your comment. It is true that if we change the topology the manifold "changes", and so its *Borel* $\sigma$-algebra. However, we are talking here about $\sigma$-algebras which strictly contain the Borel $\sigma$-algebra. Would you mind elaborating?
Answer: To put it brief, as hkr noted in the comment, "you buy the charts and topology, you buy the measurable sets".
Here is a more detailed answer:
(1) It is possible to define the Lebesgue sigma-algebra on a general manifold (with or `without' boundary) without alluding to Riemannian metrics or specific choices of densities.
Details can be found in Chapter XII of Amann, H. & Escher, J. "Analysis III". (Birkhäuser, 2009).
(2) This is implied by (1), as otherwise the construction would not work. A function is integrable with respect to a given measure---an invariant notion. (1) only gives you the sigma-algebra on the manifold, it does not give you the measure, however. Whether a function is integrable may depend on the choice of volume form/density, but I do not know of any more detailed discussion of this topic.
(3) Again, if you take a measure-theoretic perspective, the notions of Lp spaces carry over. In the mentioned reference, they even treat the case that the functions take values in some Banach space. A more interesting question would be, if one can make sense of "Lp-spaces of forms".


What trigonometric identities was used to get this?

Question: I have this solution for a math question, but I didn't get how did we get from the line $3$ to $4$ and also from $4$ to $5$. I can understand that this is done through trigonometric identities. but which ones?
The question is
Comment: Please do not use pictures for critical portions of your post. Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers. – For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: this is complex number that's why j is used
Comment: What is $j{}{}$?
Comment: $i=j=\sqrt{-1}$ both are used, latter more in electrical engg.
Comment: @markvs In complex numbers, usually $i$ is used to represent $\sqrt{-1}$; in electrical engineering, $i$ represents current, so $j$ is used instead.
Comment: @bjcolby: I think that number $i$ was introduced **long before** electric currents were discovered. So electrical engineers should choose another letter.
Comment: @markvs: Agreed.
Answer: The entire calculation seems highly suspect to me, not just due to the (not entirely consistent) use of trig identities, but also due to an earlier step.
I will use $i$ for the imaginary unit. I will also insert some parentheses since I really dislike reading notation like $i\pi/2t$.
In the absence of a definition of $X$ I will have to assume that the derivation of this equation from the summation form is correct:
$$
x(t) = 6 + (-4 - 2i) e^{i(\pi/2)t} + 2 e^{i(2\pi/2)t} + (-4 + 2i) e^{i(3\pi/2)t}. \tag1
$$
On the next line it is claimed that
$$
x(t) \stackrel?=
 6 + (-4 - 2i) e^{i(\pi/2)t} + (-4 + 2i) e^{-i(\pi/2)t} + 2 e^{i\pi t}. \tag2
$$
Observing that the first, second, and third terms on the right side of Equation $(1)$ are equal to the first, second, and fourth terms on the right side of Equation $(2)$,
the claim in Equation $(2)$ comes down to a claim that
$$
(-4 + 2i) e^{i(3\pi/2)t} \stackrel?= (-4 + 2i) e^{-i(\pi/2)t}. \tag{*}
$$
Since $3\pi/2 = -\pi/2 + 2\pi,$ Equation $(\text{*})$ is true for every integer value of $t$, but it is false for every other value of $t$.
The next equation is a simple rearrangement of terms from Equation $(2)$:
$$
x(t) \stackrel?=
 6 - 4\left(e^{i(\pi/2)t} + e^{-i(\pi/2)t}\right)
 - 2i \left(e^{i(\pi/2)t} - e^{-i(\pi/2)t}\right) + 2 e^{i\pi t}. \tag3
$$
From this we are supposed to conclude that
$$
x(t) \stackrel?= 6 - 8 \cos((\pi/2)t) + 4 \sin((\pi/2)t) + 2\cos(\pi t). \tag4
$$
The first, second, and third terms of Equation $(4)$ are equal to the first three  terms of Equation $(3)$ by well-known trig identities.
In order to derive Equation $(4)$ from Equation $(3)$, then, we must believe that
$$
2 e^{i\pi t} \stackrel?= 2\cos(\pi t). \tag{**}
$$
Since $\cos(\theta) = \Re\left(e^{i\theta}\right),$
the real parts of both sides of Equation $(\text{**})$ match up all right,
but the imaginary parts do not.
Once again we have an equation that is true for every integer $t$ but
false for every other value of $t$.
If the final answer is correct it seems to me it could only be through previous lucky errors in the calculations before the final sequence of equations in the question.
Answer: The identities are...

$e^{jt} = \cos t + j \sin t$
$\Re (e^{jt}) = \cos jt = \dfrac {e^{jt} + e^{-jt}}{2}$ and $\Im (e^{jt}) = \sin jt = \dfrac {e^{jt} - e^{-jt}}{2i}$
$a \sin t + b \cos t = \sqrt {a^2 + b^2} \cos\left(t + \arctan \left(-\dfrac {b}{a}\right)\right)$

Note: I am using $j$ here as in the exercise, but usually the imaginary unit for $\sqrt {-1}$ is $i$.
Comment: @markvs Ha...I knew I was missing something in the formula!  Thanks for catching this - I've updated my post.
Comment: thanks a lot for all answers and especially @bjcolby15 you are a life saver, i have never seen the third identity before that's why i was so confused. but dont you think it should be arctan -b/a ?
Comment: @zed_eln No problem! You are right, however, that it should be $-\dfrac {b}{a}$.  I have corrected my post.


dotnet tool restore fails with Unable to load the service index for source - 401 (Unauthorized)

Question: I have a private nuget feed hosted through our Azure DevOps Server 2020 (Azure Artifacts), which I try to access from a build pipeline. Here's the command using a .Net Core task (v2):
C:\Agent\_work\_tool\dotnet\dotnet.exe tool restore --verbosity detailed
Unfortunately, I always get the following error:
C:\Agent\_work\_tool\dotnet\sdk\5.0.403\NuGet.targets(131,5): error : Unable to load the service index for source http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json. [C:\Users\DevOps-AzAgent$\AppData\Local\Temp\c1xjkwos.iwp\restore.csproj]
C:\Agent\_work\_tool\dotnet\sdk\5.0.403\NuGet.targets(131,5): error :   Response status code does not indicate success: 401 (Unauthorized). [C:\Users\DevOps-AzAgent$\AppData\Local\Temp\c1xjkwos.iwp\restore.csproj]

My Azure DevOps Agents are running using a MSA, which has no permissions on our Azure DevOps Server nor the nuget feed. The agent should authenticate by using the security token (System.AccessToken) provided by the build engine. Our Build Service has Contributor permissions to the feed.
To get the authentication right, I inserted a NuGet authenticate task. Here's the output of the task:
Installing the Azure Artifacts Credential Provider (.NET Framework) to 'C:\Users\DevOps-AzAgent$\.nuget\plugins\netfx\CredentialProvider.Microsoft'. This credential provider is compatible with nuget.exe 126.96.36.19985 or later, and MSBuild 188.8.131.52604 or later.

Installing the Azure Artifacts Credential Provider (.NET Core) to 'C:\Users\DevOps-AzAgent$\.nuget\plugins\netcore\CredentialProvider.Microsoft'. This credential provider is compatible with dotnet SDK 2.1 or later.

Setting up the credential provider to use the identity 'XXX Build Service (XXX)' for feeds in your organization/collection starting with:
  http://tfs.XXXsoftware.at:8080/tfs/XXX/

I checked the environment variables after executing the NuGet authenticate task and it creates the following ones:

VSS_NUGET_ACCESSTOKEN
VSS_NUGET_URI_PREFIXES

Here are the logs of the dotnet tool restore command:
         Using C:\Users\DevOps-AzAgent$\.nuget\plugins\netcore\CredentialProvider.Microsoft\CredentialProvider.Microsoft.dll as a credential provider plugin.
             [CredentialProvider.113308]Running in plug-in mode
             [CredentialProvider.113308]Command-line v0.1.28+103227dd070f2b048ce0ae9bc259f12d509d85e2: C:\Users\DevOps-AzAgent$\.nuget\plugins\netcore\CredentialProvider.Microsoft\CredentialProvider.Microsoft.dll -Plugin
             [CredentialProvider.113308]Handling 'Request' 'Initialize'. Time elapsed in ms: 4 - Payload: {"ClientVersion":"5.11.1","Culture":"de-DE","RequestTimeout":"00:00:05"}
             [CredentialProvider.113308]Sending response: 'Request' 'Initialize'. Time elapsed in ms: 5
             [CredentialProvider.113308]Time elapsed in milliseconds after sending response 'Request' 'Initialize': 7
             [CredentialProvider.113308]Handling 'Request' 'GetOperationClaims'. Time elapsed in ms: 0 - Payload: {}
             [CredentialProvider.113308]Sending response: 'Request' 'GetOperationClaims'. Time elapsed in ms: 6
             [CredentialProvider.113308]Time elapsed in milliseconds after sending response 'Request' 'GetOperationClaims': 15
             [CredentialProvider.113308]Handling 'Request' 'SetLogLevel'. Time elapsed in ms: 1 - Payload: {"LogLevel":"Debug"}
             [CredentialProvider]Sending response: 'Request' 'SetLogLevel'. Time elapsed in ms: 2
             [CredentialProvider]Time elapsed in milliseconds after sending response 'Request' 'SetLogLevel': 12
             [CredentialProvider]Handling 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 5 - Payload: {"Uri":"http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json","IsRetry":false,"IsNonInteractive":true,"CanShowDialog":false}
             [CredentialProvider]Creating a progress reporter with interval: 00:00:02
             [CredentialProvider]Handling auth request, Uri: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json, IsRetry: False, IsNonInteractive: True, CanShowDialog: False
             [CredentialProvider]URI: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]VstsBuildTaskServiceEndpointCredentialProvider - This credential provider must be run under the Team Build tasks for NuGet with external endpoint credentials. Appropriate environment variable needs to be set.
             [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Using NuGetCredentialProvider.CredentialProviders.VstsBuildTask.VstsBuildTaskCredentialProvider to try to get credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json.
             [CredentialProvider]VstsBuildTaskCredentialProvider - IsRetry: False
             [CredentialProvider]VstsBuildTaskCredentialProvider - URI Prefixes:
             [CredentialProvider]VstsBuildTaskCredentialProvider - http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Sending response: 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 19
             [CredentialProvider]Time elapsed in milliseconds after sending response 'Request' 'GetAuthenticationCredentials': 23
             [CredentialProvider]Handling 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 0 - Payload: {"Uri":"http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json","IsRetry":true,"IsNonInteractive":true,"CanShowDialog":false}
             [CredentialProvider]Creating a progress reporter with interval: 00:00:02
             [CredentialProvider]Handling auth request, Uri: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json, IsRetry: True, IsNonInteractive: True, CanShowDialog: False
             [CredentialProvider]URI: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]VstsBuildTaskServiceEndpointCredentialProvider - This credential provider must be run under the Team Build tasks for NuGet with external endpoint credentials. Appropriate environment variable needs to be set.
             [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Using NuGetCredentialProvider.CredentialProviders.VstsBuildTask.VstsBuildTaskCredentialProvider to try to get credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json.
             [CredentialProvider]VstsBuildTaskCredentialProvider - IsRetry: True
             [CredentialProvider]VstsBuildTaskCredentialProvider - URI Prefixes:
             [CredentialProvider]VstsBuildTaskCredentialProvider - http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Sending response: 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 1
             [CredentialProvider]Time elapsed in milliseconds after sending response 'Request' 'GetAuthenticationCredentials': 1
             [CredentialProvider]Handling 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 0 - Payload: {"Uri":"http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json","IsRetry":true,"IsNonInteractive":true,"CanShowDialog":false}
             [CredentialProvider]Creating a progress reporter with interval: 00:00:02
             [CredentialProvider]Handling auth request, Uri: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json, IsRetry: True, IsNonInteractive: True, CanShowDialog: False
             [CredentialProvider]URI: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]VstsBuildTaskServiceEndpointCredentialProvider - This credential provider must be run under the Team Build tasks for NuGet with external endpoint credentials. Appropriate environment variable needs to be set.
             [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Using NuGetCredentialProvider.CredentialProviders.VstsBuildTask.VstsBuildTaskCredentialProvider to try to get credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json.
             [CredentialProvider]VstsBuildTaskCredentialProvider - IsRetry: True
             [CredentialProvider]VstsBuildTaskCredentialProvider - URI Prefixes:
             [CredentialProvider]VstsBuildTaskCredentialProvider - http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Sending response: 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 0
             [CredentialProvider]Time elapsed in milliseconds after sending response 'Request' 'GetAuthenticationCredentials': 0
             [CredentialProvider]Handling 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 0 - Payload: {"Uri":"http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json","IsRetry":true,"IsNonInteractive":true,"CanShowDialog":false}
             [CredentialProvider]Creating a progress reporter with interval: 00:00:02
             [CredentialProvider]Handling auth request, Uri: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json, IsRetry: True, IsNonInteractive: True, CanShowDialog: False
             [CredentialProvider]URI: http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]VstsBuildTaskServiceEndpointCredentialProvider - This credential provider must be run under the Team Build tasks for NuGet with external endpoint credentials. Appropriate environment variable needs to be set.
             [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Using NuGetCredentialProvider.CredentialProviders.VstsBuildTask.VstsBuildTaskCredentialProvider to try to get credentials for http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json.
             [CredentialProvider]VstsBuildTaskCredentialProvider - IsRetry: True
             [CredentialProvider]VstsBuildTaskCredentialProvider - URI Prefixes:
             [CredentialProvider]VstsBuildTaskCredentialProvider - http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: http://tfs.XXXsoftware.at:8080/tfs/XXX/
             [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json
             [CredentialProvider]Sending response: 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 1
             [CredentialProvider]Time elapsed in milliseconds after sending response 'Request' 'GetAuthenticationCredentials': 1
     1>C:\Agent\_work\_tool\dotnet\sdk\5.0.403\NuGet.targets(131,5): error : Unable to load the service index for source http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json. [C:\Users\DevOps-AzAgent$\AppData\Local\Temp\qn20vf2i.kp0\restore.csproj]
C:\Agent\_work\_tool\dotnet\sdk\5.0.403\NuGet.targets(131,5): error :   Response status code does not indicate success: 401 (Unauthorized). [C:\Users\DevOps-AzAgent$\AppData\Local\Temp\qn20vf2i.kp0\restore.csproj]
         NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json.
          ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
            at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
            at NuGet.Protocol.HttpSource.<>c__DisplayClass15_0`1.<<GetAsync>b__0>d.MoveNext()
         --- End of stack trace from previous location ---
            at NuGet.Common.ConcurrencyUtilities.ExecuteWithFileLockedAsync[T](String filePath, Func`2 action, CancellationToken token)
            at NuGet.Common.ConcurrencyUtilities.ExecuteWithFileLockedAsync[T](String filePath, Func`2 action, CancellationToken token)
            at NuGet.Protocol.HttpSource.GetAsync[T](HttpSourceCachedRequest request, Func`2 processAsync, ILogger log, CancellationToken token)
            at NuGet.Protocol.ServiceIndexResourceV3Provider.GetServiceIndexResourceV3(SourceRepository source, DateTime utcNow, ILogger log, CancellationToken token)
            --- End of inner exception stack trace ---
            at NuGet.Protocol.ServiceIndexResourceV3Provider.GetServiceIndexResourceV3(SourceRepository source, DateTime utcNow, ILogger log, CancellationToken token)
            at NuGet.Protocol.ServiceIndexResourceV3Provider.TryCreate(SourceRepository source, CancellationToken token)
            at NuGet.Protocol.Core.Types.SourceRepository.GetResourceAsync[T](CancellationToken token)
            at NuGet.Protocol.Core.Types.SourceRepository.GetResourceAsync[T]()
            at NuGet.Protocol.HttpFileSystemBasedFindPackageByIdResourceProvider.TryCreate(SourceRepository sourceRepository, CancellationToken token)
            at NuGet.Protocol.Core.Types.SourceRepository.GetResourceAsync[T](CancellationToken token)
            at NuGet.Protocol.Core.Types.SourceRepository.GetResourceAsync[T]()
            at NuGet.Commands.SourceRepositoryDependencyProvider.EnsureResource()
            at NuGet.Commands.SourceRepositoryDependencyProvider.FindLibraryCoreAsync(LibraryRange libraryRange, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.Commands.SourceRepositoryDependencyProvider.<>c__DisplayClass19_0.<<FindLibraryAsync>b__0>d.MoveNext()
         --- End of stack trace from previous location ---
            at NuGet.Commands.SourceRepositoryDependencyProvider.FindLibraryAsync(LibraryRange libraryRange, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.<>c__DisplayClass9_1.<<FindLibraryFromSourcesAsync>b__0>d.MoveNext()
         --- End of stack trace from previous location ---
            at NuGet.DependencyResolver.ResolverUtility.FindLibraryFromSourcesAsync(LibraryRange libraryRange, IEnumerable`1 providers, Func`2 action)
            at NuGet.DependencyResolver.ResolverUtility.FindLibraryByVersionAsync(LibraryRange libraryRange, NuGetFramework framework, IEnumerable`1 providers, SourceCacheContext cacheContext, ILogger logger, CancellationToken token)
            at NuGet.DependencyResolver.ResolverUtility.FindPackageLibraryMatchAsync(LibraryRange libraryRange, NuGetFramework framework, IEnumerable`1 remoteProviders, IEnumerable`1 localProviders, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.FindLibraryMatchAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, IEnumerable`1 remoteProviders, IEnumerable`1 localProviders, IEnumerable`1 projectProviders, IDictionary`2 lockFileLibraries, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.FindLibraryEntryAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, RemoteWalkContext context, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge, TransitiveCentralPackageVersions transitiveCentralPackageVersions)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge, TransitiveCentralPackageVersions transitiveCentralPackageVersions)
            at NuGet.DependencyResolver.RemoteDependencyWalker.WalkAsync(LibraryRange library, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, Boolean recursive)
            at NuGet.Commands.ProjectRestoreCommand.WalkDependenciesAsync(LibraryRange projectRange, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, RemoteDependencyWalker walker, RemoteWalkContext context, CancellationToken token)
            at NuGet.Commands.ProjectRestoreCommand.TryRestoreAsync(LibraryRange projectRange, IEnumerable`1 frameworkRuntimePairs, NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteDependencyWalker remoteWalker, RemoteWalkContext context, Boolean forceRuntimeGraphCreation, CancellationToken token, TelemetryActivity telemetryActivity, String telemetryPrefix)
            at NuGet.Commands.RestoreCommand.ExecuteRestoreAsync(NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteWalkContext context, CancellationToken token, TelemetryActivity telemetryActivity)
            at NuGet.Commands.RestoreCommand.ExecuteAsync(CancellationToken token)
            at NuGet.Commands.RestoreRunner.ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
            at NuGet.Commands.RestoreRunner.ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
            at NuGet.Commands.RestoreRunner.CompleteTaskAsync(List`1 restoreTasks)
            at NuGet.Commands.RestoreRunner.RunAsync(IEnumerable`1 restoreRequests, RestoreArgs restoreContext, CancellationToken token)
            at NuGet.Commands.RestoreRunner.RunAsync(RestoreArgs restoreContext, CancellationToken token)
            at NuGet.Build.Tasks.BuildTasksUtility.RestoreAsync(DependencyGraphSpec dependencyGraphSpec, Boolean interactive, Boolean recursive, Boolean noCache, Boolean ignoreFailedSources, Boolean disableParallel, Boolean force, Boolean forceEvaluate, Boolean hideWarningsAndErrors, Boolean restorePC, Boolean cleanupAssetsForUnsupportedProjects, ILogger log, CancellationToken cancellationToken)
            at NuGet.Build.Tasks.RestoreTask.ExecuteAsync(ILogger log)
       Done executing task "RestoreTask" -- FAILED.
     1>Done building target "Restore" in project "restore.csproj" -- FAILED.
     1>Done Building Project "C:\Users\DevOps-AzAgent$\AppData\Local\Temp\qn20vf2i.kp0\restore.csproj" (Restore target(s)) -- FAILED.

What am I missing?
UPDATE 1:
Using the task NuGet to restore packages works and does not need task NuGet authenticate to execute prior. Still, the problem is, I have to use the command dotnet.exe tool restore to restore some dotnet tools. It seems, that dotnet.exe needs some further help to authenticate properly against our nuget server hosted by Azure DevOps Server.
UPDATE 2:
nuget.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>

    <add key="enabled" value="True" />

    <add key="automatic" value="False" />
  </packageRestore>

  <solution>

    <add key="disableSourceControlIntegration" value="true" />
  </solution>

  <packageSources>
    <add key="XXXFeed" value="http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

UPDATE 3:
For debugging purposes, I added another task into my pipeline, which runs the Azure Credential Provider in standalone mode:
"C:\Users\DevOps-AzAgent$\.nuget\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe" -I -V Verbose -U "http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json"
Result:
[Verbose] [CredentialProvider]Running in stand-alone mode
[Verbose] [CredentialProvider]Command-line v1.0.0+94af8126cf520805dd7e213b92cdecd9d8728d1f: "C:\Users\DevOps-AzAgent$\.nuget\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe"  -I -V Verbose -U "http://tfs.rzlsoftware.at:8080/tfs/RZL/_packaging/RZLFeed/nuget/v3/index.json"
[Verbose] [CredentialProvider]Handling auth request, Uri: http://tfs.rzlsoftware.at:8080/tfs/RZL/_packaging/RZLFeed/nuget/v3/index.json, IsRetry: True, IsNonInteractive: False, CanShowDialog: False
[Verbose] [CredentialProvider]URI: http://tfs.rzlsoftware.at:8080/tfs/RZL/_packaging/RZLFeed/nuget/v3/index.json
[Verbose] [CredentialProvider]VstsBuildTaskServiceEndpointCredentialProvider - This credential provider must be run under the Team Build tasks for NuGet with external endpoint credentials. Appropriate environment variable needs to be set.
[Verbose] [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for http://tfs.rzlsoftware.at:8080/tfs/RZL/_packaging/RZLFeed/nuget/v3/index.json
[Verbose] [CredentialProvider]Using NuGetCredentialProvider.CredentialProviders.VstsBuildTask.VstsBuildTaskCredentialProvider to try to get credentials for http://tfs.rzlsoftware.at:8080/tfs/RZL/_packaging/RZLFeed/nuget/v3/index.json.
[Verbose] [CredentialProvider]VstsBuildTaskCredentialProvider - IsRetry: True
[Verbose] [CredentialProvider]VstsBuildTaskCredentialProvider - URI Prefixes:
[Verbose] [CredentialProvider]VstsBuildTaskCredentialProvider - http://tfs.rzlsoftware.at:8080/tfs/RZL/
[Verbose] [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: http://tfs.rzlsoftware.at:8080/tfs/RZL/
[Verbose] [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint http://tfs.rzlsoftware.at:8080/tfs/RZL/_packaging/RZLFeed/nuget/v3/index.json
[Information] [CredentialProvider]Username: VssSessionToken
[Information] [CredentialProvider]Password: ***

That seems to work?
Answer: Since you have granted your Build Service with Contributor permissions to the feed, then there should be sufficient permissions for the Build service to retore it. And it is not needed to add "NuGet authenticate" task.
I have tested and got work when restoring with my DefaultCollection Build service "Contributor" role, and not adding the  "NuGet authenticate" task.
(1).Test with "Contributor" role granted.

(2).Restore successfully.

And the prerequisite is that you should check and confirm whether the specified nuget feed is correct located in your Artifact.
For your updates:
If you mean you want to get the resource from the "nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" ?
You can manually add a "packages.config" file in your Repo and then edit the "packages.config" file with the specified resource URL like below:
<?xml version="1.0" encoding="utf-8"?>

<packages>

<package id="wso" version="1.0.0" targetFramework="net46" />

<package id="NLog" version="4.3.10" targetFramework="net46" />

<package id="jQuery" version="3.1.1" targetFramework="net46" />

</packages>

Then just run the restore task with Path specified:
Comment: You are right. When using the task `NuGet` to restore packages, it a) works and b) task `NuGet authenticate` is not required. **But**, I have to use the command `dotnet.exe tool restore` to restore some dotnet tools. It seems, that `dotnet.exe` needs some help to authenticate properly.
Comment: @roli09 Does your dotnet.exe tool is contained in the nuget.config file? And what is your dotnet.exe tool?
Comment: The feed hosting my dotnet tool is in my `nuget.config`. I added my `nuget.config` to my original post as **Update 2**.
Comment: @roli09 Hi, I have updated and edited my answer, you could check and test to see if it works.
Comment: No, as you can see in my logs, the feed I have problems with is `http://tfs.XXXsoftware.at:8080/tfs/XXX/_packaging/XXXFeed/nuget/v3/index.json`. I don't think any `packages.config` would help, because the logs suggest, that everything is picked up correctly. As mentioned earlier, if I use the *Azure Artifacts Credential Provider* in standalone-mode, looking at the logs, it seems to work.
Comment: I also already downloaded the source code of the *Azure Artifacts Credential Provider* and tried to create a version with some more output to narrow my issue down. Unfortunately, *dotnet* refuses to use my modified version of the credential provider, because it has no embedded signature.


Can Webrtc datachannel be used for file transfer between a Lync and non-lync user?

Question: Imagining if the signalling and presence information are handled,
how, is it possible to use Webrtc datachannel as the underlying file transfer protocol instead of lync's own File transfer protocol (TFTP) to transfer file from a lync client(web app) to a non-lync client (web app with webrtc enabled)?
Answer: Lync provides Client interoperable programs. In that way it can be easily attached to any web application for presence information.
<code>Client interoperability example:
    Application:  http://lyncpresence.orbitone.com/
    Source: http://lyncwidget.codeplex.com/

Unified Program (includes interoperability of Lync server with all networks):
    http://technet.microsoft.com/en-us/library/gg398996.aspx
    http://technet.microsoft.com/en-in/office/ocs/bb735838.aspx
    http://technet.microsoft.com/en-us/lync/gg131938.aspx
</code>


Flutter & Firebase: Compression before upload image

Question: I want to send photo selected by user in my app to Firebase Storage. I have a simple class with property _imageFile which is set like this:
File _imageFile;

_getImage() async {
    var fileName = await ImagePicker.pickImage();
    setState(() {
        _imageFile = fileName;
    });
}

after that I send photo like with this code:
final String rand1 = "${new Random().nextInt(10000)}";
final String rand2 = "${new Random().nextInt(10000)}";
final String rand3 = "${new Random().nextInt(10000)}";
final StorageReference ref = FirebaseStorage.instance.ref().child('${rand1}_${rand2}_${rand3}.jpg');
final StorageUploadTask uploadTask = ref.put(_imageFile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
print(downloadUrl);

The problem is that the photos are often very large. Is there any method in Flutter/Dart to compress and resize photo before upload? I am ok with loss of quality.
Comment: You might want to give https://pub.dartlang.org/packages/image a try, I have not tried this, but when you read the documentation you will find that you can encode images into different formats and specify different compression levels.
Comment: You might want to check https://pub.dev/packages/uuid for uploading files on firebase because using random numbers may have collisions at some time.
Comment: If you are in for lutter web check out my answer. https://stackoverflow.com/questions/60728872/flutter-web-how-do-you-compress-an-image-file/68358346#68358346
Answer: June 05, 2020 - Update
The image_picker plugin now supports an imageQuality paramater. You can do something like
ImagePicker imagePicker = ImagePicker();
PickedFile compressedImage = await imagePicker.getImage(
  source: ImageSource.camera,
  imageQuality: 85,
);

Old Answer
or if you want to compress an image without using ImagePicker
I ran into this and was able to accomplish compression / resizing with the Dart image package along with path provider. You can look at dart image api and examples for other ways and more help.
Here's what I did:
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart';
import 'dart:math' as Math;

void compressImage() async {
  File imageFile = await ImagePicker.pickImage();
  final tempDir = await getTemporaryDirectory();
  final path = tempDir.path;
  int rand = new Math.Random().nextInt(10000);

  Im.Image image = Im.decodeImage(imageFile.readAsBytesSync());
  Im.Image smallerImage = Im.copyResize(image, 500); // choose the size here, it will maintain aspect ratio

  var compressedImage = new File('$path/img_$rand.jpg')..writeAsBytesSync(Im.encodeJpg(image, quality: 85));
}

Then I uploaded compressedImage to firebase storage. You can adjust the quality that the jpg is saved with using the quality property, in my case I chose 85 (out of 100).
Hope this helps! Let me know if you have any questions.
Comment: yes it's quite long and I cannot undersand why it freeze my UI even though the code is async
Comment: i have found that it does freeze my ui for a while in debug, it runs much better when the app is built for release
Comment: @Mans What is average image file size reduction?
Comment: I Am Also doing the same stuff but it takes long time in iOS (if the image is take from it)
Comment: @gbaccetta being async doesn't mean its parallel
Comment: @gbaccetta it also doesn't mean multi threading, it all depends on the developers on how they implement their async functionality
Comment: @gbaccetta dart is single threaded. So it all runs on the UI thread. To achieve true multi threading, use an isolate.
Comment: Why is the smallerImage not used?
Comment: but image picker doesn't support png compression what to do  in that case
Comment: @mans my question is do I need to ask for permission in android for this code(like storage permission or something)
Answer: The image_picker plugin is currently very simple. It would be straightforward to add an option for specifying the desired size/quality of the picked image. If you do this, please send us a pull request!
Comment: SYNTAX: ImagePicker.pickImage(source.ImageSource.gallery, imageQuality: 85); But this will compress the image by 85% of its current quality, so if an image is already of less quality then it will just mess it up even more!

ALTERNATE SOLUTION: ImagePicker.pickImage(source.ImageSource.gallery, maxHeight: 200); Using maxHeight will only compress the image if it greater than mentioned height!
Comment: What parameter to pass in the image picker library? Can you provide the link for it
Comment: use  an imageQuality parameter  in the image picker library.
Comment: Is there any solution for the web?
Comment: I did not find any params to resize all images above X and Y, did you found it? Thanks
Answer: There are many solutions :
Use image_picker package:
You can use the built-in imageQuality property of ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the quality of the original image.
First, add image_picker as a dependency in your pubspec.yaml file.
Usage
  File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(
        source: ImageSource.gallery,
                imageQuality: 25,
    );

    setState(() {
      _image = image;
    });
  }

The advantage of this approach is that it is embedded in the
image_picker package and is therefore incredibly easy to use.

You can also adjust the quality from the Image widget.
Use filterQuality  to set the FilterQuality of the image.
Example :
Image.asset('assets/kab1.png', filterQuality: FilterQuality.high,),

These properties are present in AssetImage , NetworkImage , FileImage and MemoryImage.

You can also simply resize the image (Resizing an image can compress it). To do so, try the ResizeImage widget
Another solution is to use flutter_image_compress package
Answer: Use image_picker plugin and call pick image function as
Future<File> imageFile = ImagePicker.pickImage(source: ImageSource.gallery  , maxHeight:  200 , maxWidth: 200 );
change maxHeight and maxWidth to whatever size of image you need.
Comment: This worked for me! I used 400 instead of 200 to get a better quality. Generally, a 200x200 is less than 20kb, and the 400x400 is less than 40kb
Comment: 2020 : 'pickImage' is deprecated and shouldn't be used. Use imagePicker.getImage() method instead..
Comment: Great, this is something I needed. i don't want to use another library for compress.
Answer: Besides mentioning this native library:
https://pub.dartlang.org/packages/flutter_image_compress
This is a fully dart based compressor with isolates, which might make the compression parallel to UI thread in multi core CPUs.

You might want to use compute function which makes using isolates simpler:
  https://docs.flutter.io/flutter/foundation/compute.html
https://flutter.io/cookbook/networking/background-parsing/

import 'package:image/image.dart' as ImageLib;
import 'package:path_provider/path_provider.dart';

Future<void> getCompressedImage(SendPort sendPort) async {
  ReceivePort receivePort = ReceivePort();

  sendPort.send(receivePort.sendPort);
  List msg = (await receivePort.first) as List;

  String srcPath = msg[0];
  String name = msg[1];
  String destDirPath = msg[2];
  SendPort replyPort = msg[3];

  ImageLib.Image image =
      ImageLib.decodeImage(await new File(srcPath).readAsBytes());

  if (image.width > 500 || image.height > 500) {
    image = ImageLib.copyResize(image, 500);
  }

  File destFile = new File(destDirPath + '/' + name);
  await destFile.writeAsBytes(ImageLib.encodeJpg(image, quality: 60));

  replyPort.send(destFile.path);
}

Future<File> compressImage(File f) async {
  ReceivePort receivePort = ReceivePort();

  await Isolate.spawn(getCompressedImage, receivePort.sendPort);
  SendPort sendPort = await receivePort.first;

  ReceivePort receivePort2 = ReceivePort();

  sendPort.send([
    f.path,
    f.uri.pathSegments.last,
    (await getTemporaryDirectory()).path,
    receivePort2.sendPort,
  ]);

  var msg = await receivePort2.first;

  return new File(msg);
}

if (false ==
    await SimplePermissions.checkPermission(
        Permission.ReadExternalStorage)) {
  await SimplePermissions.requestPermission(
    Permission.ReadExternalStorage);
}

File img = await ImagePicker.pickImage(
    source: ImageSource.gallery);
if (null != img) {
  img = await compressImage(img);
}

Comment: Hangs up sometimes :( Without exception
Comment: Forgot to `import 'dart:isolate';`
Answer: The following code is what I use to take an image with the camera and then compress it:
import 'dart:async' show Future;
import 'dart:io' show File;
import 'package:flutter/foundation.dart' show compute;
import 'package:flutter/material.dart' show BuildContext;
import 'package:image/image.dart' as Im;
import 'dart:math' as Math;
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;

Future<File> takeCompressedPicture(BuildContext context) async {
  var _imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
  if (_imageFile == null) {
    return null;
  }

  // You can have a loading dialog here but don't forget to pop before return file;

  final tempDir = await getTemporaryDirectory();
  final rand = Math.Random().nextInt(10000);
  _CompressObject compressObject =
      _CompressObject(_imageFile, tempDir.path, rand);
  String filePath = await _compressImage(compressObject);
  print('new path: ' + filePath);
  File file = File(filePath);

  // Pop loading

  return file;
}

Future<String> _compressImage(_CompressObject object) async {
  return compute(_decodeImage, object);
}

String _decodeImage(_CompressObject object) {
  Im.Image image = Im.decodeImage(object.imageFile.readAsBytesSync());
  Im.Image smallerImage = Im.copyResize(
      image, 1024); // choose the size here, it will maintain aspect ratio
  var decodedImageFile = File(object.path + '/img_${object.rand}.jpg');
  decodedImageFile.writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 85));
  return decodedImageFile.path;
}

class _CompressObject {
  File imageFile;
  String path;
  int rand;

  _CompressObject(this.imageFile, this.path, this.rand);
}

You can call this very easy with this:
import 'path/to/compress_image.dart' as CompressImage;
// ...
File file = await CompressImage.takeCompressedPicture(context);

Comment: gives this error for   `return compute(_decodeImage, object);` like this 'Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function '_decodeImage@38216194':.)'
Answer: While i am using

package:image/image.dart

facing below issues

showing blank page while converting image ( may be taking so much process while compressing image)
After compression image was stretched and not looking good

Then used below plugin, same working fine without any issue, even faster and what i expected
https://github.com/btastic/flutter_native_image.git

steps and method available in above link.
Answer: You can use a plugin called flutter_image_compress
// Active image file
File _imageFile;

// Select an image via gallery or camera
Future<void> _pickImage(ImageSource source) async {
  File selected = await ImagePicker.pickImage(source: source);

// Compress plugin
  File compressedImage = await FlutterImageCompress.compressAndGetFile(
    selected.path,
    selected.path,
    quality: 50,
  );

  setState(() {
    _imageFile = compressedImage;
    print('compressedimagesize: ${_imageFile.lengthSync()}');
  });
}

Voila! Compressed file image
Comment: its going to say that the target path cannot be the same as the file path.
Answer: Since you are using Firebase, one option would be using the Extension - Resize Image. It gives you the option to keep or delete the original image and it is very easy to install and use.
Comment: From Review: This post does not seem to provide a [quality answer](https://stackoverflow.com/help/how-to-answer) to the question. Please either edit your answer, or just post it as a comment to the question.
Answer: You can do as follows,
//Compressing Image
    File compressedImg = await FlutterNativeImage.compressImage(
      _image.path,
      quality: 70,
    );
//Compressing Image

Answer: Well
1. If you are in mobile you could use flutter_image_compress: ^1.0.0  will do the work
Eg.
Pass youe Uint8List and quality, you will get compressed image in no time.
Future<Uint8List> testComporessList(Uint8List uint8List) async {
    var result = await FlutterImageCompress.compressWithList(
      uint8List,
      quality: 50,
    );
    return result;
}

2. But If you are in flutter web then you won't get any other option than image picker etc etc.
I end up using javascript. You can find answer here.
Flutter Web: How Do You Compress an Image/File?
Answer: ImagePicker has now a default option to reduce imageQuality.
 final returnedImage = await ImagePicker()
    .pickImage(source: ImageSource.gallery, imageQuality: 50);

Here

imageQuality: 50

means that the image will be reduced to 50% of it's actual quality.
Answer: Update 2020 'pickImage' is deprecated and shouldn't be used. Use imagePicker.getImage() method instead**
  ImagePicker picker = ImagePicker();
   PickedFile compressedImage = await imagePicker.getImage(
  source: ImageSource.camera,
  imageQuality: 80,
);

Doc for ImageQuality :

Returns a PickedFile object wrapping the image that was picked. The
returned PickedFile is intended to be used within a single APP
session. Do not save the file path and use it across sessions. The
source argument controls where the image comes from. This can be
either ImageSource.camera or ImageSource.gallery. Where iOS supports
HEIC images, Android 8 and below doesn't. Android 9 and above only
support HEIC images if used in addition to a size modification, of
which the usage is explained below. If specified, the image will be at
most maxWidth wide and maxHeight tall. Otherwise the image will be
returned at it's original width and height. The imageQuality argument
modifies the quality of the image, ranging from 0-100 where 100 is the
original/max quality. If imageQuality is null, the image with the
original quality will be returned. Compression is only supported for
certain image types such as JPEG and on Android PNG and WebP, too. If
compression is not supported for the image that is picked, a warning
message will be logged. Use preferredCameraDevice to specify the
camera to use when the source is ImageSource.camera. The
preferredCameraDevice is ignored when source is ImageSource.gallery.
It is also ignored if the chosen camera is not supported on the
device. Defaults to CameraDevice.rear. Note that Android has no
documented parameter for an intent to specify if the front or rear
camera should be opened, this function is not guaranteed to work on an
Android device. In Android, the MainActivity can be destroyed for
various reasons. If that happens, the result will be lost in this
call. You can then call getLostData when your app relaunches to
retrieve the lost data.


Typescript map.get return undefined

Question: When I want get Object by key I have undefined each all element.
My Map :
nodesMaps : Map<number, Object> = [
{ key: "1", value: Object },
{ key: "2", value: Object },
{ key: "3", value: Object },
]

When I want get value of this map :
this.nodesMaps.get(1) // return undefined
this.nodesMaps.get("1") // return undefined

Comment: `undefined` is a runtime value or a *type* hinted by typescript?
Comment: In my case, had to cast search key in get to number, using +
Answer: below code for me..
let map = new Map([
    [ "A", "AA" ],
    [ "B", "BB" ],
    [ "C", "CC" ]
]);

console.log(map.get("A"));

check this: https://jsfiddle.net/vipinmpd08/1b68eLdr/91920/
Comment: let map = new Map();
Comment: And If I want fill my map with value. How I can initialize an empty map ?
Comment: Wow ! Why we can't instantiate map with key / value ?
Comment: check same fiddle..i updated with three examples..is it something u r looking for ?
Answer: You've messed many things.

Even if you declared type Map, you assigned an Array value.
The array was array of objects, not array of arrays with length 2.
etc.

Valid map creation should look like this:

let nodesMap = new Map([
    [1, 'foo'],
    [2, 'bar'],
    [3, 'baz'],
])

 console.log(nodesMap.get(1)) // foo
Comment: "And If I want fill my map with value.": `nodesMap.set(4, 'qwe')` "How I can initialize an empty map": Just like this: `new Map()`
Comment: And If I want fill my map with value. How I can initialize an empty map ?
Answer: You can't assign properties on top of the fact they aren't objects, they are arrays, and you need to use new.  Your code should look like:
// TypeScript
nodesMaps : Map<number, Object> = new Map([
  [ 1, Object ],
  [ 2, Object ],
  [ 3, Object ],
]);

Map Reference

var nodesMaps = new Map([
  [ 1, "Object 1" ],
  [ 2, "Object 2" ],
  [ 3, "Object 3" ],
]);

$('button').on('click', function() {
  var key = $(this).data('key');
  console.log("key :" + key);
  console.log("value: " + nodesMaps.get(key));
});

<button data-key="1">1</button>
<button data-key="2">2</button>
<button data-key="3">3</button>

Typescript map.get return undefined


Comparing two files using commons or Javascript

Question: I need to check if any of the 4 uploaded files are same, this check might be on the JSP or Java-Servlet side.
I've been using
var FileName1 = document.getElementById('fileChooser1').value;
var FileName2 = document.getElementById('fileChooser2').value;
if(FileName1 == FileName2)
{
 alert("same files cannot be uploaded");
}

But, the problem is that this only deals with the name of the file and this fails if files with same content but different names are uploaded.
So, on apache commons search I found that there is a Default Comparator but I have no idea of how I can use this or is there any other better/simpler way to check for same files.

How can I use the Default Comparator and on what basis does it compare?
Is there any better/simpler solution to this problem in java or javascript?
Comment: Looks like you want to compare files in Javascript while Apache commons will give Java based solution
Comment: It may be either a javascript or java solution, I just want to compare two files and identify duplicate uploads.
Answer: You can use FileUtils.contentEquals method to compare content of 2 files.
Example
System.out.println(FileUtils.contentEquals(file1, file2));

Comment: i think you should go with this solution .


Understanding select from channels with and without goroutine

Question: Hello stackoverflow community,
I am using github.com/fsnotify/fsnotify to set watchers to a file in Go. My function looks like
func SetWatcher(filename string) {
    fmt.Println("Setting watcher to file ", filename)
    Watcher, err = fsnotify.NewWatcher()
    if err != nil {
        fmt.Println("inotify errored. Other methods needs to be implemented.")
        panic(err)
    }
    if err != nil {
        log.Fatal(err)
    }

    done := make(chan bool)
    go func() {
        for {
            select {
            case event := <-Watcher.Events:
                if event.Op == fsnotify.Remove {
                    fmt.Println("File removed, needs to kill the process.")
                } else if event.Op == fsnotify.Rename {
                    fmt.Println("File renamed, need to restart seeking.")
                }

            case err := <-Watcher.Errors:
                log.Println("error:", err)
            }
        }
    }()

    err = Watcher.Add(filename)
    if err != nil {
        log.Fatal(err)
    }
    <-done
}

which works so far and I get outputs as
Setting watcher to file  /var/log/syslog
File renamed, need to restart seeking.

However, if I try to remove the closure running in the goroutine and run it as
func SetWatcher(filename string) {
    fmt.Println("Setting watcher to file ", filename)
    Watcher, err = fsnotify.NewWatcher()
    if err != nil {
        fmt.Println("inotify errored. Other methods needs to be implemented.")
        panic(err)
    }
    if err != nil {
        log.Fatal(err)
    }
    //defer Watcher.Close()

    //done := make(chan bool)
    //go func() {
    //  for {
            select {
            case event := <-Watcher.Events:
                if event.Op == fsnotify.Remove {
                    fmt.Println("File removed, needs to kill the process.")
                } else if event.Op == fsnotify.Rename {
                    fmt.Println("File renamed, need to restart seeking.")
                }

            case err := <-Watcher.Errors:
                log.Println("error:", err)
            }
        //}
    //}()

    err = Watcher.Add(filename)
    if err != nil {
        log.Fatal(err)
    }
    //<-done
}

the program never outputs anything. I ran it with strace and the program is seen stuck at
[pid  5773] pselect6(0, NULL, NULL, NULL, {tv_sec=0, tv_nsec=20000}, NULL <unfinished ...>
[pid  5772] epoll_wait(4, [], 128, 0)   = 0
[pid  5772] futex(0x598bf8, FUTEX_WAIT, 0, NULL <unfinished ...>
[pid  5773] <... pselect6 resumed> )    = 0 (Timeout)
[pid  5740] <... pselect6 resumed> )    = 0 (Timeout)
[pid  5773] futex(0x598578, FUTEX_WAIT, 0, {tv_sec=60, tv_nsec=0}
<unfinished ...>
[pid  5740] futex(0xae1f58, FUTEX_WAIT, 0, {tv_sec=60, tv_nsec=0}

and not receiving from the channel and keeps on waiting.
I've read that this could be caused because of non-buffered channel. So to validate that, I modified the library to use a buffered channel and the part of the function that generates the new watcher looks like
    w := &Watcher{
    fd:       fd,
    poller:   poller,
    watches:  make(map[string]*watch),
    paths:    make(map[int]string),
    Events:   make(chan Event, 10), // Made it buffered here
    Errors:   make(chan error),
    done:     make(chan struct{}),
    doneResp: make(chan struct{}),
}

But the behavior is the same. Can someone please help me understand why the reading from channel worked when it was in a goroutine, and didn't work without a goroutine?
Thank you.
Answer: I am not familiar with fsnotify, but it looks like it won't send anything on the channels until Watcher.Add() is called to watch the file, but the Watcher.Add() occurs after the select in the second version. In this case select will block for ever as nothing can be signaled as Watcher.Add() has not been called. Hence there is deadlock.


Reclaiming Space That 'df' Says Should Be Available

Question: I have a linux server hosted on one of Rackspace's CloudServers and it is showing that I have both no room available, yet also shows I have 12GB not used on the root partition.  This server's only job is to rsync over files nightly from another server via rsync and keep an emergency backup of those files.
I found a directory that had some backup files that weren't needed so deleted those and that is what gave me the 12GB unused.  Deleting files shrinks the "Used" space, but doesn't give anything to the "Avail" space.
lsof doesn't show that it is holding on to anything and df -i says I have plenty of free inodes.
I've also rebooted this server multiple times and the problem persists.  I've even rebooted in to rescue mode and ran an fsck on the device and didn't see any glaring errors:
root@RESCUE-nightly-snapshot:~# fsck /dev/xvdb1
fsck from util-linux 2.20.1
e2fsck 1.42 (29-Nov-2011)
/dev/xvdb1: recovering journal
Setting free inodes count to 20630768 (was 20630766)
Setting free blocks count to 2845985 (was 2755815)
/dev/xvdb1: clean, 340752/20971520 files, 81040087/83886072 blocks
root@RESCUE-nightly-snapshot:~#

So I'm kind of stuck because normal users can't create any new files and the syslog user can't append to any log files.
Lastly, the filesystem is ext3 and something in my brain is saying maybe there is something weird with the journal.  I don't know if this space could be taken up by the journal or how to even tell.
I'd appreciate any tips on how to regain this space that should've been freed.
root@nightly-snapshot:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1      315G  303G     0 100% /
udev            3.9G  4.0K  3.9G   1% /dev
tmpfs           1.6G  244K  1.6G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            3.9G     0  3.9G   0% /run/shm
overflow        1.0M     0  1.0M   0% /tmp
/dev/md0        5.0T  4.2T  593G  88% /mnt/raid
root@nightly-snapshot:~# df -i
Filesystem        Inodes    IUsed     IFree IUse% Mounted on
/dev/xvda1      20971520   340750  20630770    2% /
udev             1016188      422   1015766    1% /dev
tmpfs            1018170      319   1017851    1% /run
none             1018170        3   1018167    1% /run/lock
none             1018170        1   1018169    1% /run/shm
overflow         1018170        1   1018169    1% /tmp
/dev/md0       167772160 12607068 155165092    8% /mnt/raid
root@nightly-snapshot:~#
root@nightly-snapshot:~# lsof | grep -i deleted
root@nightly-snapshot:~#

Answer: There is a chance that this space is reserved for root user. Please check out how much space is reserved for root,with:
tune2fs -l /dev/xvda1
This will give you the block count reserved for root user, multiply it by the block size and you will get the size of reserved space (in bytes).
You can modify the reserved space with: tune2fs -m 1 /dev/xvda1 The number after -m is the percent of disk space which should be reserved. In this example it is 1%.
Comment: It appears that this was it.  Getting the reserved space in bytes showed that it was set to get 17GB (or 5%) and in the above measurement showed that I had only freed up 12GB.  I found a couple of multi-gigabyte files that I could remove and soon the the size in Avail started to increase.  My assumption is that a process running as root filled up the drive as well as the reserved space.


Regex for end of string

Question: I can't find the magic formula to get my regex working in Javascript.
let's say I have:
const branchnames = [
    { name:'WICO-29', key:1 },
    { name:'WICO-9', key:2 },
    { name:'wico-2', key:3 },
    { name:'wiCo-2: description', key:4 },
    { name:'WiCO-2 example ', key:5 },
    { name:'WiCO-2-dosomething', key:6 },
    { name:'wiCO-2, great', key:7 },
];

I would like to recover every names excepts for the first two. Hence I am looking for a regex looking for "wico-2" (not case sensitive), followed either by nothing or a non alphanumerical character. Following attempts didn't work...
const reg = new RegExp(/wico-2[ ,:-]?$/, "i"); // miss: 4,5,6,7
const reg = new RegExp(/wico-2\W/, "i"); // miss: 3
const reg = new RegExp(/wico-2\W?/, "i"); // wrong:1
const reg = new RegExp(/wico-2\W?$/, "i"); // only 3

branchnames.forEach( element => {
    console.log ( element.name.match(reg));
});

any help ? thanks !
Comment: wait a sec.... Wico or Jico ? :D
Comment: @Mohammad why would you? key != name
Comment: please add the wanted result of the regex.
Comment: Why you don't use `if (key > 2)`?
Comment: @RokoC.Buljan Because *I would like to recover every names excepts for the first two*.
Comment: @Mohammad I'm not sure a key `value` in programming or in his example might be a UUID... but yeah
Comment: @Mohammad ... Actually this "key" was just used for the example, as I thought it would ease the listing of missing / wrong results in my attempts ! Sorry if it did confuse you.
Answer: I would use /wico-2(?:\D+|$)/ to do this:

const branchnames = [
    { name:'WICO-29', key:1 },
    { name:'WICO-9', key:2 },
    { name:'wico-2', key:3 },
    { name:'wiCo-2: description', key:4 },
    { name:'WiCO-2 example ', key:5 },
    { name:'WiCO-2-dosomething', key:6 },
    { name:'wiCO-2, great', key:7 },
];

const reg = new RegExp(/wico-2(?:\D+|$)/, "i");

branchnames.forEach( element => {
    console.log ( element.name.match(reg));
});

Explanation of (?:\D+|$):

Non-capturing group (?:\D+|$)

1st Alternative \D+ : matches any character that's not a digit (equal to [^0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Alternative $: asserts position at the end of the string
Comment: @bertrand By the way, the `?:` only makes the parentheses not count as matching groups.  You could leave that out to make the regular expression easier to read, possibly at the expense of speed.
Comment: Thank you. Actually, in this case speed is clearly not an issue, and I am in favor of something easy to read / understand ... actually before the answers from the community, I was doing :
Comment: const regexp1 = currentTaskKey + '\\W'; const reg1 = new RegExp(regexp1, 'i');

   const regexp2 = currentTaskKey + '$'; // task key not followed by anything
   const reg2 = new RegExp(regexp2, 'i');

   return element.name.match(reg1) || element.name.match(reg2);
Comment: const regexp1 = currentTaskKey + '\\W';
const reg1 = new RegExp(regexp1, 'i');

const regexp2 = currentTaskKey + '$';
const reg2 = new RegExp(regexp2, 'i');

return element.name.match(reg1) || element.name.match(reg2);
Comment: (sorry for the mess... comments cannot be formatted...)
Answer: You can use regex as /wico-2(?!\d)/gi

const branchnames = [
    { name:'WICO-29', key:1 },
    { name:'WICO-9', key:2 },
    { name:'wico-2', key:3 },
    { name:'wiCo-2: description', key:4 },
    { name:'WiCO-2 example ', key:5 },
    { name:'WiCO-2-dosomething', key:6 },
    { name:'wiCO-2, great', key:7 },
];
const reg = new RegExp(/wico-2(?!\d)/, "gi");

branchnames.forEach( element => {
  if(element.name.match(reg)){
     console.log (element);
  }
});
Comment: Your example will select also `fico-3: wico-26`
Answer: One might do as follows;

var branchnames = [
    { name:'WICO-29', key:1 },
    { name:'WICO-9', key:2 },
    { name:'wico-2hello', key:3 },
    { name:'wico-2', key:3 },
    { name:'wiCo-2: description', key:4 },
    { name:'WiCO-2 example ', key:5 },
    { name:'WiCO-2-dosomething', key:6 },
    { name:'wiCO-2, great', key:7 },
];
branchnames.forEach(bn => /wico-2(?=[^\dA-Za-z]|$)/i.test(bn.name) && console.log(bn.name));
Comment: like `WiCO-2-dosomething`? @RokoC.Buljan
Answer: You could do this:
/wico-2(([ ,:-]+|$).*$)/

Here is a link to regex tester:Regex
Comment: "Don't" use spaces in regex

Regex for end of string