What does rebuilding content access permissions do?

Question: Since installing the node access module I see the following message randomly.

Content access permissions need to be rebuilt.

Will rebuilding them remove all the node access permissions already set? What does "rebuilding" do? Why do I get this message?
Answer: There's a quote in the comments on this post that puts it nicely:

Drupal maintains a table of who can access what; this needs to be rebuilt when a new module affecting user access is enabled.

Think of it as a cache-clear for node access data, except that it's quite complicated so needs to be run as a batch job rather than all at once (e.g. on a cron run).
Since node access is a sensitive issue it's also not wise to rely on scheduled jobs to make the necessary changes, hence why this is all done in one go.
Comment: Is it as harmless as clearing caches, or should I always do a backup beforehand? 'Cuz, let's be real. I don't do backups before clearing caches. :) Thanks for the clarification.
Comment: This is all correct as you seem to mean "batch job" informally, as synonym to "cron job" and "all in one go". In the code, there is something called "batch mode" for rebuilding permissions, and this is something else. It will distribute rebuilding over several batches, doing one per HTTP request to avoid timeouts. The permission rebuilding function can be run in this batch mode (usually done when run from a browser) and non-batch mode (usually done when run via cron).
Answer: I also was getting this error, after installing the Book Access module in Drupal 6.
It turns out I hadn't created any books yet, so that after I had clicked the check box to enable the new installed module, drupal was unable to find found any book permissions with which to initialise the new database table that Book Access uses.
I was able to get rid of the error by

disabling Book Access
creating a book page

no need for content, but do include at least a title
remember to select "new book" from the dropdown box in the "Book Outline" section of the "edit" tab

enabling Book Access again

Your situation may be similar.
Answer: I've been frustrated at times trying to find how to run this process manually on D8 / D9 - top Google results are useless. So, if you know you have a content access issue (content that should be viewable is being restricted, for example), then navigate to:
yoursite.com/admin/reports/status/rebuild
The reason is that a problem with content access permissions is shown as an item on your status report, and the rebuild command comes from there. But you can navigate directly to the above URL at any time if you need to kick off a rebuild. (Don't do it casually as it's a tedious operation - only if you know you have content that is incorrectly being hidden, or not hidden, especially by a custom module or a wacky contrib module like permissions_by_term.)


Unable to write formula with range method

Question: I am using xlwings v'0.10.2'. I am finding that the range method doesn't appear to write the formula, but only the computed value. The formula is retained from within the VBA but not when written from python. Tried using the python UDFs macro.
Say for cell A1, I am trying to accomplish the following:
xw.Range('A1').formula = SUM(1,3) -> want to retain this formula

Am i missing something?
Answer: You need to assign the formula as string:
xw.Range('A1').formula = '=SUM(1,3)'

Comment: Thank you, appreciate it! Is there also a way to assign a global variable in the formula? For e.g. say there is a variable some_var = 6, then how can we have something like xw.Range('A1').formula = some_var - 5 in a way that would compute this equation but write it as formula to cell A1?
Comment: I think I have this figured out, need to do more testing but this thread can be closed. Thanks!


Modular Multiplicative Inverses

Question: I'm in a cryptography and struggling with understanding how the Euclidean Algorithm necessarily works for finding multiplicative inverses. We haven't actually covered the algorithm yet, just a way to brute force finding the inverses but I like working with an algorithm instead of just guess and checking so I learned it myself. In the equation 1/5 mod 13 I understand that this is equivalent to 5x = 1 mod 13 however when going through the algorithm I get the answer to be -5 instead of 8 which it is supposed to be. Can anyone shed some light on where I'm going wrong? Here's my work.
(a) 1/5 mod 13
1/5 mod 13 ≡ 5-1 mod 13 ≡ 5x = 1 (mod 13)
13 = 2(5) + 3
5 = 1(3) + 2
3 = 1(2) + 1
GCD of 13 and 5 is 1.
1 = 3 – 2(1)
= 3 – (5 – 3(1)) = 3 - 5 + 3 = 2(3) - 5
= 2(13 - 2(5)) - 5
= 2(13) – 4(5) – 5
= 2(13) -5(5)
-> mod 13 on both sides
1 mod 13 = 0 – 5(5) mod 13
1 = -5(5) mod 13
x = -5
Comment: Welcome to MathSE.  Please read this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: There is no mistake. $-5$ and $8$ are just equal mod $13$. They are the same number.
Answer: Remember $a\equiv b \pmod n$ if $a-b$ or $b-a$ is a multiple of $n$.
You have $-5\equiv 8 \pmod {13}$ because $8-(-5) = {13}$ is a multiple of $13$.
Answer: You are right indeed by Euclidean algorithm we have

$13=5\cdot 2+\color{red}3$
$5=\color{red}3\cdot 1+\color{red}2$
$3=\color{red}2\cdot 1+1$

and therefore starting from the last one
$$1=3-2=3-(5-3)=2\cdot 13-2\cdot 5\cdot 2-5 \implies  2\cdot 13-5\cdot 5=1 $$$$\implies -5\cdot 5=1-2\cdot 13$$
and then
$$5x\equiv 1 \pmod {13} \implies x\equiv -5 \equiv 8 \pmod {13}$$

Modular Multiplicative Inverses


A limited composition of two unlimited functions on natural numbers?

Question: Can someone give an example of two functions $f,g:\Bbb N\to \Bbb N$ such that
$|\operatorname{Im}f|,|\operatorname{Im}\,g|\notin\Bbb N$, but such that
$|\operatorname{Im}\,g\circ f|\in\Bbb N$?
Answer: $$
f(n)=2n+1
$$
$$
g(n) = \begin{cases}
1 \quad \mbox{if $n$ is odd}; \\
n \quad \mbox{if $n$ is even}.
\end{cases}
$$
Comment: Yeah! :) Not my best!


Möbius tranformation taking reals to reals can be written with real coefficients

Question: I'm working on this one (from Ahlfors' Complex Analysis):
A Fractional Linear Transformation of form $\displaystyle T(z) = \frac{a z + b}{c z + d}$ which takes the real numbers into the real numbers can be written in a way where all the coefficients are real.
I'm pretty sure I know a way to get the answer.
First, the thing is a constant exactly when $ad - bc = 0$. Then you're done. If not, some coefficient is not zero. in that case, you can change variables and stuff around in a way so that you can assume WLOG $a \ne 0$.
Then, you pick three different real-valued inputs and show that all the three remaining coefficients $b, c, d$ are real-valued.
My question is:
Is there an easier way to do this, without using more advanced complex analysis (which I don't know yet)
Comment: Um...What do you mean by "More Advanced Complex Analysis"?
Comment: We've been introduced to the idea of an analytic function, talked a little about complex differentiability being the same as $\mathbb{R}^2$ differentiability plus Cauchy-Riemann stuff.
Comment: No integration theory, and no "power series uniqueness" stuff.
Comment: Hmm...With no other tools than arithmetic and differentiability, I'd say just beat the crap out of it like you said you can do. Do case-by-case and force it out. But, I'm an amateur, and you should still look for a better way. Maybe some of the real mathematicians here have better ideas.
Comment: Dude - You put some thought into your question, provided a possible solution (which isn't rock-hard, but whatever), and so your post is legit (IMHO). I don't know about people respond to the "homework" label.
Comment: It turns out this question is essentially answered under https://math.stackexchange.com/q/105859/139123, although the form of the question there was somewhat different.
Answer: It turns out that this is not an answer to the OP's question. I will leave this answer nevertheless, perhaps someone might find it useful for something. This was my fault for not reading the question more carefully
I will start the answer with an exercise. We will assume throughout that $a\neq 0$, and $ad-bc\neq 0$. Throughout, $L$ will denote a linear fractional transformation that sends extended reals to the extended reals, that satisfies the conditions above.
Exercise: Let $(z_1,z_2,z_3)$, and $(w_1,w_2,w_3)$ be two triples of extended complex numbers (the complex numbers with the point at infinity include). Then their is a unique linear fractional transformation, $L$ such that $L(z_i)=w_i,i=1,2,3.$
Now to take on the literal statement of the question, if a linear fractional transformation takes the reals to the reals, then it is a linear function (and takes infinity to infinity), but this is not so interesting. More interesting (the one I assume that you want to prove) is that a LFT that takes the extended reals to the extended reals (the reals with infinity included) mat be written to have all real coefficients. Since by your remark, that we may assume $a\neq 0$, multiply the numerator and denominator by $\frac{1}{a}$, so now without loss of generality, we may assume that $a=1$.
We will now invoke our exercise. If we say where we send $\{0,1,\infty\}$, we completely determine the LFT. Again, if we send infinity to infinity, we have a linear function. Let us assume that we send infinity to some real number. If $L(z)=\frac{z+b}{cz+d}$, then $L(\infty)=\frac{1}{c}$. If we assume that $L$ sends extended reals to extended reals, the, $\frac{1}{c}$ is real and therefore ,so is $c$. Likewise $L(0)=\frac{b}{d}$, which is also real if $d\neq 0$(we will also need to deal with the case when $d=0$.
Since our linear fractional transformation does not send infinity to infinity, the number, $-\frac{d}{c}$ is real, since $L(-\frac{d}{c})=\infty$. Since $c$ is real, so is $d$. Since $\frac{b}{d}$ is real, so is $b$, since $d$ is real. Now suppose that $d=0$. Then the LFT is of the form, $\frac{z+b}{cz}=\frac{1}{c}+\frac{b}{cz}$. We still know that $c$ is real, the previous argument for this did not require $d\neq 0$. Now pick $z=1$ and plug it into $\frac{1}{c}+\frac{b}{cz}$, which concludes this argument.
Comment: Let $(z_1,z_2,z_3)$, and $(w_1,w_2,w_3)$ be two **triples**?
Comment: You wrote "Then their is a unique linear fractional transformation, $L$ such that $L(z_i)=w_i,i=1,2,3.$ ". Sure, of course there is: But I explicitly said that I can't assume that. If I could have, I wouldn't have posted the question.
Comment: Anyway, I had already solved it in a way similar to the way you did above. That's why the question was **Is there an easier way to do this**.
Comment: @ Mulling Right I want $(z_1,z_2,z_3)$, and $(w_1,w_2,w_3)$ to be  triples of extended complex numbers such that the three were distinct. As to you not wanting to assume that I do remember reading that and it somehow got mentally replaced with one of the comments that said that you wanted a proof not involving power series or power series.
Comment: To your original question I cannot see a way of proving this without using the exercise, that is on the surface (more elaborate techniques might give something however).


Kruskal-Wallis test for Length vs Year test

Question: I have a dataset of the lengths of a species which has a 1-year lifespan, going back 20 years.
I would like to test if the lengths recorded each year are significantly different from one another (for each sex, we already know that there is a difference between the sexes).
My length data does not have a normal distribution; therefore, I was thinking of using the Kruskal-Wallis test.
However, I am not sure if that is the right way forward for the following reasons:
1) It requires an ordinal scale for the dependent variable, and I am unsure if this applies to length data
2) Is it okay that I am treating the years as a 'group' in this case? I would have ~20 groups.
3) Biologically speaking, I know that each year we are measuring different population, as this species spawns and dies (in a different location to where they are sampled) and the data is temporally independent. However, is there a way to prove this statistically? I attempted running the autocorrelation function in R but I am unsure if that is the way to go?
Many thanks!
Comment: Lengths are ratio scale; Kruskal-Wallis should not have a problem (though personally I'd probably consider a generalized linear model). It's not clear that lengths are necessarily independent across years since the population in one year is descended from the population in the previous year.
Comment: How comes your lengths are not normally distributed? Because discrete ages?
Comment: @KaPy3141 Lengths will tend to be right skew. They certainly can't actually be normally distributed because lengths cannot be negative.
Comment: @Glen_b: Thanks, I get it!
Comment: @Glen_b, thank you for the response, how would you suggest dealing with autocorrelation if I was to find that this is the case? Would a generalised least squares as described here - https://rpubs.com/markpayne/164550 applicable?
Comment: Would you be more interested in treating year as a continuous variable and looking for a trend over years?
Comment: @ichemshirova it depends; probably best to post a new question in that case
Answer: 1): It doesn't need ordinal variables. Your R implementation automatically ranks your variables which makes them ordinal.
2): Yes, that's ok. Just be aware of additional biases than gender. (age distribution)
3) Yes, you can do a regression of your choice. For example linear regression to show that there is no linear time dependence.
(I am not a statistics expert myself, but I am quite confident this should be correct)
Comment: Could you explain how you're using linear regression to show there's no autocorrelation in "3)"?
Comment: I referred to the first part of the question: If there is a way to analyze temporal dependence. The answer is there are multiple ways. Just the result needs to be interpreted differently! (Linear for linear effect, auto-correlation for year-to-year effect)
Comment: @KaPy3141 Thanks for the info!


jQuery Slider - Dynamic Height on Mobile & Refresh

Question: I'm having a issue with a slider. I want the slider height to change to the height of the image present. This works on desktop, but seems to break on mobile.
Additionally, when the page is refreshed manually, the initial height isn't set. I read this was due to the ready() function, and to use a onload with a interval init, which I tried to do, but the whole slider breaks with onload and the interval in use.
http://www.nwdastore.com/slideshow-test/
Answer: You just have to remove min-height: 450px from #slider-container since the slider has a height less than 450px when the device is mobile.
#slider-container {
    background: rgb(1,1,1);
    margin: 0 auto -10px auto;
    max-width: 1440px;
    overflow: hidden;
    position: relative;
    width: 100%;
}

Comment: Glad you did it. I was going to try to help you later, but now it's done. Yes, onload is appropriate that way. See, I also missed that silly detail. :)
Comment: Makes me feel a little dumb. lol I removed the actual height element, of course **min**-height is the cause.
Comment: Do you have any idea about the second part of the dynamic height? When page is manually refreshed the height cannot be accurately grabbed.
Comment: I think it happens because you forget to dynamically set height inside `prevSlide()` the same way you did on `nextSlide()`. I'm not sure, but I think that's it. Of course, there are probably more details to improve.
Comment: When you F5 to refresh, the first slide is not present at all because the `min-height` is missing. This means that the script that gets the height of the hidden/visibl  elements suddenly cannot get the height when you manually refresh with F5 versus clicking "Go" with the address bar.
Comment: https://stackoverflow.com/questions/13314058/jquery-height-returns-different-results-using-f5-or-ctrlf5 This seems to be the problem, and solution, but it breaks my slider when using `load`. The slider never initiates, even with the interval being started when load is finished.
Comment: I resolved the refresh issue. I was trying to use `onload` with the `document` rather than the `window`. Woops. After that self initiation was no issue. Thanks for the help!


Date format changing according to browser

Question: This is my JS function for displaying the date in the browser, but the format is changing according the browser. Means when i open my project on chrome then format is 4/30/2015, and when open on IE then 30 april, 2015. How can i fix this?
document.getElementById(lblClock).innerHTML = nd.toLocaleString();

I am using this. How can i do this without using Date.js and moment.js? Please help me
Comment: Try using something like moment.js instead
Comment: How can i use this ? using reference in my project or something else?
Comment: That how it behave.  If you want to follow a common format then parse the date and add in.
Comment: How can i do this without using library?
Comment: You do this without library by searching StackOverflow.
Comment: Good idea bro............i dont know Stackoverflow!
Answer: Nothing Special about this previously i was using this which convert the locale date into a string.
document.getElementById(lblClock).innerHTML = nd.toLocaleString();

Just give your specific format in which you want to see your date just like this.
document.getElementById(lblClock).innerHTML = nd.format('dddd,MMM dd,yyyy,HH:mm:ss');

It will work on any browser or any version.
Answer: Try to use date format lib from http://blog.stevenlevithan.com/archives/date-time-format
or try to find something similar
Comment: So, maybe i understand your question wrong. What is `nd` in your code `document.getElementById(lblClock).innerHTML = nd.format('dddd,MMM dd,yyyy,HH:mm:ss');` ?


Pass variable inside ruby command?

Question: prueban8 file content is:
 $F[1] > "2" and $F[1] < "4" and $F[3] == "pet"

Code is:
ruby -a -F ';' -ne 'input = File.read("prueban8"); eval (input); puts  $F[2] end' ppp.txt

but I cant pass variable appears error
, unexpected end-of-input
How can I solve this?
Comment: I am curious as to the advantage of putting the code in another file when it would have been quicker to just include it in the script you have written?
Comment: I am  using a variable from jquery serialize command throught sinatra framework
Comment: for filter data
Answer: I solved with this
ruby   -a   -F';' -ne      'input = File.read("prueban8")   ; eval ( input +  " ; puts  $F[2] end")   '  ppp.txt

Pass variable inside ruby command?


Add user id to comment model

Question: I'm following this tutorial :
http://guides.rubyonrails.org/getting_started.html#adding-a-second-model
It works when using commenter and comment where the user can add a name and message but I want to associate the comment with a user id (I already have users)
It uses
rails generate model Comment commenter:string body:text post:references but I want to replace commenter:string with a user id association (user_id:integer?). In a previous question someone suggested author_id:integer but it did not work. Not sure where to start and there doesn't seem to be any tutorials on the subject (I have read RoR help guides on associations etc but can't find the correct way to generate a user id with the comment model)
comments_controller.rb
def create
@listing = Listing.find(params[:listing_id])
@comment = @listing.comments.create(params[:comment])
redirect_to listing_path(@listing)
end

Answer: You can generate the Comment mode like this:

rails generate model Comment user:references body:text post:references

The references type you specify will actually create a user_id:integer column and adds a belongs_to association to the Comment model:
class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

If you do want to have a Comment#commenter association to refer to the user rather than Comment#user, you can define it in your Comment model as follows:
class Comment < ActiveRecord::Base
  belongs_to :commenter, class_name: 'User', foreign_key: 'user_id'
  belongs_to :post
end

Comment: How would i get the user id of a specific comment on the /posts/1 page where the comments and comment form are located? (so each comment had the user id next to it) When I look in the dev database the user_id for the comment is blank. How do I associate the user ID when creating a new comment (I will post my comments controller)
Comment: That would be with something like: `@post.comments.first.user_id`. Or you can just return the `User` instance: `@post.comments.first.user`.
Comment: To assign the user to a new comment, you need to get the current user instance and then use it to create the comment: `@comment = @listing.comments.create(params[:comment].merge(user: user))`. I'm assuming you're using Rails 3.2 or below btw.
Comment: I'm using Rails 4.0.2
Comment: Then you need to use strong parameters or else the comment creation won't work properly. See here: http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller

Add user id to comment model


The Conjugate Beta Prior proof

Question:
Hello.
I'm having a problem with trying to figure out this proof that shows the beta
distribution is conjugate to the binomial distribution (picture attached).
I understand it until the third row, but I got confused with this step from the third to the fourth row.
I would appreciate a simple explanation.
Thank you in advance.
Answer: To go from the third to fourth row just ignore factors that are constant with respect to $\pi$. That is, let
$$\binom{n}{y}\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}=k$$
so
$$p(\pi|y)=k \cdot \pi^y (1-\pi)^{(n-y)}\pi^{(\alpha-1)}(1-\pi)^{(\beta-1)}$$
or
$$p(\pi|y) \propto \pi^y(1-\pi)^{(n-y)}\pi^{(\alpha-1)}(1-\pi)^{(\beta-1)}$$
The idea's to deal just with the kernel of the probability distribution, knowing you can always put the normalizing constant back in later.

The Conjugate Beta Prior proof


is ndarray faster than recarray access?

Question: I was able to copy my recarray data to a ndarray, do some calculations and return the ndarray with updated values.
Then, I discovered the append_fields() capability in numpy.lib.recfunctions, and thought it would be a lot smarter to simply append 2 fields to my original recarray to hold my calculated values.
When I did this, I found the operation was much, much slower. I didn't have to time it, the ndarray based process takes a few seconds compared to a minute+ with recarray and my test arrays are small, <10,000 rows.
Is this typical? ndarray access is much faster than recarray? I expected some performance degradation due to access by field name, but not this much.
Comment: It's unclear which operations you are comparing.  `append_fields` has to define a new array, and copy data from the sources, field by field.  What size of arrays are dealing with? shape? dtype?
Comment: As hpaulj said, append_fields creates a new array and copies data over so it will be rather slow.  In most cases it's better to just return the calculated values.
Comment: `recarray/structured array` is convenient when you want to keep a mixed set of values together - for indexing, sorting, saving and loading from files.  Most users first encounter them when loading `csv` files.  But for calculations across fields, or adding/removing fields, they aren't anything special.  Separate arrays with simple numeric dtype are faster, and just as memory efficient.
Comment: Thanks for the feedback. First some background: I use Pytables to extract data from and HDF5, and pytables returns a recarray whenever a table has dissimilar types.
Comment: My data is in 5 different HDF5 datasets/tables (w/ 2 different dytpes). Here is a typical dtype example:
dtype([('ID', '<i8'), ('F1', '<f8'), ('X1R', '<f8'), ('X1I', '<f8'), ('Y1R', '<f8'), ('Y1I', '<f8'), ('TXY1R', '<f8'), ('TXY1I', '<f8'), ('F2', '<f8'), ('X2R', '<f8'), ('X2I', '<f8'), ('Y2R', '<f8'), ('Y2I', '<f8'), ('TXY2R', '<f8'), ('TXY2I', '<f8'), ('DOM', '<i8')])
Comment: I pull 12 different values from each row to calculate 2 new values that are then saved back to the array. I append  2 "np.zero" arrays to the recarray prior to any  calculations.
The difference in processing time occurs when extracting values, calculating new values and saving them. There are 36,000 rows. When referencing an ndarray, they are processed in a few seconds. When referencing a recarray, they are processed in a few minutes.
Comment: Question: I'm relatively new here. What did I do to get a -1?
Answer: Updated 15-November-2018
I expanded my timing tests to clarify differences in performance for ndarray, structured array, recarray and masked array (type of record array?). There are subtle differences in each. See discussion here:
numpy-discussion:structured-arrays-recarrays-and-record-arrays
Here are result of my performance tests. I built a very simple example (using 1 of my HDF5 data sets) to compare performance with the same data stored in 4 types of arrays: ndarray, structured array, recarray and masked array. After the arrays are constructed, they are passed to a function that simply loops thru each row and extracts 12 values from each row. The functions are called from the timeit function  with a single pass (number=1). This test only measures the array read function, and avoids all other calculations.
Results given below for 9,000 rows:
for ndarray: 0.034137165047070615
for structured array: 0.1306827116913577
for recarray: 0.446010040784266
for masked array: 31.33269560998199

Based on this test, access performance decreases with each type. Access times for structured array and recarray are 4x-13x slower than ndarray access (but all are only a fraction of second). However, ndarray access is 1000x faster than masked array access. That explains the seconds to minutes difference I see in my complete example. Hopefully this data is useful to others that encounter this issue.

is ndarray faster than recarray access?


How to set up path for library and include files

Question: In Drupal 7, I am writing PHP from inside the Front Page module, say:
$page = include_once "templates/page.php";

I put the "templates/page.php" under /sites/all/modules/front and Drupal complains about file missing. Any suggestion where best to put up the files to be included?
Then, after installing the PHP Simple HTML DOM Parser, I wrote the following
$html = new simple_html_dom();

and was complained for Class 'simple_html_dom' not found. I have tried duplicating the library file to the same folder and home, but all cases not working. How to set up the correct path?
Many thanks.
Comment: The [Libraries API](https://www.drupal.org/node/1342220) provides this function.
Answer: If it's a theme function, guessing from the file name you mentioned, you should use them theme() function to get the themed output.
To get the path of a module relative to the Drupal root, use drupal_get_path() function.
If you want to include or require a file, you can use module_load_include(). However, note that if the including files print anything, they will be printed to the current output buffer (which means they will be printed on user browser).
Given the above available features, I think it's theme() that you are looking for.
Comment: Indeed I move the include files to the home directory (Drupal root) and it works fine, though that might not be good practice.
Comment: Is there some way to set up the include path so that a particular file could be found?


High action on higher fret on my steel acoustic guitar

Question: It's been 2 years since the last time I played guitar. I tried to play again this morning and something feels off. I felt sore on my wrist when trying to play barre chords for just a few strums. I don't know if it's just my hands not getting used to after 2 years of break.
I remember something about action and measured my guitar's action. And there is quite a gap between the action on its 1st fret and 15th fret. The action on the 1st fret is around 1 - 2 mm and 5-6 mm on the 15th fret. I'm not sure if this is normal or not. For comparison, the action on my electric guitar is pretty much the same across all fret (1-2 mm on the 1st fret and 2-3 mm on the last fret).
Should I adjust the truss rod? I never do this before so I'm worried if I broke my guitar because of it. Here are some pictures of my guitar's action for reference:
1st Fret:

15th Fret:
Answer: Look down the neck and see how its shape is compared to the very straight strings. It probably needs a tweak of the truss rod, to bring fingerboard and neck more closely in line with each other. Compare with the other guitar and you'll get a better idea.
Comment: I agree with Tim's advice, but would simply recommend using small truss rod adjustments, like an eighth of a turn or so. And don't force it! If the adjuster becomes stiff, you may be a the end of the threads; continuing to force it may break it at that point. Lastly, allow some time for the guitar to settle before making another adjustment; I prefer overnight.
Comment: @Tim I looked at my friend's guitar. Its action is more or less the same (we both took a break at the same time and have the same model). I tried to look down the neck from the headstock and from the bridge but can't find any curve.
Comment: @KirkA I did a half of a turn after looking at my owner's manual. Alas, no change on the action height. Maybe I should bring it to the shop. It bothers me how tight it feels when turning the truss road. I thought I was going to break my guitar.
Comment: Bringing it to the shop is the right thing to do in my opinion. Ask the luthier to teach you some stuff while you are there.
Comment: Is it possible that the action is supposed to be in this height for my guitar's model? Considering my friend's guitar is also in this state. I couldn't really remember how high it was when I first bought it.
Comment: Perhaps they both need a little light relief. There is nothing much wrong with the neck if it looks pretty straight. You could try lowering the saddles or the bridge. There is no real need to have a high action on a well-made guitar. Unless you play slide. If the bridge is non-adjustable, take it to a luthier as b3ko suggests.


Localized short time string using moment.js

Question: How do I get time string from moment.js object with respect to current locale?
moment().format('HH:mm')

always get the same result regardless of localization.
I want similar result as I would use in angular using shortTime:
formatDate(new Date(), 'shortTime'): // HH:mm, resp hh:mm a

Answer: You can simply use Localized formats listed in format() docs

Because preferred formatting differs based on locale, there are a few tokens that can be used to format a moment based on its locale.
There are upper and lower case variations on the same formats. The lowercase version is intended to be the shortened version of its uppercase counterpart.

Here a live sample:

console.log( moment().format('LT') );
moment.locale('it');
console.log( moment().format('LT') );

Comment: @Julia if you want to customized the output of `LT`, you can use [`updateLocale`](https://momentjs.com/docs/#/customization/long-date-formats/) function, so you can have something like: `moment.updateLocale('en', {longDateFormat : { LT: "HH:mm a"} })`. Please consider searching other question similar to yours on SO or ask a new one, instead of asking for custom cases in the comments.
Comment: do you know how to change "8:39 PM" to "8:39pm"?
Comment: @Julia if you need to get "8:39pm" you can use "`HH:mm a`" as formatting token.
Comment: Yep, but I need to use "LT" for localization)


Python/Django OOP modify the following code to show get/set and constructor

Question: Case. I want to modify and add the following behavior to the code below (it's a context processor):
After checking if a user is authenticated check the last time the balance was updated (cookie maybe) if it was updated in the last 5 mins do nothing, else get the new balance as normal.
def get_balance(request):

     if request.user.is_authenticated():
        balance = Account.objects.get(user=request.user).balance
     else:
        balance = 0

     return {'account_balance': balance}

HOWEVER:
I want to learn a little more about OOP in Django/Python can some modify the example to achieve my goal include the use of:
Property: I come from Java, I want to set and get, it makes more sense to me. get balance if does not exist else create new one.
Constructor method: In Python I think I have to change this to a class and use init right?
UPDATE:
To use a construct I first think I need to create a class, I'm assuming this is ok using  as a context processor in Django to do something like this:
class BalanceProcessor(request):

    _balance = Account.objects.get(user=request.user).balance

    @property
    def get_balance(self):
       return  return {'account_balance': _balance}

    @setter???

Comment: please, fix your indentation. It is not anoptional thing for Python code.
Comment: @jsbueno Typed into question so forgot indention, fixed :)
Comment: I keep trying to answer your question correctly, but you keep editing it ;) Btw, the "request" variable in parentheses next to "BalanceProcessor" is what you would be subclassing... it's not an argument.
Comment: @JoeLinux no more edits :)
Answer: Python is not Java. In Python you don't create classes for no reason. Classes are for when you have data you want to encapsulate with code. In this case, there is no such thing: you simply get some data and return it. A class would be of no benefit here whatsoever.
In any case, even if you do create a class, once again Python is not Java, and you don't create getters and setters on properties unless you actually need to do some processing when you get and set. If you just want to access an instance attribute, then you simply access it.
Finally, your proposed code will not work for two reasons. Firstly, you are trying to inherit from request. That makes no sense: you should inherit from object unless you are subclassing something. Secondly, how are you expecting your class to be instantiated? Context processors are usually functions, and that means Django is expecting a callable. If you give the class as the context processor, then calling it will instantiate it: but then there's nothing that will call the get_balance method. And your code will fail because Django will pass the request into the instantation (as it is expecting to do with a function) and your __init__ doesn't expect that parameter.
It's fine to experiment with classes in Python, but a context processor is not the place for it.
Comment: @User7 : doing proper OO in Django requires a good understanding of both Python's object model (which is a bit peculiar when coming from most mainstream OOPLs) AND the objects lifecycle in Django. Also wrt/ properties (which are just a "general" application of the `descriptor` protocol), the moto is "don't use them until you need them" - and if you find yourself writing the same fget/fset implementation for a couple or more properties it might be time to roll your own custom `descriptor`.
Comment: Hi @Daniel Roseman, I still see the need for a getter and setter here. It allows me to get the balance and let the code set one if not created. I also see the need to change or modified the set balance method in the future. A setter makes more sense to me here. It future-proofs the code! Without doing this I don't see how I can change the code later without changing the calling methods here.
Comment: We don't "future-proof" with getters and setters: this is why Python has the `@property` decorator. But what would be the point of setting anything here? The context processor would be instantiated when the template is rendered, then immediately disposed. Nothing is persisted. Why would you set data?
Comment: I see thanks for taking the time to explain, this is what I need to learn. In terms of a context processor I see now why this makes no sense. @property is very interesting I tried to edit the code to make use of them (pretending it's not context processor)


Controle de versão de dependências

Question: Uso python, Django em um servidor com CloudFoundry instalado. Lá, consigo manter o meu requirements.txt com todas as dependências da minha aplicação e, por segurança, mantenho sempre o nome exato da versão de cada plugin pra evitar crashes inesperados por incompatibilidade com novas versões.
Werkzeug==126.96.36.199
Django==1.11

Quais as melhores práticas pra se acompanhar as versões das minhas dependências em uma aplicação "séria" (grande porte)? Inscrevo-me nas listas de distribuição de e-mail de cada plugin pra receber informações de atualizações mas nem sempre elas existem.
Imagino que essa pergunta seja aplicável a outros ambientes/frameworks.
Comment: Se ao invés de eu perguntar quais são as melhores, eu perguntasse quais opções disponíveis, reabriria? Ou ainda é muito ampla?
Answer: Eu vi alguns projetos usando badges de serviços externos como o https://requires.io/
Eles tem plano grátis para projetos open source e planos pagos.
Você também pode rodar pip list -o que vai listar os pacotes que tem atualização disponível, você pode colocar esse comando rodando uma vez por dia no seu CI e ter um alerta se o comando tiver algum output.
Comment: O requires.io me pareceu muito interessante pra quem usa GitHub. Vou deixar a pergunta em aberto, por enquanto, pra ver se vejo algum exemplo de grandes aplicações em produção.

Controle de versão de dependências


Passing dates or date ranges into a view as arguments

Question: Drupal 7, Views and Date modules installed.
I have a view on a content type with a date field (timestamp, but I can change it if necessary)
When I use it in filter criteria, I have no problem to use criteria like Mydate greater than, less than, between, not between etc.
But if I try to do the same thing using contextual filters I have only the "equal" criteria. I need to do this, so i can call the view from code passing arguments to it.
I found some pages about Drupal 6 where is written that i can pass parameter to the filter in format: 2008-11-12--2010-11-12, but when i try to make it and hit 'update preview', i obtain: (field_data_field_test_date.field_test_date_value = '2008-01-01--2010-12-31') in the query.
I need to:

use criteria greater than, less than, between
pass date range to the view

Does anybody have some suggestion on how I can do it?
Comment: @OwenBlacker We *don't* cross-post on sites in the SE network, that's considered *noise*.  This is being migrated though, and you should recommend that in the future
Comment: @casperOne That makes complete sense. I'll bear that in mind in future. Thanks for the reminder.
Answer: Please refer below URL and check the answer given by @Dmitriy
How to implement less than / greater than in views contextual filters
This may help you.
Answer: Use Views Contextual Range Filter module

Views Contextual Range Filter is a simple plugin for Views that adds
  the option to contextually filter not just by a single value, but also
  by range.
Numeric, alphabetical and list ranges are all supported. Node ids,
  user ids and even taxonomy term ids are all special cases of numbers
  so will work also. Range-filtering on dates is also supported. For
  this you may use either the absolute date format as dictated by Views,
  YYYYMMDD, or the relative format, which supports natural language
  phrases like six months ago, today noon and even first Tuesday of
  November


Failed to reproduce the high-precision time measuring kernel module from intel's white paper

Question: I am trying to reproduce How to Benchmark Code Execution Times on Intel IA-32 and IA-64 Instruction Set Architectures White Paper. This white paper provides a kernel module to accurately measure the execution time of a piece of code, by disabling preempt and using RDTSC, etc.
However, I cannot get the expected low variance when running the benchmark codes as reported in the white paper, which means the technique from the white paper doesn't work. I couldn't find out what's wrong.
The core of the kernel module is just a couple of lines
unsigned int flags;
preempt_disable();
raw_local_irq_save(flags);

asm volatile(
    "CPUID\n\t"
    "RDTSC\n\t"
    "mov %%edx, %0\n\t"
    "mov %%eax, %1\n\t"
    : "=r"(cycles_high), "=r"(cycles_low)::"%rax", "%rbx", "%rcx", "%rdx");
/* call the function to measure here */
asm volatile(
    "RDTSCP\n\t"
    "mov %%edx, %0\n\t"
    "mov %%eax, %1\n\t"
    "CPUID\n\t"
    : "=r"(cycles_high1), "=r"(cycles_low1)::"%rax", "%rbx", "%rcx", "%rdx");
raw_local_irq_restore(flags);
preempt_enable();

The codes are directly copied from the white paper with the optimizations adopted.
From the white paper, the expected output should be
loop_size:995 >>>> variance(cycles): 0; max_deviation: 0 ;min time: 2216
loop_size:996 >>>> variance(cycles): 28; max_deviation: 4 ;min time: 2216
loop_size:997 >>>> variance(cycles): 0; max_deviation: 112 ;min time: 2216
loop_size:998 >>>> variance(cycles): 28; max_deviation: 116 ;min time: 2220
loop_size:999 >>>> variance(cycles): 0; max_deviation: 0 ;min time: 2224
total number of spurious min values = 0
total variance = 1
absolute max deviation = 220
variance of variances = 2
variance of minimum values = 335757

However, what I get is
[1418048.049032] loop_size:42 >>>> variance(cycles): 104027;max_deviation: 92312 ;min time: 17
[1418048.049222] loop_size:43 >>>> variance(cycles): 18694;max_deviation: 43238 ;min time: 17
[1418048.049413] loop_size:44 >>>> variance(cycles): 1;max_deviation: 60 ;min time: 17
[1418048.049602] loop_size:45 >>>> variance(cycles): 1;max_deviation: 106 ;min time: 17
[1418048.049792] loop_size:46 >>>> variance(cycles): 69198;max_deviation: 83188 ;min time: 17
[1418048.049985] loop_size:47 >>>> variance(cycles): 1;max_deviation: 60 ;min time: 17
[1418048.050179] loop_size:48 >>>> variance(cycles): 1;max_deviation: 61 ;min time: 17
[1418048.050373] loop_size:49 >>>> variance(cycles): 1;max_deviation: 58 ;min time: 17
[1418048.050374]
                  total number of spurious min values = 2
[1418048.050374]
                  total variance = 28714
[1418048.050375]
                  absolute max deviation = 101796
[1418048.050375]
                  variance of variances = 1308070648

a much higher max_deviation and variance(cycles) than the white paper.
(please ignore different min time, since the white paper may be actually benchmarking something, but my codes do not actually benchmark anything.)
Is there anything I missed from the report? Or is the white paper not up-to-date and I missed some techniques in the modern x86 CPUs? How can I measure the execution time of a piece of code with the highest precision in modern intel x86 CPU architecture?
P.S. The code I run is placed here.
Comment: BTW, `lfence` is a sufficient barrier.  Also note that CPUID's cycle cost can sometimes depend on incoming EAX and/or ECX values, so that's another reason to avoid it.  That and/or CPU frequency warm-up might possibly explain things.  (Also the inline asm statements can just use `"=a"` and `"=d"` outputs, instead of `mov` to `"=r"` outputs.  The first asm statement could/should already be doing this with CPUID.)
Comment: See also [How to get the CPU cycle count in x86\_64 from C++?](https://stackoverflow.com/q/13772567) for more about how RDTSC (and the time-stamp-counter it reads) actually work.
Comment: For information on how to measure execution times on recent x86 CPUs, have a look at https://github.com/andreas-abel/nanoBench and https://arxiv.org/pdf/1911.03282.pdf
Comment: What CPU model and kernel version are you testing with?
Comment: Although it is probably not possible to predict all the corner cases, I have had very good results from the methodology described at http://sites.utexas.edu/jdm4372/2018/07/23/comments-on-timing-short-code-sections-on-intel-processors/
Answer: Most Intel processors have a constant TSC, which implies that the core frequency and the TSC frequency may be different. If an operation takes a fixed number of core cycles to complete, it may take very different numbers of TSC cycles depending on the core frequency during the execution of the operation in different runs. When max_deviation is large, it indicates that the core frequency has changed significantly during the execution of that iteration. The solution is to fix the core frequency to the maximum non-turbo frequency of your processor. For more information on constant TSC, see: Can constant non-invariant tsc change frequency across cpu states?.

please ignore different min time, since the white paper may be
actually benchmarking something, but my codes do not actually
benchmark anything.

The minimum values depend on the microarchitecture, the core frequency (which can dynamically change), and the TSC frequency (which is some fixed value close to the base frequency). The authors of the white paper only said they're on an Core i7 processor. In 2010, this is either a Nehalem or Westmere processor.
The measurements you've copied from the paper are from Section 3.3.2 titled "Resolution with the Alternative Method." The alternative method uses mov cr0, rax for serialization instead of rdtscp. But your code is from Section 3.2.2.
Note that the if ((end - start) < 0) {...} is never true when end and start are unsigned integers because the result of the subtraction is unsigned and the constant 0 is also converted to an unsigned type. Change it to if (end < start) {...}.
Comment: Oh right, halting the core clock to change CPU frequency can explain a huge time spike even without interrupts.  It takes multiple microseconds of no core cycles for that to happen, so for an empty timed region it's a much bigger effect even than starting at idle frequency.   [Lost Cycles on Intel? An inconsistency between rdtsc and CPU\_CLK\_UNHALTED.REF\_TSC](https://stackoverflow.com/q/45472147)
Comment: Another solution would be to measure core cycles instead of reference cycles using performance counters.
Comment: `max_deviation` can also be higher than expected due to interference from hyperthreading. The solution for this would be to disable hyperthreading.


Using Pearson's $R^2$ for model selection

Question: I have a question about using $R^2$ as a "best fit" technique for cross-sectional (not time series) type data...
Suppose you have a data set, and you're trying to fit a regression model to it. You try several types of models (classic linear, exponential, log-log, etc), and ultimately choose one with the highest $R^2$  value (unadjusted?).
Is this an appropriate way to select a regression model, or are there other, more appropriate ways to determine the model which best fits the data?
Thanks
Comment: In this case, you will pick a model with as many parameters as observations, leading to the optimal R squared of 1. By including many high order polynomials of the predictors and their interactions, this is easy to achieve.
Answer: There is a much more appropriate way: the information-theoretic approach. Statistics such as AIC and BIC are distribution-independent and can be used to compare any number of candidate models. A great reference is Model Selection and Multimodel Inference by Kenneth Burnham.
I'll flesh this out a bit more: $R^2$ is useful in establishing how well a line fits data. It is defined as
$$R^2:=1 - \frac{\text{Sum of vertical distances from the line of best fit}}{\text{Sum of horizontal distances from the line of best fit}}$$
This quantity works well in linear cases because it is bounded by 0 and 1; but for your purposes, e.g. exponential fits, there is no such guarantee of behavior of your data and so $R^2$ isn't such a good metric.
EDIT: See the answer in this post as to why $R^2$ is insufficient.
Comment: AIC and BIC are both likelihood-based, so what exactly do you mean when you say they're distribution independent?


understanding ldd output - symbolic links

Question: Usually shared libs have two symbolic links:
libexample.so -> libexample.so.1
libexample.so.1 -> libexample.so.1.1

I link to my program a shared lib which also has two symbolic links:
libassimp.so -> libassimp.so.3
libassimp.so.3 -> libassimp.so.3.1.1

When I run ldd myprogram I get:
libassimp.so.3 => /home/user/libs/assimp-3.1.1/lib/libassimp.so.3
(0x00007f34ab0bd000)'

What does it mean ? Why ldd shows second symbolic link ? When I run grep assimp /proc/myprogrampid/maps I get path to the libassimp.so.3.1.1 which indicates that the library was loaded, but I don't understand form of the ldd output.
Answer: Refer Michael's answer on https://unix.stackexchange.com/questions/475/how-do-so-shared-object-numbers-work
Binaries themselves know which version of a shared library they depend on, and request it specifically.
The reason for the symbolic link is for the linker. When you want to link against libpthread.so directly, you give gcc the flag -lpthread, and it adds on the lib prefix and .so suffix automatically. You can't tell it to add on the .so.0 suffix, so the symbolic link points to the newest version of the lib to faciliate that


Using Dirichlet's theorem to show existence of number coprime to $n$

Question: I have the following question: Let $n$ be a positive integer and $d$ be divisor of $n$. Use Dirichlet's theorem to show that there exists an integer $k$, where $1\le k\le d-1$ such that the number $m:=1+\frac{nk}{d}$ is coprime to $n$.
My idea is to show that if we can find such a $m$ that is prime, then $m$ is coprime to $n$ necessarily. Let us suppose on the contrary for all $k=1,\cdots, d-1$, the number $m$ is not prime. Then (perhaps?) This will show that there exists finitely many numbers of the form $1+\frac{nk}{d}$ that is not prime, contradicting Dirichlet's theorem. I am stuck here. Any ideas how to proceed?
Comment: @i707107 the question insists we use Dirichlet's theorem so I would like to see an approach on that method though. Thanks for the comment nonetheless!
Comment: Dirichlet's theorem is not necessary. Try using Chinese remainder theorem.
Comment: @thedilated As my answer shows, what you're asking to prove is not necessarily always true as it's currently stated.
Answer: Using a sledgehammer to kill a flea...
Hint: by Dirichlet's theorem, there is some $k$ (not necessarily $\le d-1$) such that
$p = 1 + nk/d$ is prime.  Note that if $k' \equiv k\; (\bmod d)$, $1 + n k'/d \equiv p\; (\bmod n)$.
Comment: Yes, I agree it's overkill. However, as my answer shows, Direchlet's Theorem is not necessarily sufficient by itself. The question request is not necessarily always true, but my suggested change would then allow Dirichlet's Theorem to work as you state in your answer.
Answer: Unfortunately, using Dirichlet's Theorem is not necessarily sufficient by itself to give a prime $p = 1 + nk/d$ which you can use (such as described in the the answer hint of Robert Israel) given your problem restrictions. In particular, this is because it doesn't exclude the possibility that $k \equiv 0 \pmod d$. In fact, Dirichlet's Theorem can even require this if, for example, $d = 2$ and $n/d$ is odd and greater than $1$.
Also, note that what you're asking to prove isn't even always true! For example, if $n = 6$ and $d = 2$, then the restriction $1 \le k \le d - 1$ means that $k = 1$ is the only value allowed. However, $1 + \frac{6 \times 1}{2} = 4$ is not coprime to $n = 6$. To avoid the trivial example of $k = 0$, I believe a better question would be to have $1 \le k \le d$. However, using $k = d$ gives $m = 1 + n$, so it's also fairly trivial to solve. Nonetheless, at least with my example, $k = 2$ will then be allowed, giving $1 + \frac{6 \times 2}{2} = 7$. Also, Dirichlet's Theorem could then be appropriately used as well.
Another option is that I believe just simply requiring $d \gt 2$ is sufficient for your statement to then always be true. However, there would then still remain the issue of Dirichlet's Theorem not necessarily guaranteeing (as far as I know) any primes apart from those where $k \equiv 0 \pmod d$.
Please check your source to see if you made a mistake in your question text.


Convolutional neural networks and 3D images

Question: I am interested in applying CNNs to 3D images (i.e. medical data).
Does TensorFlow already incorporate this functionality?
Answer: TensorFlow now supports 3D convolution and 3D pooling in the master branch.
You can use them with 5D tensors as input with shape: <code>[batch_size, depth, height, width, channels]</code>.
Comment: Lucky you, there is a [pull request](https://github.com/tensorflow/tensorflow/pull/3049) under way which would add support for that. See also [this issue](https://github.com/tensorflow/tensorflow/issues/2467)
Comment: what about 3D transpose (deconvolution)?
Comment: How'd you get so good at tensorflow? Lol, you are always spot on with your answers! Thanks!
Comment: Haha I work using TensorFlow so with time comes wisdom ;)
Comment: These links are now giving 404s, but I'm not sure how to best update them. I did find this example:https://gist.github.com/dansileshi/21b52113ce0ecb6c0f56d6f7534bbaca
Answer: No, the current implementations are made for 2D images (functions like nn.conv2d). They support multiple channels (eg RGB) and it is possible to express 3D images as a multichannel 2D image (each z-slice is a channel), but this isn't always ideal. Additionally for using these sort of approaches you need substantial amounts of image data which is typically difficult to come by in the medical area.
Update: both TensorFlow and Theano (subsequently Keras, Lasagne, etc) now all support 3D operations as stated above. It is important to note that 3D operations are much more computationally and memory intensive than a similar 2D operation.
Comment: Yeah, Thats right, I just want to if the operation is the same, to be honest I'm lost how the operation is carried out. when we talk about temporal stride, what does that mean? how do we do strides for temporal dimension? I know 5 frames, in a row is called the temporal dimension. (image count, depth, channel count, x width, y width ), which depth here would be 5. denoting there are 5 frames of let say e.g 200x200x3 .
so how does stride makes sense in this regard?
Comment: How is it any different from the conv2D? It seems to me as if Conv3D is batch+image which creates batch+featuremaps.
in conv2d, we have image with channels, which creates kxWxH feature maps.
you have x number of images? then x number of featuremaps will be crated .
AM I wrong ?
Comment: Well a conv2d is a 4 dimensional matrix ( image count, channel count, x width, y width) a conv3d operation is a 5 dimensional matrix.
Answer: The TensorFlow implementation for 3D Convolutional Neural Networks has been provided with the following open source projects:
Lip Reading - Cross Audio-Visual Recognition using 3D Convolutional Neural Networks
Using 3D Convolutional Neural Networks for Speaker Verification
Answer: If you want to use CNN with 3D images, a possible alternative is to use this Caffe PR.
You will need to convert your data to HDF5 format.


An endomorphism of a tensor product

Question: Let $k$ be a field, let $A$ be a finite-dimensional $k$-algebra with basis $e_1,\ldots,e_n$, and let $B$ be any $k$-algebra. I am dealing with an endomorphism $f:A\otimes_k B \to A\otimes_k B$.

What difference is there between considering $f$ as a homomorphism of $k$-algebras or $B$-algebras?

Does $f$ induce a canonical map $A\to A$ of $k$-algebras? I tried the following: take $a=\sum \lambda_ie_i$ and $b\in B$, then $$f(a\otimes b)=\sum \lambda_i f(e_i\otimes b).$$ Assuming $f$ to be a $B$-algebra homomorphism we can further write $e_i\otimes b=b(e_i\otimes 1)$ so that $f(a\otimes b)=\sum \lambda_i b f(e_i\otimes 1)$ (not so sure about that). I was hoping for $f(e_i\otimes 1)$ to land in $A$ so that I may define $A\to A$ as $e_i\mapsto f(e_i\otimes 1)$.

Can one expect the basis elements $e_i$ to be pairwise orthogonal? or to be idempotent?
Answer:
$f$ a homomorphism of $k$-algebras means that it is a ring homomorphism which is also $k$-linear, while $f$ a homomorphism of $B$-algebras means it is a ring homomorphism which is also $B$-linear. It's possible that a $k$-linear homomorphism may not be $B$-linear depending on the action - for instance, if $A=k$ and $B=k[t]$, the $k$-linear homomorphism defined by sending $t\mapsto t+1$ is not $B$-linear.

Yes, the identity map is something you can always pick as an automorphism.

No, you can't guarantee either. For instance, if $A$ is a nontrivial field extension of $k$, then neither of those properties can hold.
Comment: Thank you for your answer. For (2), I think I didn't do a good job explaining myself, so I edited that part of the question.

An endomorphism of a tensor product


Acessar vários sistemas com uma única credencial, tipo o Google

Question: Então, estou criando pequenos sistemas (Produtos) no láravel 8 e estou com uma duvida para fazer o acesso (Login) nesses sistemas. Seria possível fazer uma única autenticação e o cliente poder acessar todos os produtos tipo o Google que você loga uma única vez e pode acessar o Gmail, Google Drive, Google Docs e etc.
Hoje nos sistemas normais eu uso a autenticação padrão do laravel, como mostro abaixo.
<code>public function index()
{
    return view('Admin.auth.login');
}

/**
 * Handle an authentication attempt.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */

public function authenticate(Request $request)
{
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
    ]);

    $remember = $request->remember?true:false;

    if (Auth::guard('user')->attempt($credentials, $remember)) {
        // $request->session()->regenerate();

        return redirect()->intended('painel');
    }

    return back()->withErrors([
        'email' => 'As credenciais fornecidas não correspondem aos nossos registros.',
    ]);
}

/**
 * Log the user out of the application.
 *
 * @param  \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */
public function logout(Request $request)
{
    Auth::guard('user')->logout();

    // $request->session()->invalidate();
    // $request->session()->regenerateToken();

    return redirect('/painel');
}
</code>
Desde já agradeço pela atenção de todos.
Comment: Quando você diz que está criando pequenos sistemas/produtos, significa que são projetos separados, com banco de dados diferentes e sem comunicação direta (um projeto não tem classes funções de outros projetos)?
Comment: Exatamente isso, serão pequenos produtos que se tiver comunicação será via API e todos eles serão acessados de uma única plataforma, é onde o cliente irá fazer o login.
Answer: Há 2 formas:

Criar uma aplicação que será usada pra gerenciar os usuários e forneça um meio para outros serviços a acessarem afim de validar o usuário. A aplicação cliente faz o login no serviços de usuários, que armazena um token no banco e o retorna pro cliente, esse token é enviado para todos os serviços que precisem de autenticação e esses serviços consultam o serviço de usuários pra verificar se o token é válido e qual usuário está atrelado aquele token

Apesar de funcionar, essa forma requer que o serviço de autenticação seja chamado muitas vezes pelos demais serviços, por isso, é recomendado o segundo meio...

Criar um serviço separado para genrenciar os usuários também, porém, o token gerado por ele deve ser um JWT (JSON Web Token), como ele tem uma parte criptografada e apenas você tem a chave secreta (idependente do algoritimo que for utilizar), pode verificar se aquela assinatura está correta, se sim, pode confiar nos dados do token. No payload você também pode enviar algumas informções úteis do usuário, como id, nível de permissão (role), email ou telefone, com esses dados, seus outros serviços provavelmente não precisaram acessar o serviço de usuários recorrentemente, mas em alguns casos pode ser necessaŕio obter todos os dados. Note que não é necessário armazenar esse token em nenhum banco de dados do lado do servidor, apenas o cliente armazena essa informação (em LocalStorage, por exemplo)

Pra implementar o primeiro meio, basta criar os endpoints necessários da forma que preferir, pro segundo, também precisará usar uma biblioteca pra facilitar a criação e validação dos tokens e manter a(s) chave(s) de criptografia em todas as aplicações que precisarem criar ou validar o token

Especificamente pro Laravel, você pode utilizar o jwt-auth, tem uma explicação e exemplos nesse tutorial em português


Por que servidor requer portas abertas em um modem de acesso mas o cliente não?

Question: Me surgiu essa dúvida em quanto eu estava pensando em criar um chat para comunicação direta entre dois computadores seja local ou remotos. Esse será meu primeiro projeto de estudo em que eu aplico comunicação por rede. Então eu percebi que para criar um servidor é necessário abrir portas no modem de acesso a internet, mas para que o cliente se comunique não. Por que?
Answer: O cliente não recebe requisições, ele só as emite. O servidor recebe requisições, então precisa ser permitido que isso aconteça. Se permitisse todas portas teria uma grande área de ataque através de requisições de exploração.
Na verdade não é que precise abrir as portas para o cliente, elas estão todas abertas, não tem porque fechar portas de saída a não ser que não confie no que está rodando na máquina, mas aí porta aberta é o menor dos problemas.
É como um show, uma festa fechada, em evento, há controle de quem entra, não de quem sai. Todo mundo pode sair, só quem tem permissão pode entrar.
Claro que todo cliente pode ser um servidor também. Em comunicações ponto a ponto são assim. O ponto a ponto precisa sempre saber o endereço do ponto para iniciar a comunicação.
A requisição inicial de comunicação precisa da porta aberta, mas depois isso não é mais problema na maioria das arquiteturas já que a conexão pode ser mantida aberta, aí fica como se fossem dois clientes se comunicado.
Comment: @ThomsonTorvalds é isso mesmo, se quiser fazer comunicação ponto a ponto só se os clientes sejam servidores também. Para não exigir isto precisa de um servidor pelo menos pra iniciar a conversa, depois dá pra para eles se comunicarem diretamente mantendo a comunicação aberta, aí não precisa mais de requisições. Cada comunicador tem seu jeito, mas acredito que o mais comum é o servidor só existir para iniciar a comunicação entre pontos. Em alguns casos ele quer centralizar a comunicação e ter um histórico, aí o servidor mantêm toda conversa nele. Jogos são assim também, até pq é um "chat" deles
Comment: Entendi.
Então no caso se eu quisesse que dois computadores troquem informações entre si, levando em consideração que eles não precisem ter portas abertas no modem, eu teria que utilizar um servidor fora das duas redes  onde estarão os clientes? Sendo o servidor apenas responsável por redirecionar mensagens, é assim que serviços como Whatsapp e outros mensageiros funcionam?
Comment: Acredito que tanto cliente quanto servidor usem portas para se comunicarem, sua resposta dá a entender o contrário. Ou não sei lá... Caso o cliente necessite uma porta deveria estar mais explícito...
Comment: @MagicHat Acredito que "não é que precisa abrir as portas para o cliente, eles estão todas abertas." indica claramente que usa portas.
Comment: É parece mesmo, a pergunta é ampla e não e clara, pois nem faz referência a portas físicas ou lógicas... Como geralmente suas respostas abordam uma amplitude maior, achei conveniente mencionar... Mas talvez vc precisasse dá pergunta melhor elaborada


Are finitely generated subrings of $\mathbb{H}$ Noetherian?

Question: Let $R$ be a finitely generated subring of the ring of real quaternions $\mathbb{H}$, that is, $R$ is the subring generated by a finite subset of $\mathbb{H}$. I want to show (or find a counterexample) that $R$ is Noetherian.
My attempt is the same as the attempt in this question. However, this attempt is not correct for general rings as pointed out in the answers. I wonder if there is some special property of $\mathbb{H}$ that would make this attempt work.
Any help is much appreciated.
Comment: @morphy22: No.  For instance, note that $(\pi i)^2$ and $(e^\pi j)^2$ commute, but $X^2$ and $Y^2$ do not commute in $\mathbb{Z}\langle X,Y\rangle$.
Comment: I don't know the answer, but maybe you can embed $\mathbb Z\langle X, Y \rangle$ in $\mathbb H$ by sending $X$ and $Y$ to something like $i + \pi j$ and $i + e j$ with $\pi, e$ algebraically independent (so that hopefully that map is injective). And then it would follow from this question https://math.stackexchange.com/questions/317564/noncommutative-hilbert-basis-theorem-is-false
Comment: In fact, it suffices to show that for each $p\in \mathbb{Z}\langle X,Y\rangle$, there exists *some* $a,b\in\mathbb{H}$ such that $p(a,b)\neq 0$.  Then the set of such $(a,b)$ will be an open dense subset of $\mathbb{H}^2$ for each fixed $p$, and so by the Baire category theorem you can find a single pair $(a,b)$ that works for every $p$ simultaneously.
Comment: @Bart Michels: It is known that $\pi$ and $e^\pi$ are algebraically independent over $\mathbb{Q}$ and so over $\mathbb{Z}$ also. Isn't it immediate that $$\mathbb{Z}[\pi i,e^\pi j]\cong \mathbb{Z}\langle X,Y\rangle?$$ Here, $\mathbb{Z}[\pi i,e^\pi j]$ is the subring of $\mathbb{H}$ generated by $\{1,\pi i, e^\pi j\}$.
Comment: @Eric Wofsey: I computed for $[a,[b,[a,b]]]$ and I got $-a^2b^2+2(ab)^2-2(ba)^2+b^2a^2$. Then  $[a,[b,[a,b]]]=0$ if and only if $a^2b^2-2(ab)^2=b^2a^2-2(ba)^2$. How can I show this in an 'easy' way? I tried using the form $a+bi+cj+dk$ and also the 2x2 complex matrix form but I don't get the desired result. Maybe I am having some arithmetic errors but It's hard to check because there are too many terms.
Comment: @EricWofsey: Take $a=1+i+j+k$ and $b=1+i+j-k$. Then $[a,[b,[a,b]]]=16i-16j$.
Comment: Oh, sorry, I was wrong about $[a,[b,[a,b]]]$.  One thing that is always true though is that $[a,b]^2$ always commutes with everything, since commutators have no real part.
Comment: @Eric Wofsey: I see. Thank you very much.
Answer: Let $a,b,c,d\in\mathbb{R}$ be algebraically independent over $\mathbb{Q}$, let $x=a+bi$ and let $y=c+dj$.  Then the subring $R\subset\mathbb{H}$ generated by $x$ and $y$ is not Noetherian.
To prove this, consider the left ideal $I\subseteq R$ generated by the elements $xy^n$ for each $n\in\mathbb{N}$.  I claim that for each $n$, $xy^n$ is not in the left ideal generated by the $xy^m$ for $m<n$, and so $I$ cannot be finitely generated.
Note first that $R$ is a subring of the quaternion algebra $S$ over the polynomial ring $\mathbb{Z}[a,b,c,d]$.  We may consider $\mathbb{Z}[a,b,c,d]$ as a bigraded ring where the first degree is respect to $a$ and $b$ and the second degree is with respect to $c$ and $d$.  This then makes $S$ a bigraded ring, with $x$ being homogeneous of bidegree $(1,0)$ and $y$ being homogeneous of bidegree $(0,1)$.  Since $x$ and $y$ are homogeneous, the ring $R$ is bigraded as well.
Now suppose we could write $xy^n$ as an $R$-linear combination of the $xy^m$ for $m<n$.  The only way to take a multiple of $xy^m$ that has the same bidegree as $xy^n$ is to take an integer multiple of $y^{n-m}xy^m$, so this in fact means that we can write $$xy^n=\sum_{m<n}k_my^{n-m}xy^m$$ where each $k_m$ is an integer.  Now consider the homomorphism $S\to\mathbb{H}$ given by mapping $a$ to $0$, $b$ to $1$, $c$ to $1$, and $d$ to $2$ (and $i,j,k$ to themselves).  This turns the equation above into $$i(1+2j)^n=\sum_{m<n}k_m(1+2j)^{n-m}i(1+2j)^m.$$  Multiplying both sides by $-i$ and noting that $-i(u+vj)i=u-vj$, we get $$(1+2j)^n=\sum_{m<n}k_m(1-2j)^{n-m}(1+2j)^m.$$  But this now violates unique factorization in the Gaussian integer ring $\mathbb{Z}[j]$, since the right-hand side is divisible by $1-2j$ and the left-hand side is not.
Comment: Thank you. In this case, can we still not show that $\mathbb{Z}[x,y]\cong \mathbb{Z}\langle X,Y\rangle$?
Comment: @morphy22 If true, they are not isomorphic under $X \mapsto x, Y \mapsto y$, because (as Eric Wofsey's comment says) $[x, [y, [x, y]]] = 0$.


Can python detect which OS is it running under?

Question: Can python detect OS and then contruct a if/else statement for File System.
I would need to replace  C:\CobaltRCX\ in Fn string with the FileSys string.
import os.path, csv
from time import strftime

if os.path.?????:## Windows
   FileSys = r"C:\\working\\"
else:   ##linux
   FileSys = r"\\working\\"

y=(strftime("%y%m%d"))
Fn = (r"C:\\working\\Setup%s.csv" %y)

Comment: http://stackoverflow.com/questions/1854/python-what-os-am-i-running-on
Comment: platform.system() == platform.uname()[0] == 'Windows'
Answer: I usually just use this:
import os
if os.name == 'nt':
    pass # Windows
else:
    pass # other (unix)

edit:
Hopefully in response to your comments:
from time import strftime
import os

if os.name == 'nt': # Windows
    basePath = 'C:\\working\\'
else:
    basePath = '/working/'

Fn = '%sSetup%s.csv' % ( basePath, strftime( '%y%m%d' ) )

Comment: Huh? What do you mean with that?
Comment: Not sure if I answer it with my edit now, but I really don't get it. Please try to explain it using comprehensive english otherwise...
Comment: The Fn string "C:\\working\\Setup%s.csv." How would 2nd variable. 1, the filesys the 2nd y the date. right now I have the date setup, need help with the string for "filesys" yada yada yada "date." thanks
Comment: Yes, of course, sorry. You can also use os.path to concatenate multiple path sequences, if your path becomes more complex than this.
Answer: see here: https://stackoverflow.com/a/58689984/3752715
import platform
plt = platform.system()

if   plt == "Windows":   print("Your system is Windows")
elif plt == "Linux":     print("Your system is Linux")
elif plt == "Darwin":    print("Your system is MacOS")
else:                    print("Unidentified system")

you can see my github repo https://github.com/sk3pp3r/PyOS and use pyos.py script
Answer: Use sys.platform. You can find more information here http://docs.python.org/library/platform.html
Answer: Yes.
>>> import os
>>> os.uname()
('Linux', 'ubuntu', '2.6.32-27-generic', '#49-Ubuntu SMP Thu Dec 2 00:51:09 UTC 2010', 'x86_64')
>>> system = os.uname()
>>> print system[0] + '/' + system[1]
Linux/ubuntu
>>>

Answer: try this one:
    import platform
    platform.uname()

It works both on linux as well as windows. FYI: os.uname() will not work on windows, though it works on linux. Platform is generic.
Answer: Late answer, but if you're trying to determine the path separator, you can use
os.path.sep

Answer: You could look at os.uname
In [12]: os.uname()
Out[12]:
('Darwin',
 'demitasse.local',
 '10.6.0',
 'Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386',
 'i386')

Answer: For most usecases you should use the os.platform module. However if you need a more lean interface, try platinfo.
Answer: Here is what I just created the other day:
CODE:
def GetUserPlatform():
    if sys.platform == 'win32':
        UsrWinVer = str(sys.getwindowsversion().major)
        print("Operating System: Windows " + UsrWinVer)
    else:
        print("Something else")

GetUserPlatform()

OUTPUT:

Operating System: Windows 10
Comment: `platform.system()` is more consistent/reliable than `sys.platform`. See https://stackoverflow.com/a/1857/557406
Answer: import platform
print(platform.uname().system)

This will give you Windows, Linux, etc.


how to unregister a messenger event - Galasoft MVVM

Question: Environment;
WPF, Galasoft MVVM Light
I have a scenario where many in-active xaml views of my application keep listening to a messenger's message and this makes my application to work very slow.
Question;
What is the best way to unregister a message from inactive view? I want only active instance of a view to listen messages.
I tried to unregister it on unloading event of a view, but this unregister it from active instance also.
Thanks,
Asif
Answer: Events aren't expensive, it's the code you execute when the event has been received.
(Re)Design your message event receivers so that they only execute when the view is active.


How can I remove some content types of the admin menu?

Question: I have drupal 6.x and I have installed the module "Admin menu".  I want to know how can I remove some content types of the menu?  I have looked that this menu loads all options of the website and  I only require to remove the some content types of the menu.
Thanks for your help.
Answer: While you can add/remove items from the admin menu from this menu
/admin/build/menu-customize/admin
you really shouldn't, that would be customizing what that module does and anytime they release a new version you would have to make your customization again.
The purpose of that module to to simplify, or make shortcuts to, all of the aspects of administering a Drupal site. If there are certain portions of the admin you don't want users to see, use roles to control which of the links are viewable.
Hope this helps!
Comment: Thanks for your answer.  Your solution is good for my question, but this solutions doesn't allow remove some content types of the "Admin menu" because in the menu the content types are not listed.  I am going to update my question.  Thanks again.
Answer: I do not know if this way is useful for you: In admin_menu.module I have included a php if in admin_menu_tree_output to detect and remove items according links of content types to hide:
for example, I have several content types with the address http://yourdomain.com/admin/content/node-type/testcontenttypeXX. (XX is numbers)
then I have added if(preg_match('/(testcontenttype)/',$serializeData) == false) to admin_menu_tree_output function, seeking in $serializeData = serialize($data['link']); the respective address:
function admin_menu_tree_output($tree) {
  $output = '';

  foreach ($tree as $data) {
    $extra_class = isset($data['link']['localized_options']['extra class']) ? $data['link']['localized_options']['extra class'] : NULL;
    $link = admin_menu_item_link($data['link']);
    $serializeData = serialize($data['link']);

    if ($data['below']) {
            if(preg_match('/(testcontenttype)/',$serializeData) == false){
                $output .= theme_admin_menu_item($link, $data['link']['has_children'], admin_menu_tree_output($data['below']), $data['link']['in_active_trail'], $extra_class);
            }
        }
    else {
        if(preg_match('/(testcontenttype)/',$serializeData) == false){
            $output .= theme_admin_menu_item($link, $data['link']['has_children'], '', $data['link']['in_active_trail'], $extra_class);
        }
    }
  }
  return $output ? "\n
". $output .'
' : '';
}

I hope information be useful.


If equation $f(x)=0$, and it has roots $α$ of degree m, then prove equation $h(x)=f(x+f(x))-f(x)=0$ has roots of degree $2m-1$.

Question:
If equation $f(x)=0$, and it has roots $\alpha$  of degree $m$, then prove equation $h(x)=f(x+f(x))-f(x)=0$ has roots of degree $2m-1$.

When $\alpha$ is root of degree $m$, that means
$$
f(\alpha)=f'(\alpha)=f''(\alpha)= \ldots =f^{(m-1)}(\alpha)=0,f^m(\alpha)\neq 0
$$
I try prove $h(\alpha)=h'(\alpha)=h''(\alpha)= \ldots =h^{(2m-2)}(\alpha)=0$, $h^{(2m-1)}(\alpha)\neq 0$ but i did not find relation between $h(x)$ and $f(x)$ to prove $h^{(2m-2)}(\alpha)=0$.
Comment: Can you say whether of not $f$ is a **polynomial** ?
Comment: Jean Marie: I believe $f$ can be not polynomial. For example, $f(x)=1-\cos(x)$ has root $x=0$ of degree 2, but is not polynomial.
Comment: Is $\alpha$ a root of degree $m$, or are there multiple $\alpha 's$?
Comment: @Paul $\alpha$ a root of degree m
Answer: This is a nice application of Taylor's Theorem: If $f(x)$ is an $m$ times differentiable function at $a$ then
$$f(x)=\sum_{n=0}^{m-1} f^n(a)\frac{(x-a)^n}{n!}+f^m(c)\frac{(x-a)^m}{m!}$$
where $c$ is some value in $(x,a)$ or $(a,x)$ depending on $x$. By your conditions, we have
$$f(x)=f^m(c)\frac{(x-a)^m}{m!}$$
This then implies
$$h(x)=f(x+f(x))-f(x)=\frac{f^m(c)}{m!}(f(x)+x-a)^m-f(x)$$
$$=\frac{f^m(c)}{m!}\left[\left(\frac{f^m(c)}{m!}(x-a)^m+x-a\right)^m-(x-a)^m\right]$$
Now, recall that $f^m(x)$ is continuous and $c\in (x,a)$ (or $(a,x)$) implies
$$\lim_{x\to a}f^m(c)=f^m(a)$$
More importantly, since $f^m(a)\neq 0$ there exists some $\delta>0$ such that $|x-a|<\delta$ implies
$$\frac{1}{2}|f^m(a)|<|f^m(c)|<\frac{3}{2}|f^m(a)|$$
Define
$$Q=\max\left\{\frac{1}{2}f^m(a),\frac{3}{2}f^m(a)\right\}$$
$$q=\min\left\{\frac{1}{2}f^m(a),\frac{3}{2}f^m(a)\right\}$$
Then the statement above can be rewritten as
$$q<f^m(c)<Q$$
for all $|x-a|<\delta$. This implies that for these $x$ we have
$$\frac{q}{m!}<\frac{f^m(c)}{m!}<\frac{Q}{m!}$$
Since this quantity is never $0$, we may as well ignore it. Thus, our problem simplifies to showing that
$$g(x)=\left(\frac{f^m(c)}{m!}(x-a)^m+x-a\right)^m-(x-a)^m$$
has a root at $a$ of degree $2m-1$. This expands to
$$=\sum_{n=0}^m \binom{m}{n}\left(\frac{f^m(c)}{m!}\right)^n(x-a)^{nm+m-n}-(x-a)^m$$
$$=\sum_{n=1}^m \binom{m}{n}\left(\frac{f^m(c)}{m!}\right)^n(x-a)^{nm+m-n}+\binom{m}{0}\left(\frac{K}{m!}\right)^0(x-a)^{0\cdot m+m-0}-(x-a)^m$$
$$=\sum_{n=1}^m \binom{m}{n}\left(\frac{f^m(c)}{m!}\right)^n(x-a)^{nm+m-n}$$
To prove that this expression indeed has a root of order $2m-1$, notice that
$$\lim_{x\to a}\frac{g(x)}{(x-a)^{2m-1}}=\lim_{x\to a}\sum_{n=1}^m \binom{m}{n}\left(\frac{f^m(c)}{m!}\right)^n(x-a)^{nm+m-n-2m+1}$$
$$=\lim_{x\to a}\left[\sum_{n=2}^m \binom{m}{n}\left(\frac{f^m(c)}{m!}\right)^n(x-a)^{nm+m-n-2m+1}+m\left(\frac{f^m(c)}{m!}\right)\right]$$
Since $2\leq n\leq m$ implies
$$nm+m-n-2m+1\geq m-n+1\geq 1$$
the expression above becomes
$$\lim_{x\to a}m\left(\frac{f^m(c)}{m!}\right)=\frac{f^m(a)}{(m-1)!}\neq 0$$
which is both finite and non-zero as desired.
Comment: We have $-|\frac12 f^m(a) |<f^m(c)-f^m(a)<|\frac12 f^m(a)|$. Here, $| \frac12
  f^m(a)|$ is being used as $\epsilon$. Then there's two cases whether $ f^m(a)$ is negative or positive respectively
Comment: You should correct in particular the first expression where the $f(a)$ terms should be $f^{(n)}(a)$ and the (Lagrange) remainder should be $f^{(m+1)}$. The fact that it is $f^{(m+1)}$ and not $f^{(m)}$ has an impact on the following which I have a hard time to follow...
Comment: @JeanMarie You are correct, and in fact that correction simplifies the logic quite a bit which is nice.
Comment: @QC_QAOA In the first expression $f(a)$ isn't correct. In Taylor expression we have $f^{n}(a)$, and how did you write $f(x)=\frac{f^{(m)}(c)}{m!}(x-a)^m$?
Comment: It should be $f^n(a)$ not $f(a)$, thanks. That form of $f(x)$ follows since $f^n(a)=0$ for all $0\leq n<m$
Comment: @QC_QAOA It is clear from the definition of limit $f^{m}(\alpha)$ that $|f^{m}(c)|\leq \epsilon +|f^{m}(\alpha)|$.Excuse me, how did you find $\frac{1}{2}$ and $\frac{3}{2}$?
Answer: Let reduce claim to case $\alpha=0$ to shorten next record:
Let $x=\alpha$ is root of $f(x)$ of degree $m$. Consider $g(x)=f(\alpha+x)$. Then $0$ is root of $g(x)$ of degree $m$. And consider $i(x)=h(\alpha+x)$. If $x=\alpha$ is root of $h(x)$ of degree $2m-1$, then $x=0$ is root of $i(x)$ of degree $2m-1$ and vice versa. Note, that $$i(x)=f(\alpha+x+f(\alpha+x))-f(\alpha+x)=g(x+g(x))-g(x)$$
Then it is enough to prove the claim for case $\alpha=0$.
Let consider case $x=0$ is root of $f(x)$ of degree $m$:
$$h(x)=f(x+f(x))-f(x)$$
$$\lim_{x\to 0}\frac{h(x)}{x^{2m-1}}=\lim_{x\to 0}\frac{f(x+f(x))-f(x)}{x^{2m-1}}=\\
=\lim_{x\to 0}\frac{f(x+f(x))-f(x)}{f(x)}\frac{f(x)}{x^{2m-1}}=\\
=\lim_{x\to 0}\left(\lim_{t\to 0}\frac{f(x+t)-f(x)}{t}\right)\frac{f(x)}{x^{2m-1}}=\\
\lim_{x\to 0}\frac{f(x)}{x^m}\frac{f'(x)}{x^{m-1}}$$
Let $f^{(m)}(0)=C$, $C\neq 0$, then $$\lim_{x\to 0}\frac{f(x)}{x^m}=\lim_{x\to 0}\frac{f'(x)}{mx^{m-1}}=\frac{C}{m!}$$
$$\lim_{x\to 0}\frac{h(x)}{x^{2m-1}}=\frac{C}{m!} \frac{C}{(m-1)!}=\frac{C^2}{m! (m-1)!}\neq 0$$
Existence of this limit requires $h(0)=0$, $h^{(k)}(0)=0$ for $1\leq k \leq 2m-2$. Also this limit is equal to $\frac{h^{(2m-1)}(0)}{(2m-1)!}$ and this quantity is not equal to zero. Then $x=0$ is root of $h(x)$ of degree $2m-1$.
Comment: @avatar It should be $g(x)=f(x-\alpha)$ not $g(x)=f(x+\alpha)$ to 0 is root of $g(x)$ of degree m.
Comment: Nope: If $g(x)=f(x-\alpha)$, then $g(0)=f(-\alpha)$ which may be not zero. If $g(x)=f(x+\alpha)$, then $g(0)=f(\alpha)$ and $g^{(k)}(0)=f^{(k)}(\alpha)$, when such derivative exists.


What does a single square bracket next to a single note mean?

Question: I just stumbled on a bit of notation in a music score, and I'm stumped as to what it means. It's a single square bracket, spanning the whole staff, to the left of a single note.

This is measure 58 of Fandango, by Padre Antonio Soler, arr. Fernand Vera, for guitar duo. The piece is in D minor.
There are also similar brackets in measures 63, 64 and 65,

as well as 98 and 125.
What does the bracket mean?
Comment: Well... These examples also seem to suggest barres. The first three being on fret 10, for F and A on strings 3 and 2, but with the 3rd finger marking on the wrong note in those in bars 64 and 65 (one note early). The last example is just a fret 8 barre for the G and C. The fact that musical markings, barlines and notes often 'collide' here, suggests that this has not been carefully edited, and is likely to have mistakes, which is why I think the fret 4 barre was suggested in the first example...
Comment: Just to avoid any confusion: the question was originally posted with just the first musical excerpt (with no key sig.) The next two musical excerpts were then added; the comment above is a response to the these excerpts!
Answer: Must simply be notation for a barre across the fourth fret, as this would also be for the subsequent G#. Admittedly, this is not the most conventional notation, but it is certainly valid.
EDIT: this kind of bracket is commonly used in bowed string (eg. violin) music, to denote double-stopped notes, which may sometimes be with the same finger, and so are an equivalent of barres.  (Here, of course, the notes aren't played together though - thanks for pointing this out @Alexander Troup.)
Comment: Apologies, I should have made this clear; the key is D minor so the B should be assumed to be flat, and on the third fret. I'm not particularly sure how to interpret the IV in light of that.
Comment: Ah! Well in that case it makes no sense! I think the most obvious explanation is that there is an error in the music here. Either it is supposed to be a B natural, or the fingerings have been put in afterwards and the person putting fingerings in has not 'clocked' the Bb. I followed your link to the original, and had a very brief look, it appears this may not be conventionally edited music...? This may help to explain the error, if there is one, but of course conventionally published and edited music often has mistakes too... Sorry for not being able to be definitive.
Comment: I feel it's unlikely to be a typo; the Bb also appears in [many of these other versions](http://imslp.org/wiki/Fandango,_R.146_(Soler,_Antonio)). I'm not sure what to make of the typesetting; it was very likely made by the arranger himself, but I do find it strange that he would include non-standard notation in his PhD thesis.
Comment: Exactly, I don't think he's used non-standard notation, I think he's just made a mistake, and fingered it as though it is a B natural. The only other explanation I could think of is that the Bb is played on string 4, but a fret 4 barre is being prepared for notes in the next bar of music (I haven't looked at the next bar...) I reckon it's probably a mistake though...
Comment: Yes, the next bar does have a bar on V. I guess it can be taken to mean to bar the third fret in preparation to shift it to V. I'll look more carefully at the other occurrences to see if this fits.
Comment: I think you're right about using a barre, see http://justinguitarcommunity.com/index.php?topic=32543.0 and http://www.dolmetsch.com/musicalsymbols.htm (search square bracket in page), but it might be worth clarifying that here it's two separate notes and the notation still stands, rather than a double stop where the 2 notes would be played simultaneously :) Great job on the answer, I learned my cool thing for today :D


Startup no .net core 2.2 e .net core 3.1

Question: Estou fazendo o curso de MVC core do desenvolvedor.io, mas no curso é usado o .net core 2.2 e estou usando a versão 3.1. Na criação de um projeto MVC do zero o código de configuração das rotas no Startup.cs do .netcore 2.2 é:
app.UseMvc(routes =>
{
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");

    //routes.MapRoute(
    //    name: "default",
    //    template: "{controller=Home}/{action=Index}/{id?}"
    //    )
});

E no .net core 3.1 é:
app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/", async context =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
});

Tentei usar o código do 2.2 no 3.1, mas não está funcionando, porque o código já está depreciado. Eu gostaria de saber a diferença entre os dois códigos, por exemplo, pra que eu uso o endpoints.MapGet no 3.1. Qual foi a mudança que fizeram entre o .net core 2.2 e 3.1 no Startup.cs?
Answer: Olá, na versão do Core 3.0 ou 3.1 a configuração é
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });

O MapGet método é usado para definir um ponto final. Um ponto final é algo que pode ser:
Selecionado, combinando o método URL e HTTP.
Você pode ler mais sobre o assunto aqui:
https://aregcode.com/blog/2019/dotnetcore-understanding-aspnet-endpoint-routing/


How do I actually play higher octaves in flute?

Question: Flute newbie here. I'm learning to read notes and play them on the flute (Western concert flute, closed buttons). I find many sources for fingerings of the notes in different octaves. Sometimes they are contradicting and sometimes the fingerings are the same for different octaves. I also know that I can change the octave by changing the air speed. I'm confused about that.
If I see a low C and a high C on the note sheet, how do I actually play them? Do I change the fingering? Or do I change the air speed?
Some youtube videos show fingerings for higher octaves, and when I try them they sound differently, because I have a different air speed.
Some other youtube videos mention that the step between C and D is very hard, because you have to move almost all fingers. But that's not true, right? I can also change the air speed and have only a minor change in the fingering?!
Comment: @CarlWitthoft  Yes, the answers there should be checked out too.
Answer: In order to answer your questions completely, we must understand a little about how a flute works. Basically (leaving out a few keys for the moment) the modern flute plays the notes in the first octave of its range, from c' (middle C) to c'' (an octave higher), by successively opening fingerholes, effectively shortening the playing length of the tube, and sounding what's called the fundamental tone (also known as the first harmonic).  This is the lowest sound you can get for any given fingering.
Starting with the next tone higher from c'', d'', the sound is produced not by playing the first harmonic, but rather the second, which is twice the frequency of the first, or an octave higher.  That's why you have to move so many fingers going from c'' to d'': you're going from the highest note of the fundamentals, with all fingerholes open, to the lowest of the second harmonics, with almost all fingers down.  Thus, there's no way to get from c'' to d'' with a minor change in fingering- unless you use the trill keys, which are there for exactly that purpose.
You are right about the speed of the air.  The faster and narrower the airstream, the more likely that you will overblow: produce a higher harmonic than the fundamental.  You can do this by simply blowing harder, or by narrowing your lips.
A good way of practicing this is by taking a note somewhere in the middle of the octave- say, G, and playing first a g', then a g'', using only your lips to go up and down the octave.
I hope this helps.
Comment: This is a good technical answer.  I propose that the "root cause" answer is, as always,  "get a teacher and have them observe what you are doing."
Comment: @CarlWitthoft - yes, that should go without saying.  But it doesn't hurt to repeat it.  Good teachers are what get us further.
Answer: I'm also fairly new to flute, and the exercise my teacher gave me was to hold a piece of paper (or an envelope held sideways) and let it hang down about a foot in front of your mouth.  Then make your embrasure and blow.  The goal is to direct the stream of air from the bottom of the piece of paper to the top and back again.  That's the mechanism to go from (for example) G (second line) to G (top of the staff.)  It was hard for me at first.


USE MAX( ) WITH SELECT column_name WITHOUT GROUP BY

Question: I want to SELECT MAX wickets with the NAME
SELECT NAME, MAX(WICKETS) FROM BOWLER;
but get this error
not a single-group group function
what should I do;
Comment: Why don't you want to use a group-by clause? There is an analytic version of max but if that's all you are selecting then you'd just see the same data repeated multiple times for each name.
Comment: SELECT NAME, MAX(WICKETS) FROM BOWLER group by Name
Answer: Use an analytic function:
SELECT name,
       MAX(wickets) OVER () AS global_maximum,
       MAX(wickets) OVER (PARTITION BY name) AS name_maximum
FROM   bowler;

Which, for the sample data:
CREATE TABLE bowler (name, match_id, wickets) AS
SELECT 'Alice', 1, 0 FROM DUAL UNION ALL
SELECT 'Alice', 2, 3 FROM DUAL UNION ALL
SELECT 'Alice', 3, 4 FROM DUAL UNION ALL
SELECT 'Beryl', 1, 2 FROM DUAL UNION ALL
SELECT 'Beryl', 2, 1 FROM DUAL UNION ALL
SELECT 'Beryl', 3, 0 FROM DUAL;

Outputs:

NAME
GLOBAL_MAXIMUM
NAME_MAXIMUM

Alice
4
4

Alice
4
4

Alice
4
4

Beryl
4
2

Beryl
4
2

Beryl
4
2

If you want to filter to only get the row that is a maximum for the name then:
SELECT name,
       match_id,
       global_maximum,
       name_maximum
FROM   (
  SELECT name,
         match_id,
         wickets,
         MAX(wickets) OVER () AS global_maximum,
         MAX(wickets) OVER (PARTITION BY name) AS name_maximum
  FROM   bowler
)
WHERE wickets = name_maximum;

Which outputs:

NAME
MATCH_ID
GLOBAL_MAXIMUM
NAME_MAXIMUM

Alice
3
4
4

Beryl
1
4
2

db<>fiddle here
Answer: Here's sample table:
SQL> select ename, sal from emp order by sal desc;

ENAME             SAL
---------- ----------
KING             5750       --> I presume you want KING, as his salary
FORD             3450           is greatest (i.e. MAX) in that data set
SCOTT            3450
JONES            3421
<snip>

If that's so, then
SQL> select a.ename, a.sal
  2  from emp a
  3  where a.sal = (select max(b.sal) from emp b);

ENAME             SAL
---------- ----------
KING             5750

SQL>

Query you posted presumes that there are several rows per each name, and you want to get MAX value of the wickets column per each name without group by. Why would you want that? GROUP BY is what you should be using, then.


Why does this sequence not oscillate?

Question: I'm confused on why this sequence converges to 0 rather than diverge because of an oscillating series, since the result would be negative if n is odd and positive if n is even
Edit for the downvote: I apologize that my question was simple, but I genuinely thought it through for a while and could not understand. I was hoping I could ask the smart and giving people of Stack Exchange in order to enlighten me.
Comment: It does oscillate between positive and negative terms. However, since it oscillates between numbers that get smaller and smaller in absolute value as $n$ increases, it converges to $0$.
Comment: Just guessing, not the downvoter: The downvote probably reflects not the simplicity of the question, but the fact that the mathematical content is an image, which isn't [accessible](https://en.wikipedia.org/wiki/Web_accessibility). Typing the content of the question in MathJaX would be welcome, in any case. (The downvoter may also have taken exception to the use of "series" when "sequence" was meant; the terms are not interchangeable here.)
Answer: For $n>0$, we have
$$a_{2n}=\frac{2n}{8n^3+1}>0$$
and
$$a_{2n+1}=-\frac{2n+1}{(2n+1)^3+1}<0$$
thus
$$\lim_{n\to+\infty}a_{2n}=0$$
and
$$\lim_{n\to+\infty}a_{2n+1}=0$$
So,
$$\lim_{n\to+\infty}a_n=0.$$
Answer: Notice we have: If $|a_n| \to 0$, then $a_n \to 0$ because of
$$ - |a_n| \leq a_n \leq |a_n| $$
and the squeeze rule

Why does this sequence not oscillate?