Types of tools to automate "tape-like" audio manipulation

Question: [To anyone who recognizes the following setup as shamelessly derived from musique concrète and Cage's music: apologies for the gross simplifications]
Setup:
I have a project in which I need to programmatically read audio samples, possibly manipulate their features (applying envelopes, reversing, reverb, speed up/down, etc), and combine them in sequences.
Basically, I need to programmatically control the effects I would have available in a tool like Audacity or its equivalents.
Question: Which types of tool could I look at to achieve this? I have briefly looked into supercollider and pure data (= read a couple of tutorials), but they seem  mainly oriented to sound synthesis, even though reading samples from files is possible. The sound synthesis orientation seems also to introduce a lot of unneeded complexity for a project as simple as mine. Besides, pure data (and its siblings) are visually oriented, and I would prefer a text-based environment if possible.
Perhaps there are sound manipulation libraries that would allow access to "Audacity-like" effects from within a standard programming language (a tool  that would be like a "Audacity bindings" for language X, for lack of a better term)?
Comment: This question is off topic here because we have decided not to discuss recommendations for hardware or software. You might try it over at softwarerecs.stackexchange.com instead.
Comment: do you need any real-time capabilities, or is this all a question of doing offline processing?
Comment: Stefano - would you be happy with recommendations for a *type* of tool, rather than specific tools?
Comment: @topomorto: I only need offline processing. Also, suggestions about the recommended class of tools are welcome. in fact they are even more welcome than suggestions about specific tools. I basically need to know where to look
Comment: I've edited the question to make that clear - hope the edit's OK. (questions asking for suggestions for specific tools are off topic here - but hopefully as now worded it's OK.)
Answer: One way to go would be simply to use a general-purpose programming language - almost any will do - to read the audio samples in, do any processing, and write out the piece to disk. Reading and writing WAV format is quite straightforward even if you need to parse it yourself. Some of the manipulations you mention - applying envelopes, slowing audio down - are very easy to code; convolution reverb is fairly easy. Speeding audio up can be a bit more difficult as you have to do it in a way that avoids aliasing. http://musicdsp.org/ is one resource for audio algorithms you can implement yourself.
Of course you might prefer to get a third-party audio library to do some of the work for you so you don't have to do all this low-level work. The choice of these would depend on the language you are using.
Another option would be a language that has good audio support built in to its standard libraries - for example JavaScript is actually pretty capable with audio if you use it in a browser that supports the Web Audio API. This API supports all the things you've mentioned, and you could even get some interesting interactive things happening in the web browser (and of course put your interactive works on the web!).
Then we get to dedicated audio programming languages, which are often dialects of general programming languages with audio library support built in as standard. One that I saw a great demo of recently is Sonic PI (which uses supercollider under the hood) and is oriented around live coding - though you can just as easily render your work to disk. This would be one of my  personal recommendations for a straightforward starting point, though I'm not an expert on it.
You might also consider using some command-line audio tools and writing a batch / PowerShell / other script file to drive them to do some processing. Sox is an example, and rubberband is an interesting little tool too.
Comment: Thanks. That's exactly what I was looking for: a taxonomy of available toot types (with the correct terms to enable search).


If $A$ is diagonalisable, why $\dim\big(\ker(A-\lambda I)\big)=\dim\big(\ker(PAP^{-1}-\lambda I)\big)$?

Question: Let $A$ a matrix $n\times n$. If $A$ is diagonalizable, why $$\dim\big(\ker(A-\lambda I)\big)=\dim\big(\ker(PAP^{-1}-\lambda I)\big)$$
whenever $P$ is invertible ?
This result indeed makes sense, but I'm unable to prove it.
Comment: @Martigan: To have same eigenvalue is not sufficient, e.g. $$\begin{pmatrix}1&0\\0&1\end{pmatrix}\quad \text{and}\quad \begin{pmatrix}1&2\\0&1\end{pmatrix},$$ have same eigen value, but the dimension of there eigenspace associated to the eigenvalue 1 are not the same.
Comment: What are your thoughts on the problem?
Comment: Hint: $A$ and $PAP^{-1}$, with $P$ invertible, have the same eigenvalues...
Comment: @Surb Clearly this is not enough... But it was only a hint, not the solution. The idea was also to make him work. They have the same eigenspaces as well, but it was really too muc information IMO.
Answer: Note that $PAP^{-1}-\lambda I = P(A - \lambda I) P^{-1}$, so that $A-\lambda I$ and $PAP^{-1}-\lambda I$ are similar matrices. Hence their kernels are isomorphic, and in particular, they have the same dimension.
This follows from the following general lemma:

Lemma. Let $M$ be an $n \times n$ matrix and let $P$ be an invertible $n \times n$ matrix. There is a linear isomorphism $\ker M \overset{\cong}{\longrightarrow} \ker PMP^{-1}$.

To prove this, note that the map $v \mapsto Pv$ is well-defined (since if $Av=0$ then $PAP^{-1}Pv=0$), linear and invertible, hence is a linear isomorphism.
Setting $M=A-\lambda I$ gives the result you desire.
Diagonalisability of $A$ was not a necessary hypothesis.
Answer: This is just another way to state that similar matrices have the same dimension eigenspaces.
To prove it we first note that $=PAP^{-1} - \lambda I = P(A- \lambda I)P^{-1}$.
Then we use the fact that $P$ is invertible to get that $PBP^{-1}v=0 \iff BP^{-1}v = 0 \iff P^{-1}v \in \ker(B)$.
Finally we use again that $P$ is invertible to deduce $ \dim (P^{-1} (\ker(B)) ) = \dim(\ker(B))$.
Answer: Note that $PAP^{-1} - \lambda I = P(A - \lambda I)P^{-1}$. Thus, if $\{v_1,...v_n\}$ is base for $Ker(A - \lambda I)$,since $P$ is isomorphism,  $\{Pv_1,...Pv_n\}$ is L.I.. That implies  $dim(Ker(PAP^{-1} - \lambda I)) \geq dim(Ker(A - \lambda I))$. By other side, if $\{w_1,...,w_m\}$ is base of $Ker(PAP^{-1} - \lambda I)$ that implies that $(A - \lambda I)P^{-1}w_i = 0$, for $i=1,...,m$ and therefore  $\{P^{-1}w_1,...,P^{-1}w_m\} \subset Ker(A - \lambda I)$  and because $\{P^{-1}w_1,...,P^{-1}w_m\}$ is L.I., we have that $dim(Ker(PAP^{-1} - \lambda I)) \leq dim(Ker(A - \lambda I))$.


Port based virtual hosts in CentOS 5.5 / Webmin

Question: I am trying to setup virtual hosts in the respect that everything is in the /var/www/html/ root folder however, I am trying to setup folders within that and then setup port related url's.

myserverip - Would get the local intranet
myserverip:8181 - Would get my personal website
myserverip:8080 - Would get the intranet blog etc

I tried setting these up through webmin, however they just won't resolve. I disabled the Linux Firewall, as it's on a local intranet and will NEVER have remote access / public access from the internet. Our local intranet is completely locked down.
Does anyone have any suggestions with this as I have got to the point where I am just clutching at straws :(
Thanks for your time, if I manage to get any further, I will edit this post so that you have further information. Please understand I am a server newbie :(.

Below is what is inside the httpd.conf file
Listen 80
Listen 8080
Listen 8081

NameVirtualHost *:80
NameVirtualHost *:8080
NameVirtualHost *:8081

<VirtualHost *:80>
        ServerName SERVERIPHERE
        DocumentRoot /var/www/html/
</VirtualHost>

<VirtualHost *:8080>
        ServerName SERVERIPHERE
        DocumentRoot /var/www/html/example2
</VirtualHost>

<VirtualHost *:8081>
        ServerName SERVERIPHERE
        DocumentRoot /var/www/html/example3
</VirtualHost>

And this is the error returned
Starting httpd: (13)Permission denied: make_sock: could not bind to address [::]:8081
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:8081
no listening sockets available, shutting down
Unable to open logs

Comment: Does the IP address you are using match the one shown by ifconfig? If so, can you ping it?
Answer: I think it could be selinux in enforcing mode, httpd is not allowed to listen to port 8081, check /var/log/audit/audit.log
Comment: Good point - type "getenforce" and see if it says enforcing
Comment: Yes it's Enforcing, so how would I go about stopping that?
Comment: No worries, I actually went to the box and changed it via the gui... Will let you know shortly IF it has fixed the issue :) Thanks
Comment: Yep... That fixed it guys... Thank you so much... I can't 1 up at the minute due to newbie status.
Comment: It doesn't want to work on any other port either :/

Only seem to work on the default :80 port and :8080...


Integer to Roman while loop explanation-Python

Question: I am trying to understand the while loop and sorted call in the program to convert a number to Roman numerals below.
numerals = { 1 : "I", 4 : "IV", 5 : "V", 9 : "IX", 10 : "X", 40 : "XL",
             50 : "L", 90 : "XC", 100 : "C", 400 : "CD", 500 : "D", 900 : "CM", 1000 : "M" }

num = 58  # LVIII

roman = ''

for k, v in sorted(numerals.items(), reverse=True):
    while num >= k:
        roman += v
        num -= k

print(roman)

Questions:
1) Why doesn't the code work if numerals.items() is used instead of sorted(numerals.items(), reverse=True)? (For example, 58 would result in IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII instead of LVIII.) When using a breakpoint on that line it looks like the order remains same both with and without sorted.
2) The first Roman numeral is L. Why? When debugging I noticed it starts counting down from 1000. When it reaches 50, I see that roman == 'L'. The code tests if num >= k. 1000 (M) is also greater than 58. Why does the condition num >= k result in L being the first digit?
Comment: Have you sat down and worked out what the code does step by step? Use pencil and paper or gratuitous `print`s if necessary. You need to develop the ability to do so if you're going to write code. Others answering this question for you are doing you no favors. If you already understand *what* the code does, then you need to be more specific about what particular behavior confuses or surprises you. Most likely, the answer to why the language behaves those specific ways is already available somewhere.
Comment: `the code does not work unless "sorted(numerals.items(), reverse=True)" is used` What does it do without it? Where do you put it? Also, AFAICT, `num=58 answer> LVIII` is invalid syntax. Was `answer> LVIII` supposed to be a comment (beginning with `#`)?
Comment: LVIII is just for reference in case anyone is running the code. Without using sorted  it prints IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII. To get LVIII need to use for k,v in sorted(numerals.items(), reverse=True):
Answer: Without sorted, the loop would begin with 1, 'I'. It would then be used as many times as possible. In this case, this would result in 58 Is. (It would then continue onto 4, 'IV', 5, 'V', etc., but num would be 0.) With sorted, the loop begins with 1000, 'M', then 900, 'CM', etc. (The reason the sorting was not visible in the debugger is that sorted returns a new list.) When it reaches 50, 'L', the while loop tests if 58 >= 50 (you got the order wrong in your observation), which is true. It then sets num to 8 and roman to 'L'. It then continues to loop to get the remaining digits.
Answer:
sorted(numerals.items(), reverse=True) not only means sorted, but also means sorted in reverse. The key point is reverse=True. Because we must compare to the largest Roman first. From M to I, not from I to M.
"The logic says num>=k. 1000,M is also greater than num 58." I think you have misunderstanding here. for while num>=k: it find less or equal than num, not large, so L will be the first one.

Hope that will help you.
Comment: `dict.items()` is not guaranteed to have any order. Your answer is incorrect.
Comment: Great. It is clear now. The problem of not sorting and starting the comparison from largest to smallest is it will pick the IIII values as match. Thank You.
Comment: @jpmc26, sorry about that, fixed it.
Answer: Python3:
# num=58# answer> LVIII

num = 58
numerals = { 1 : "I", 4 : "IV", 5 : "V", 9 : "IX", 10 : "X", 40 : "XL",
        50 : "L", 90 : "XC", 100 : "C", 400 : "CD", 500 : "D", 900 : "CM", 1000 : "M" }
roman=''
#reserve numerals
for k, v in sorted(numerals.items(), reverse=True):
    while num>=k:
        roman=roman+v
        num = num - k
print(roman)

Comment: How does this answer the question?
Comment: I updated the example code, that is working. I think this is same as @recnac
Comment: That is not what was asked. I think they did have working code.
Comment: The question is updated to `for k, v in sorted(numerals.items(), reverse=True):`. Of course, now, the question 's code is no problem.


Hard-copy (printed) MFA tokens for AWS

Question: Is it possible to have hard-copy (i.e. printed out on paper) MFA tokens for AWS?
For Google's MFA, you can print out around 10 numbers to use in a disaster-type situation (say you are using an MFA app on your phone and you lose your phone or can't get a signal for some reason). Does a similar option exist for AWS? I can't seem to find it anywhere in the documentation.
I'm aware that there are digital MFA devices that you can keep in your wallet, but I feel like at some point, you really do need a backup solution in a form that isn't susceptible to electronic failure of one kind or another.
This would be for an IAM, by the way, not the master account.
Comment: You could print out the QR code you sync your MFA against, I guess?
Answer: I always print the QR code and keep that physically secure. That makes it easier to enrol multiple/new devices and also resolves the issue of losing a device.
From a security standpoint I don't feel this is substantially less secure than backup codes. The only area where it's weaker is that if an attacker manages to obtain your printed backup codes without you realising they are limited in the number of times they can use it - although by that point the damage is probably already done.

Hard-copy (printed) MFA tokens for AWS


For key and value in file json

Question: FILE json
<code>{
  "102": "868",
  "103": "8648",
  "104": "868",
  "105": "8468",
  "1026": "8468",
  "107": "8648",
  "108": "85468",
}
</code>
I want to make a loop for and get the key and value
Comment: That file isn't valid JSON -- it won't parse because of the trailing `,`. And what have you tried / how much do you know already? (Do you know how to iterate over key/value pairs from a standard Python data structure, so the only problem is converting from JSON to a regular Python object? Then ask only about the specific problem you're having with that conversion. Do you *not* know how to iterate over key/value pairs in Python dictionaries? Then focus on that alone without being unnecessarily specific to JSON).
Comment: Looping through key and value is a basic technique available from any tutorial on Python dictionaries (dict).  What you posted is a dict, not JSON.  We expect you to do your own research before posting here.
Comment: What's stopping you?  What specific question do you have?
Answer: looool [in python3.7]
<code>import json
with open(path_to_your_json_file) as f:
    d = json.load(f)
    for k in d:
        print(k, d[k])
</code>

For key and value in file json


Cannot fetch data from Rails at ReactJS

Question: I am using front-end source is ReactJS at port 5555, and my back-end is Rails at port 8888. I was trying to fetch data from Rails at React by using:
const url = 'http://localhost:8888/problems';
fetch(url)
  .then(res => {
    res.json();
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

but I was received the message:
Access to fetch at 'http://localhost:8888/problems' from origin 'http://localhost:5555' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have no idea about that error. Please help me to fix it
Comment: It's nothing to do with reactjs. It's CORS problem, check how to handle it in rails: https://stackoverflow.com/questions/29751115/how-to-enable-cors-in-rails-4-app
Comment: You are getting a CORS error from the browser. Your Rails server needs to set the header `Access-Control-Allow-Origin: *`. This is because your webpage and server are technically different origins due to the different ports.
Comment: @Benjamin Where i should set that?
Answer: Read more about CORS
to fix this, you need rack-cors gem in your Gemfile gem 'rack-cors'
in config/application.rb
# Rails 5

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end

# Rails 3/4

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end

that would suffice for your local right now. You will need to modify it if you deploy your code.
Answer: As comment said, this is a CORS error.
You could fix it according to this question allow-anything-through-cors-policy

Cannot fetch data from Rails at ReactJS


Do the basketball "ribs" have a specific purpose?

Question: I just wonder if the typical black ribs (small lines) have any specific purpose (like improving grip, aerodynamics or something related to dribbling) or they are just cosmetic detail (I guess inherited from leather balls).
Are they mentioned in any of the rules?
Answer: TL;DR:  they cover up the seams between the panels that make up the ball.
The internet (other Q&A sites) think that the lines and the bumps are there to improve grip.  But I don't see any references to rules in those.  That seems to be players' impressions.
The NBA Rulebook has a section on RULE NO. 1: Court Dimensions – Equipment.  Section II.f.1 says:

The ball shall be an officially approved NBA ball between 7 ½ and 8 ½ pounds pressure.

It doesn't explain what is necessary to "be an officially approved NBA ball".  And that is the most relevant quote (e.g. I don't think that knowing that there must be at least nine balls available helps us).
The NCAA rules PDF has Rule 1, Section 16, Articles

The ball shall be spherical. Spherical shall be defined as a round body
whose surface at all points is equidistant from the center, except at the approved
black rubber ribs (channels and/or seams).

The width of the black rubber rib (channels and/or seams) shall not
exceed 1/4 inch.

From this, we get that the ribs are seams (and also known as channels).
More search finds that Spalding was the official NBA ball provider:

...the Spalding NBA Official Game Ball. For over three decades, Spalding has worked with the league to create the gold standard basketball. This ball is designed to feel like second nature in the hands of the legends who wield it. Strictly made for the hardwood, it has a full grain leather construction that turns butter-soft once broken in.

Well, that wasn't helpful.  It does provide us with pictures of the ball.
Now Wilson is the official NBA ball provider.  The ball is very similar, replacing Spalding with Wilson.  Note that Wilson made the official game ball prior to Spalding as well (before the previously mentioned three decades).
Both balls share the black lines.  The orange sections are covered with bumps (called pebbling).  They differ in that the Wilson puts the writing on top of bumps as well, while the Spalding does not (its writing is smooth, like the ribs/channels).
How a basketball is made.  Key takeaway:  the lines/ribs (called channels) are overtop the seams of the cover:

6 A hand-operated punch press—equipped with specially designed and tooled dies—punches the rubber outlines to create six separate panels per ball. The same die has a hole that is punched in one of the six panels to make an opening for the air tube. The excess rubber surrounding the panels is lifted off the line and deposited in a bin for recycling.
7 The assembly worker picks up the six panels for a single ball in a specific order and carries them to the vulcanizer. The interior of the vulcanizer for this process is different from the one for the bladders. It is form-fitted to hold the six panels, to create the channels between the panels, and to add any embossed information. The assembler fits the panels individually into specified sections in the vulcanizer. A bladder/carcass is taken off the overhead conveyor, covered with a coating of glue, and placed inside the chamber of the vulcanizer that is lined with the cover panels. When the ball emerges from the vulcanizer, most of its surface is still smooth (there are no bumps, called pebbling), but the channels and any embossing are formed into the surface.

This suggests that while they may help with grip (as many players believe), the primary purpose is simply to hide the seams between the panels.
The NBA and the ball manufacturers (Wilson and Spalding) have worked together over time to determine the construction of the ball.  But they do not seem to publicly describe the characteristics of the ball, although they presumably have some private agreement that specifies the lines/ribs, pebbling, size, and materials.
Note that even if they are primarily to hide the seams, that doesn't mean that they don't improve the grip.  The NBA, et. al. may have chosen this particular way to hide the seams because it helps with the grip.  The seams on a volleyball are done differently.  Possibly because a volleyball gets struck rather than held during active play.  And apparently basketballs used to have lacing, like gridiron (American-rules) football still does.  Search for Spalding 125th anniversary basketball for examples (Spalding issued a remake of the 1894 ball in 2019).


What can you say for sure about an individual after studying a sample of the population?

Question: For example, if 80% of my sample of people living in a certain town is bald, what are the chances that an individual from that town is bald?
Edit: This is all fictional, But let me be more precise. Let's say I have a sample (n = 350) of the population of a town (N = 5000). In this sample I find that 80% are bald. Can I say that John, who lives in this town has an 80% chance of being bald?
Comment: I am sure the probability is within 0 and 1 range.
Comment: Can you be more precise what you mean by "for sure"? How large is your sample and how large is the town? How was the sample drawn?
Comment: I've edited my question
Comment: This still does not answer what "for sure" means. Moreover, what do you mean with chance? Some frequentists would state that the probability of a unique event (John being bald) is either 0 or 1 and nothing in between, others have a broader or more wishy-washy (depending on your preferences) definition of chance.
Answer: If 80% in your sample is bald, then that suggests that your sample consists overwhelmingly of men over 50 years old. I suspect that that is extremely far removed from your population. With such an extreme bias, I would say that pretty much nothing can be learned from that sample.
Comment: The sample needs to say something about the population. If the sample is extremely biased then that is the end of the end of the story, regardless of whether that story is fictional or not. In real world analysis these kinds of plausibility checks are crucial. That is the point of my answer: in your example I would not be willing to make such a statement, because I strongly distrust the sample. I might be convinced if the process of sampling was clearly documented and sound *and* there is a substantive reason for that high proportion, e.g. it is a settlement of cancer patients.
Comment: This is a hypothetical question, it is just an example - I'd like to know if and what can I infer about an individual?
Answer: That's a great question. I don't think there is much you can say by drawing from one sample of the population and making an inference because we don't know the complete sample space. For example if we toss 3 coins, we know that there can be 8 outcomes and not all are equally likely, for example probability of a HHH is only 1/8. However, if I didn't know the sample space that they it came from I won't be able to compute the probability accurately. In that case I would probably bootstrap the event and try to derive the probability and I think that's what you need to do here to come to a conclusion. Draw repeated samples and calculate proportion of bald men. Plot it on a histogram, the centre of that histogram is the value that would be closer to the actual proportion. 80% could be a one off event or due to poor sampling method but assuming that random sampling has been applied it could just be an extreme event.


How can I create an excerpt for each of a node's taxonomy terms?

Question: Rather than create a single node excerpt/ preview used across all Views for a taxonomy term, how can I create individual excerpts for a selection of taxonomy terms used to describe a node?
For example, if I have a node about a hotel that is family-friendly and has business facilities (both of which are also taxonomy terms), when I display a list of 'family-friendly' nodes I would like to display an excerpt with a short description of the family-friendly features of that hotel, whilst when displaying a list of nodes for hotels with 'business facilities', I would like to display excerpts with short descriptions of the business facilities at those hotels.
I've found the Excerpt module, but this only appears to provide a minor modification to how Drupal's existing excerpt feature works.
Answer: This is an interesting feature. I have never seen a  module which does it.
If you look at the Open Calais module, you can see some custom extensions to the way taxonomy works. While it doesn't do what you want precisely it may be a  good guide for you.
In short, you can assign meta data to a node-term relationship which contains your excerpt. It would require a custom module and a fair amount of coding.
Comment: Thanks for the reply.

Unfortunately, I don't have the capability to do any customisation and coding at the moment.

I think it's certainly a worthwhile future project, though. It would be an excellent extension of usability and SEO on a Drupal site.


How do you deploy an application to VMWare?

Question: I have an enterprise java container called Karaf that I would like to test on a VMWare node. Unfortunately, I haven't found anything on the web that describes the process of how to deploy an application to a VMWare node. Can anyone assist by either telling me or pointing me to a tutorial?
Answer: You would deploy your application to a VMWare node in the same way that you would deploy it to a physical node - at the OS level they are the same.
Answer: Not quite the same. You should follow vmware tuning guide for jvm such as reserve the memory you need, large memory page etc. Google for vmware jvm tuning and search at vmware.com


In $L^2$ but not in $L^p$, $p \neq 2$.

Question: We consider Lebesgue measure space $(\mathbb{R} , \mathcal{L} , m)$ and let $f : \mathbb{R} \to \mathbb{R}$, $f(x) = \frac{1}{x^{\frac{1}{2}} (1 + |\log x|)} {\chi}_{(0 , \infty)}(x)$ for all $x \in \mathbb{R}$. Show that $f \in L^p$ if, and only if, $p = 2$. Obviously, $f \geq 0$. I have already shown that $f \in L^2$ with ${\|f\|}_2 = \sqrt{2}$ but I can't see that $f \notin L^p$, $p \neq 2$. Any help? Thank you very much.
Comment: For $p > 2$, look at the behaviour on $(0,1)$. For $p < 2$, look at $(1,+\infty)$.
Comment: Compare $f(x)^p$ to $x^{-1}$.
Comment: $$\frac{1}{x f(x)^p} = \frac{x^{p/2}(1+\lvert\log x\rvert)^p}{x} = x^{p/2 - 1}(1+\lvert\log x\rvert)^p$$
Comment: Showing that its (right hand side) limit at $0$ is $0$ would suffice.
Comment: Yes the problem would finish if I could find $g : (1 , \infty) \to \mathbb{R}$, with $g \leq f$ on $(1 , \infty)$, such that $g \notin L^p$, $p < 2$, and $h : (0 , 1) \to \mathbb{R}$, with $h \leq f$ on $(0 , 1)$, such that $h \notin L^p$, $p > 2$. I have looked for but I didn't find $g$ and $h$.
Comment: I begin with the case $p > 2$. How can I prove that exists $y \in (0 , 1)$ such that $1/x \leq f^p(x)$ for all $x \in (0 , y)$?
Comment: Sorry I can't see the argument. What must I do with the expression?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/51525/discussion-between-joseabp91-and-daniel-fischer).
Comment: I think that I have solved the problem. Thank you Daniel. Like+1
Answer: $\int_1^{\infty} \frac{1}{x^{\frac{p}{2}}(1+log(x))^p}dx = \int_0^{\infty} \frac{1}{e^{x\frac{p}{2}}(1+x)^p}e^xdx = \int_0^{\infty} e^{x(1-\frac{p}{2})}(1+x)^{-p} dx$
What is inside the last integral diverges for any $p<2$.
and $\int_0^1\frac{1}{x^{\frac{p}{2}}(1-log(x))^p}dx= \int_{-\infty}^0 e^{x(1-\frac{p}{2})}(1-x)^{-p} dx$ and what is in the last integral diverges for any $p>2$ as $x \to -\infty$

In $L^2$ but not in $L^p$, $p \neq 2$.


Simplifying a Boolean expression for two-level NAND gate circuits

Question: The expression is: F = (X' + Y' + Z')(Y' + A')
I have no clear idea on how to go about simplifying this with Boolean algebra. After it's simplified, I'll need to implement it only using NAND gates.
My instinct is to start off with using the distributive property? Or would it be easier to use k-maps?
Answer: First of all, your question is wrong place however your answer is,
$1. \quad F = (X' + Y' + Z')(Y' + A')$
$2. \quad F=(X'Y'+X'A+Y'+Y'A+Z'Y'+Z'A)$
$3. \quad F=( Y'(X'+Z') + A(X'+Z') + Y'(A+1) )$
$4. \quad F=( Y'(X'+Z'+1) + A(X'+Z') )$
$5. \quad F=( Y'(1) + A(X'+Z') )$
$6. \quad F=( Y' + AX' + AZ' )$
Well, How can I draw only NAND gates diagram? Firsty, I have to know that $(AA)'$ is $A'$ and I can obtain not of anything in these question, then you can step back in circuit for correct usage of NANDs.
click here to access circuit
Comment: You will have to take deMorgan's on 6. to eliminate OR's (+) to get all NANDs.
Answer: You start with your expression and turn it into NANDs, bit by bit. An important rule is that NAND (x, y) = OR (x', y').
F = AND (X' + Y' + Z', Y' + A')
F = NAND (F1, F1) where F1 = NAND (X' + Y' + Z', Y' + A').
F1 = NAND (F2, F3) where F2 = X' + Y' + Z', F3 = Y' + A'.
F2 = NAND (NOT (X' + Y'), Z), so F2 = NAND (F4, Z) where F4 = NOT (X' + Y')
F3 = NAND (Y, A)
F4 = NAND (F5, F5) where F5 = X' + Y'
F5 = NAND (X, Y)


TwinCAT Pointer to Pointer of undefined type?

Question: I'm trying to build a function that sums a single dimension array of any type in TwinCAT.
I'm relatively inexperienced with pointers so the answer may be obvious, but I could not find any solutions. I read through all these and they helped a bit.
T_ARG
Convert Byte arrays
The Wonders of ANY
My conceptual code works for an INT array, but I realized I would have to write a FOR loop for each datatype to make it work and that seems wrong.
I also wanted to avoid having a CASE in a FOR loop as that seemed inefficient.
Is it possible to have a pointer (of unset type) to a pointer (of a specific type)? It looks possible in C, but not sure about IEC-61131.
FUNCTION fn_SumArray : DINT
VAR_INPUT
    inArr : ANY;
    inElem : ANY;

END_VAR

VAR
    i : DINT := 0;
    stepsize : DINT :=1;

    pLREAL : POINTER TO LREAL; //64 bit
    pREAL : POINTER TO REAL; //32 bit
    pBYTE : POINTER TO BYTE; //8 bit
    pWORD : POINTER TO WORD; //16 bit
    pDWORD : POINTER TO DWORD; //32 bit
    pLWORD : POINTER TO LWORD; //64 bit
    pSINT : POINTER TO SINT; //8 bit
    pUSINT : POINTER TO USINT; //8 bit
    pINT : POINTER TO INT; //16 bit
    pUINT : POINTER TO UINT; //16 bit
    pDINT : POINTER TO DINT; //32 bit
    pUDINT : POINTER TO UDINT; //32 bit
    pLINT : POINTER TO LINT; //64 bit
    pULINT : POINTER TO ULINT; //64 bit
END_VAR

--------------------------------------------------
CASE inElem.TypeClass OF
    __SYSTEM.TYPE_CLASS.TYPE_LREAL:
        stepsize := 8;
        //set generic pointer here
    __SYSTEM.TYPE_CLASS.TYPE_INT:
        stepsize := 2;
        //set generic pointer here
ELSE
    fn_SumArray :=0;
END_CASE;

    FOR i := 0 TO inArr.diSize-1 BY stepsize DO
            genericPointer:= ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray +genericPointer^;
        END_FOR;

Answer: As far as I know, you'll have to repeat the code for all types you want to cover. CODESYS doesn't have true generic programming, so it is what it is:
(* DECLARATION *)
METHOD fn_SumArray : BOOL // if TRUE, then error
VAR_INPUT
    arr_first : ANY_NUM;
    arr_size : DINT;
    sum_out : ANY_NUM;
END_VAR
VAR
    i : DINT;
    ptr_arr: NUMBER_POINTER; // just a UNION with all number type pointers
    ptr_sum: NUMBER_POINTER;
END_VAR

(* IMPLEMENTATION *)
IF (arr_first.TypeClass <> sum_out.TypeClass) THEN
    fn_SumArray := TRUE;
    // set all bytes of sum_out to 0
    FOR i := 0 TO sum_out.diSize - 1 DO
        sum_out.pValue[i] := 0;
    END_FOR
    RETURN;
END_IF

CASE arr_first.TypeClass OF
    __SYSTEM.TYPE_CLASS.TYPE_LREAL:
        ptr_arr._LREAL := arr_first.pValue;
        ptr_sum._LREAL := sum_out.pValue;
        ptr_sum._LREAL^ := 0;
        FOR i := 0 TO arr_size - 1 DO
            ptr_sum._LREAL^ := ptr_sum._LREAL^ + ptr_arr._LREAL[i];
        END_FOR
    // Repeat the above for all ...
ELSE
    fn_SumArray := TRUE;
    // set all bytes of sum_out to 0
    FOR i := 0 TO sum_out.diSize - 1 DO
        sum_out.pValue[i] := 0;
    END_FOR
END_CASE;

// A POINTER for every data type of ANY_NUM
// PS. A pointer has the exact same size for any type
TYPE NUMBER_POINTER :
UNION
    // floating
    _REAL: POINTER TO REAL;
    _LREAL: POINTER TO LREAL;

    // unsigned
    _USINT: POINTER TO USINT;
    _UINT: POINTER TO UINT;
    _UDINT: POINTER TO UDINT;
    _ULINT: POINTER TO ULINT;

    // signed
    _SINT: POINTER TO SINT;
    _INT: POINTER TO INT;
    _DINT: POINTER TO DINT;
    _LINT: POINTER TO LINT;
END_UNION
END_TYPE

(* DECLARATION *)
PROGRAM PLC_PRG
VAR CONSTANT
    SIZE: DINT := 50;
END_VAR
VAR
    i: DINT;
    arr_int: ARRAY [0..(SIZE - 1)] OF INT;
    sum_int: INT;
    arr_dint: ARRAY [0..(SIZE - 1)] OF DINT;
    sum_dint: DINT;
    arr_real: ARRAY [0..(SIZE - 1)] OF REAL;
    sum_real: REAL;
    first_run: BOOL := TRUE;
    sum_test: REAL;
    test_failed: BOOL;
END_VAR

(* IMPLEMENTATION *)
IF (first_run) THEN
    first_run := FALSE;
    FOR i := 0 TO SIZE - 1 DO
        arr_int[i] := DINT_TO_INT(i);
        arr_dint[i] := i * 10;
        arr_real[i] := DINT_TO_REAL(i) / 10;
    END_FOR
END_IF

fn_SumArray(arr_first := arr_int[0], arr_size := SIZE, sum_out := sum_int);
sum_test := 0;
FOR i := 0 TO SIZE - 1 DO
    sum_test := sum_test + arr_int[i];
END_FOR
IF (sum_int <> REAL_TO_INT(sum_test)) THEN
    test_failed := TRUE;
END_IF

fn_SumArray(arr_first := arr_dint[0], arr_size := SIZE, sum_out := sum_dint);
sum_test := 0;
FOR i := 0 TO SIZE - 1 DO
    sum_test := sum_test + DINT_TO_REAL(arr_dint[i]);
END_FOR
IF (sum_dint <> REAL_TO_DINT(sum_test)) THEN
    test_failed := TRUE;
END_IF

fn_SumArray(arr_first := arr_real[0], arr_size := SIZE, sum_out := sum_real);
sum_test := 0;
FOR i := 0 TO SIZE - 1 DO
    sum_test := sum_test + arr_real[i];
END_FOR
IF (sum_real <> sum_test) THEN
    test_failed := TRUE;
END_IF

The result of the program above:

If writing the same code for every type is too tedious, you can always use a script to automate this:
#!/usr/bin/env python3

code_template = \
"""CASE arr_first.TypeClass OF
{0}
ELSE
\tfn_SumArray := TRUE;
\tFOR i := 0 TO sum_out.diSize - 1 DO
\t\tsum_out.pValue[i] := 0;
\tEND_FOR
END_CASE;
"""

case_template = \
"""\t__SYSTEM.TYPE_CLASS.TYPE{0}:
\t\tptr_arr.{0} := arr_first.pValue;
\t\tptr_sum.{0} := sum_out.pValue;
\t\tptr_sum.{0}^ := 0;
\t\tFOR i := 0 TO arr_size - 1 DO
\t\t\tptr_sum.{0}^ := ptr_sum.{0}^ + ptr_arr.{0}[i];
\t\tEND_FOR
"""

types = ['_REAL', '_LREAL', '_USINT', '_UINT', '_UDINT', '_ULINT', '_SINT', '_INT', '_DINT', '_LINT']

cases = [case_template.format(t) for t in types]
code = code_template.format(''.join(cases))

print(code)

Just run the above script with python 3.x and you'll get the case statements code for the types listed in the script.
Comment: Thank you so much for the prompt and thorough response!
Answer: What I ended up going with was a case statement, with for loops inside.
Not as elegant as I had hoped, but still functional.
FUNCTION fn_SumArray : REAL
VAR_INPUT
    inArr : ANY; //Array to size
    inElem : ANY; //Any element in the array
END_VAR

VAR
    i : DINT := 0;
    pBYTE : POINTER TO BYTE; //8 bit
    pSINT : POINTER TO SINT; //8 bit
    pUSINT : POINTER TO USINT; //8 bit
    pWORD : POINTER TO WORD; //16 bit
    pINT : POINTER TO INT; //16 bit
    pUINT : POINTER TO UINT; //16 bit
    pDINT : POINTER TO DINT; //32 bit
    pUDINT : POINTER TO UDINT; //32 bit
    pDWORD : POINTER TO DWORD; //32 bit
    pREAL : POINTER TO REAL; //32 bit
    pLREAL : POINTER TO LREAL; //64 bit
    pLWORD : POINTER TO LWORD; //64 bit

END_VAR
//---------------------------------
CASE inElem.TypeClass OF
    __SYSTEM.TYPE_CLASS.TYPE_SINT:
        FOR i := 0 TO inArr.diSize-1 BY 1 DO
            pSINT := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pSINT^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_USINT:
        FOR i := 0 TO inArr.diSize-1 BY 1 DO
            pUSINT := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pUSINT^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_WORD:
        FOR i := 0 TO inArr.diSize-1 BY 2 DO
            pWORD := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pWORD^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_INT:
        FOR i := 0 TO inArr.diSize-1 BY 2 DO
            pINT := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pINT^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_UINT:
        FOR i := 0 TO inArr.diSize-1 BY 2 DO
            pUINT := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pUINT^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_DINT:
        FOR i := 0 TO inArr.diSize-1 BY 4 DO
            pDINT := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pDINT^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_UDINT:
        FOR i := 0 TO inArr.diSize-1 BY 4 DO
            pUDINT := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pUDINT^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_DWORD:
        FOR i := 0 TO inArr.diSize-1 BY 4 DO
            pDWORD := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pDWORD^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_REAL:
        FOR i := 0 TO inArr.diSize-1 BY 8 DO
            pREAL := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pREAL^;
        END_FOR;
    __SYSTEM.TYPE_CLASS.TYPE_LREAL:
        FOR i := 0 TO inArr.diSize-1 BY 8 DO
            pLREAL := ADR(inarr.pValue[i]);
            fn_SumArray := fn_SumArray + pLREAL^;
        END_FOR;
ELSE
    fn_SumArray :=0;
END_CASE;

Comment: Figured out my issue

` __SYSTEM.TYPE_CLASS.TYPE_REAL:
  pReal:=inArr.pValue;
  FOR i := 0 TO Size-1 DO
   fn_SumArray := fn_SumArray + pReal[i];
  END_FOR;
`
Comment: There is no need to get the address of every element. You can just get the address of the first element and then access all the rest of the elements with the array operator (`[index]`), as long as the pointer you store the first address is of the correct size. Also, you could use a UNION with all the pointers instead of declaring pointers of every type.
Comment: Im not quite clear on what you meant? I tried of a few iterations of what you suggested but couldnt get it to work?
I ended up getting page faults with various combinations of the below.

`__SYSTEM.TYPE_CLASS.TYPE_REAL:`

`pREAL := ADR(inarr.pValue[0]);`

`//pReal:=inArr.pValue;`

`//fn_SumArray := pREAL^;`

`FOR i := 0 TO Size-1 DO`

`//pReal:=inArr.pValue[i];`

   `fn_SumArray := fn_SumArray + pReal^;`

  `END_FOR;`


How to change the system in 4x4 system of first-order equations?

Question: Consider the coupled spring-mass system with a frictionless table, two masses $m_1$ and $m_2$, and three springs with spring constants $k_1, k_2$, and $k_3$ respectively. The equation of motion for the system are given by:
$y_1''=-\frac{(k_1+k_2)}{m_1}y_1+\frac{k_2}{m_1}y_2$
$y_2''=\frac{k_2}{m_2}y_1-\frac{(k_1+k_2)}{m_2}y_2$
Assume that the masses are $m_1 = 2$, $m_2 = 9/4$, and the spring constants are $k_1=1,k_2=3,k_3=15/4$.
a)use 4x4 system of first order equations to model this system of two second order equations. (hint: $x_1=y_1,x_2=y_2,x_3=y_1',x_4=y_2'$)
Answer: Introducing a whole new set of $x_i$ variables is somewhat confusing. Simpler to just introduce two new variables $y_3$ and $y_4$ where $y_3=y_1'$ and $y_4=y_2'$. So you now have:
$y_1' = y_3$
$y_2' = y_4$
$y_3' = y_1'' = \dots$
$y_4'=y_2''= \dots$


Insert into PostgreSQL table if a unique column combination doesn't exist, and if it does, update the existing record

Question: I have a table structured with columns user_id, item_id, test
I'd like to make an INSERT/UPDATE query so that if the passed in user_id and item_id combination is already found in a row of the table, it just updates the test of that row. I've tried the following query but it doesn't work:
INSERT INTO tableName (user_id, item_id, test)
VALUES($1, $2, $3)
ON CONFLICT ON CONSTRAINT UNIQUE(user_id, item_id)
DO UPDATE SET test = ($3)

This doesn't work. I've tried playing around with DISTINCT keyword as well but didn't manage to get it working correctly. Any help much appreciated!
Answer: You need a unique index on both columns. It can be a composite primary key or a composite unique constraint, example:
create table tablename(
    user_id int,
    item_id int,
    test text,
    primary key (user_id, item_id)
);

Then use the simple proper syntax:
insert into tablename (user_id, item_id, test)
values(1, 1, '1')
on conflict (user_id, item_id)
do update set test = excluded.test


Can a runner be "put out" by a runner behind him in the following situation?

Question: Suppose there is a runner on first.
The batter hits a fly ball, and runs to first. The runner on first, anticipating that the ball will be caught, "barely" leaves first, with the expectation of returning there. The ball is caught but the batter has touched first base in the meantime.
Can the runner on first return there or is he out because the batter touched first base? Should the batter refrain from touching first base until the ball hits the ground?
(My understanding is that the runner on first is out if the batter BYpasses him on the way to second, but this is a slightly different situation.)
Comment: The batter touching first is immaterial. The runner can safely return to first in the situation that you've described.
Answer: The runner on first is not out until he is bypassed by a runner behind him.  In this situation the runner on first would only be out if he is passed by the runner before the ball is caught.
If the ball is caught and then the batter continues to round the base after the catch and passes the runner, the runner is not out.
Touching first base does not change anything.  There are many different situations where the runner may want to be part of the way off the base, or even tag-up.
In a tag-up situation, the batter may touch the base at the same time as the runner, but cannot pass the runner.
Comment: OK, if the ball is caught, the batter is out, which means that he cannot put out the runner on first EVEN by passing him, right?
Comment: Correct.  Once a catch is made the batter is out.  He may not put out the runner by passing him.  However if he passes the runner and interferes with the resulting play, the umpires may decide on penalties based on rule [7.09-d](http://mlb.mlb.com/mlb/official_info/official_rules/runner_7.jsp).


Accessing Pytest Pass/Fail count (Test stats) from with in code

Question: Is there a way to capture the test stats (pass/fail/xfail/skipped) count when invoking pytest from with in python code using
exit_code = pytest.main()

Once the pytest is done executing the tests, I would like to collect these stats for further processing. All I could think right now is to write plugin and access "terminalreporter" plugins stats, but if there's a better and easy way to do this , I would love to know.
Answer: not really a good solution (imho) but it seems to be working
have counters for run/passed/failed and increment using pytest_runtest_logreport(self,report) hook
if report.when == "setup":
    test_run += 1
if report.passed and report.when == "teardown":
    test_passed += 1
if not report.passed and report.outcome != 'skipped':
    test_failed += 1


Way to display list of users in a horizontal container, rather than vertically and uncontained?

Question: I'm using this WordPress code http://www.wpbeginner.com/wp-tutorials/how-to-randomly-display-registered-users-in-wordpress/
function wpb_random_users() {

global $wpdb;

$randomusers = '
';

// Query database for users
$usernames = $wpdb->get_results("SELECT user_nicename, user_url, user_email FROM $wpdb->users ORDER BY RAND() LIMIT 5");

// Display users in a list
foreach ($usernames as $username) {

if (!$username->user_url) :

$randomusers .= '
' .get_avatar($username->user_email, 45) .$username->user_nicename."
";

else :

$randomusers .= '
' .get_avatar($username->user_email, 45).'user_url.'">'.$username->user_nicename."
";

endif;
}
$randomusers .= '
';

return $randomusers;
}

add_shortcode('randomusers','wpb_random_users');

which works to list users vertically. But I'm wondering how to make the users list horizontally instead, preferably contained in a moving carousel.
How might I change the code to at least partially achieve this, like placing the users horizontally in a box?
Thank you.
Answer: Add to the css file
ul.random-users li {
    display: inline;
}

Comment: Hmm, sadly, adding that to the style.css file doesn't have a visual effect. Also, for testing purposes I typed `padding:50px; margin-bottom:50px; background:red;` under `display: inline;` and it still had no effect. I also tried changing `ul.random-users li` to `li` and emptied the cache and no effect still. Eep. Not sure why it doesn't seem to work. But it seems like it should!
Comment: EDIT: Nevermind! I just needed to edit the CSS in the right place within WordPress. The code works great. Thank you!!


Updating core to 8.9.6 fails

Question: I'v installed Drupal 8 by composer. Everything worked fine, but when I tried to update core from 8.9.1 to 8.9.5 in ended up in 8.9.4.
Today I tried to update from 8.9.4. to 8.9.6 by changing composer.json to demand v 8.9.6 at least.
The result was following error message:

Your requirements could not be resolved to an installable set of packages.
Problem 1

Installation request for symfony/http-kernel (locked at v3.4.41) -> satisfiable by symfony/http-kernel[v3.4.41].
> - drupal/core-recommended 8.9.6 requires symfony/http-kernel v3.4.44 -> satisfiable by symfony/http-kernel[v3.4.44].
> - drupal/core-recommended 8.9.x-dev requires symfony/http-kernel v3.4.44 -> satisfiable by symfony/http-kernel[v3.4.44].
> - Conclusion: don't install symfony/http-kernel v3.4.44
> - Installation request for drupal/core-recommended ^8.9.6 -> satisfiable by drupal/core-recommended[8.9.6, 8.9.x-dev].

I'm stuck, since I don't know what locks symphony/http-kernel to v3.4.41.
I'm still pretty new with composer and would be glad if anybody could help me. Thanks a lot.
EDIT 1
<code>{
"name": "drupal/legacy-project",
"description": "Project template for Drupal 8 projects with composer following drupal/drupal layout",
"type": "project",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/drupal",
"support": {
    "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
    "chat": "https://www.drupal.org/node/314178"
},
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
],
"require": {
    "civicrm/civicrm-asset-plugin": "~1.0.0",
    "civicrm/civicrm-core": "~5.28",
    "civicrm/civicrm-drupal-8": "~5.28",
    "civicrm/civicrm-packages": "~5.28",
    "composer/installers": "^1.2",
    "drupal/admin_toolbar": "^2.2",
    "drupal/antibot": "^1.4",
    "drupal/at_tools": "^3.2",
    "drupal/barrio": "1.x-dev",
    "drupal/captcha": "^1.0",
    "drupal/clever_theme_switcher": "^3.0",
    "drupal/colorbox": "^1.4",
    "drupal/commerce": "^2.17",
    "drupal/commerce_shipping": "^2.0@RC",
    "drupal/core-composer-scaffold": "^8.9.6",
    "drupal/core-project-message": "^8.9.6",
    "drupal/core-recommended": "^8.9.6",
    "drupal/core-vendor-hardening": "^8.",
    "drupal/ctools": "^3.4",
    "drupal/editor_advanced_link": "^1.6",
    "drupal/editor_file": "^1.4",
    "drupal/entity_browser": "^2.4",
    "drupal/hotkeys_for_save": "^1.0",
    "drupal/imce": "^2.3",
    "drupal/layout_builder_kit": "^1.0@beta",
    "drupal/layout_builder_modal": "^1.0",
    "drupal/linkit": "^4.3",
    "drupal/media_library_theme_reset": "^1.0@beta",
    "drupal/menu_block": "^1.5",
    "drupal/menu_item_role_access": "^2.0",
    "drupal/mobile_device_detection": "^3.2",
    "drupal/module_filter": "^3.1",
    "drupal/nagios": "^1.9",
    "drupal/pathauto": "^1.6",
    "drupal/permissions_by_term": "^2.18",
    "drupal/pixture_reloaded": "^3.0",
    "drupal/printable": "^1.1",
    "drupal/quick_node_clone": "^1.12",
    "drupal/redirect": "^1.5",
    "drupal/superfish": "^1.3",
    "drupal/swiftmailer": "^2.0@beta",
    "drupal/token": "^1.6",
    "drupal/upgrade_status": "^2.0",
    "drupal/views_conditional": "^1.0",
    "drupal/views_slideshow": "^4.7",
    "drupal/webform": "^5.9",
    "drupal/webform_civicrm": "^5.0@beta",
    "drupal/xmlsitemap": "^1.0@RC",
    "wikimedia/composer-merge-plugin": "^1.4"
},
"conflict": {
    "drupal/drupal": "*"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "sort-packages": true
},
"extra": {
    "drupal-scaffold": {
        "locations": {
            "web-root": "./"
        }
    },
    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        "libraries/{$name}": [
            "type:drupal-library"
        ],
        "modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "drush/Commands/contrib/{$name}": [
            "type:drupal-drush"
        ],
        "modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ]
    },
    "merge-plugin": {
        "include": [
            "modules/contrib/webform/composer.libraries.json"
        ]
    },
    "drupal-core-project-message": {
        "include-keys": [
            "homepage",
            "support"
        ],
        "post-create-project-cmd-message": [
            "<bg=blue;fg=white>                                                         </>",
            "<bg=blue;fg=white>  Congratulations, you've installed the Drupal codebase  </>",
            "<bg=blue;fg=white>  from the drupal/legacy-project template!               </>",
            "<bg=blue;fg=white>                                                         </>",
            "",
            "<bg=yellow;fg=black>Next steps</>:",
            "  * Install the site: https://www.drupal.org/docs/8/install",
            "  * Read the user guide: https://www.drupal.org/docs/user_guide/en/index.html",
            "  * Get support: https://www.drupal.org/support",
            "  * Get involved with the Drupal community:",
            "      https://www.drupal.org/getting-involved",
            "  * Remove the plugin that prints this message:",
            "      composer remove drupal/core-project-message"
        ]
    }
}
</code>
}
My update command was
<code>composer u drupal/core* --with-dependencies
</code>
Comment: what modifications did you make in the composer ? can you post your composer.json ? what was the command you tried to update ?
Comment: Thank you for your fast answer. I've just  posted my composer.json file and the update command above.
Comment: Revert your manual composer.json changes. Then Remove the line `drupal/core-vendor-hardening` from it. Then delete the composer.lock file, delete the vendor/ folder and try again. Next time try `composer update --with-dependencies`. Disclaimer: Don't try this on a live site, try it locally first.
Comment: Generally, have your composer.json more look like https://github.com/drupal/recommended-project/blob/8.8.x/composer.json this one.
Comment: I don't have a local site, so I will try it in the evenig after having made a complete backup of the live site during a time with little traffic. But I still have a question. What vendor/ folder do you mean to delete? The vendor/-folder below my root directory contains a lot of subfolders with files necesarry for other modules like civicrm.
Comment: The vendor folder will be recreated as soon as you run `composer install -n`.
Answer: I tried an update with composer u. This updated my CiviCRM packages and their dependencies and thus removed the dependency conflict described above.
I had removed drupal/core-vendor-hardening as was suggested in @leymannx's answer (but kept the vendor/ directory). That broke the installation and produced a fatal error running composer u. After restoring it everything worked fine for me. Thanks for everyone who helped.

Updating core to 8.9.6 fails


How to store Avatar Images in JBoss' specific folder

Question: After the user has signed in, I want to show default profile images: two different depending on the user's gender.
Before that i want to store these two avatar images in jboss/standalone/images directory by using java code or image servlet code.
Comment: If there are always those two avatar as choices, why not store the images during deployment and simply show the right one after the user has selected their gender?
Answer: You can do as follows:
1) In the db, where you store informations about the user (user table) you can have a column which stores the path (url) to the image, with a default value to man avatar or woman avatar, depending on the gender. This path can be passed to the src in  tag.
2) If the user decide to change his avatar (from a list of avatars disponible on the server), you must update in it's column to the corresponding path, which is selected new avatar.
Comment: Thanks for your response,
Comment: Thanks for your response, All the Url in user(user table) is fine.But my doubt is,In userprofile imageurl path is    ../..../image/mandoctor.png.  In Standalone i have one images folder it is created at war file deployment time.In that images there is no avatars present i want to store the man avatar and women avatar at that images folder  can you please give me help to store that avatars in standalone/images folder.
Comment: @MadanMohan You say what you create a image folder on the server when the app (war) is deployed? Why?
Comment: Our leader requirement is creating an images folder at the time of deployment time.I asked that question to my leader they said to me like ,create an images folder at the time of app deployment and create users folders with user id(profileid) at the time of signup time.User want to singnin we can show him a default avatars ...Let me know if you understand my question otherwise i can try to give my question clearly to you.
Comment: @MadanMohan and if you redeploy your app, what happens with all the folders in your root image folder? Does the process overwrite it and all the data is lost?
Comment: Once i can deploy my app again we redeploy our app is any changes(new features) we have done in our app then only we redeploy our app yes..i think we need to take back up of that images every time..
Comment: no need to take backup also .The images data is permanently stored in with      respective  userids directory folder.whenever we redeploy an war file the data is stored in server. that it..
Comment: if already folder  present with userid then it dont allow to create a folder with same id.If doesn't it will allow.all the images data are stored in server .After redeploy old customer is trying to login  then the profile picture is came  whatever image present in userprofile id directory that image will be displayed.


Counting how many times an ID appears within subsequent 180 days

Question: I have a pandas dataframe that includes these columns:
REF_ID       REPORT_DATE_RAW
12345      2019-02-21 20:53:00

I want to look at each particular REF_ID and whether or not it has been reported more than one time within 180 subsequent days from REPORT_DATE_RAW. If it does not appear within 180 subsequent days, it counts as a false positive. I want to return a 1 if Yes and 0 if No.
I will need to do this for each REF_ID. I attempted to do this with groupby and a rolling sum, referencing another similar question on here. Here is what I have currently:
df['REPORT_DATE_RAW'] = pd.to_datetime(df['REPORT_DATE_RAW'])

delta=180
df = df.set_index('REPORT_DATE_RAW').assign(count=1).groupby('REF_ID').rolling(f'{delta}D').sum() - 1

This returns:
REF_ID   REPORT_DATE_RAW      count
8637    2019-10-25 16:39:00    0.0
8637    2019-10-31 10:38:00    1.0

I'm not sure I can do an analysis with these results.... I am not sure why the first occurrence has a count of 0 and the other a count of 1. These two REF_IDs are within 180 days, so I just want to count this REF_ID as 1 so I can figure out how many REF_IDs are considered false positives.
Thanks in advance. This project is very time sensitive so I appreciate the help
Answer: Use:
(df.set_index('REPORT_DATE_RAW').groupby('REF_ID')
 .apply(lambda x: (x[::-1].rolling('180d').count() > 1)[::-1].astype(int))
)

where the [::-1] notation makes a forward rolling approach.

Note: Pandas as a pd.api.indexers.FixedForwardWindowIndexer for forward functions, but it doesn't seem to work with datetime windows.
Comment: Thanks. This changes every column value to 0 or 1 but I can work around that... just out of curiosity do you know of a faster way to do this? My dataset has over 400k rows so the .apply() takes a really long time. Just a rough idea, no need to code it all out
Comment: If you have other columns in your dataset, and you wanna avoid them to be an output for the `count` method, just specify one of the columns after the `groupby`. This should solve your problem.
Comment: About your second issue, though, I don't know how to get around the `apply` because you want a forward count, don't you? I can think in a work-around only if you know all of your days are consecutive (which mean, no gaps) (in this case, we can safely use `shift`). But anyways, notice that `apply` here is applying a rolling approach per unique REF_ID, not per row!


Magento 2 New Module Route Not Found

Question: I encountered a problem where my new module is not found when I tried to browse it.
Here is the detail of the code.
Ced/CsTermsAndServices/etc/Module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Ced_TermsAndServices" setup_version="1.0.0">
    </module>
</config>

Ced/CsTermsAndServices/registration.php
<?PHP
 \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Ced_TermsAndServices',
        __DIR__
    );

Ced/CsTermsAndServices/etc/frontend/routes.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="cstermsandservices" id="cstermsandservices">
            <module name="Ced_TermsAndServices"/>
        </route>
    </router>
</config>

Ced/CsTermsAndServices/Controller/Index/Index.php
<?php
namespace Ced\CsTermsAndServices\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory)
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        echo "Hello World";
        exit;
    }
}

The expected route supposed to be
http://localhost/cstermsandservices/index/index
But the result ended up as 404 not found.
Any fix to this?
Answer: 1)make sure you have vendor/module-name vendor_module-name convention is followed( in your case modules name should be  Ced_CsTermsAndServices if you want to follow current directory structure)
2) module.xml file name should be in all lower case
Hope this will work
Happy Magento
Comment: Yeah, I did put it there
Comment: Not yet @Adarsh Shukla

Magento 2 New Module Route Not Found


Asymptotic joint distribution of sample mean and sample variance

Question: I have a square integrable strictly stationary time series $(r_t)$. Suppose that $(r_t)$ satisfies certain conditions such that
$$\sqrt{T}(\bar{r}_T-\mu_r) \rightsquigarrow N(0,\sigma_1^2)$$
$$\sqrt{T}(s_T^2-\gamma_r(0)) \rightsquigarrow N(0,\sigma_2^2)$$
$\mu_r := E[r_t]$ and $\gamma_r(0) := E[(r_t-\mu_r)^2]$. Here $\bar{r}_T$ denotes the sample mean, i.e. $\bar{r}_T = \frac{1}{T}\sum_{t=1}^Tr_t$. $s_T^2$ is the sample autocovariance at lag $0$, i.e.
$s_T^2 = \frac{1}{T}\sum_{t=1}^T(r_t-\bar{r}_T)^2$.
I want to find the limit distribution of
$$\sqrt{T}\begin{pmatrix}\bar{r}_T-\mu_r \\ s_T^2-\gamma_r(0)\end{pmatrix}$$
For this purpose I think the Cramer-Wold device is suitable. So let $a_1,a_2 \in \mathbb{R}$ such that either $a_1 \neq 0$ or $a_2\neq 0$. Then I need to find the asymptotic distribution of
$$\sqrt{T}\begin{pmatrix}a_1 & a_2\end{pmatrix}\begin{pmatrix}\bar{r}_T-\mu_r \\ s_T^2-\gamma_r(0)\end{pmatrix}$$
I manipulated the expression above a bit but I am kind of stuck. I am also not sure whether this is the way to go. I would appreciate some help.
I realized that for my purposes the limit distribution of
$$\sqrt{T}\begin{pmatrix}\bar{r}_T-\mu_r \\ \bar{r^2}_T-E[r_t^2]\end{pmatrix}$$
is also an acceptable answer.
Here $\bar{r^2}_T = \frac{1}{T}\sum_{t=1}^Tr_t^2$
Comment: Do you want the joint distribution of $\sqrt{T}\begin{pmatrix}\bar{r}_T-\mu_r \\ s_T^2-\gamma_r(0)\end{pmatrix}$ or the limit in distribution of this random vector?
Comment: @DavideGiraudo Sorry for the confusion. I meant asymptotic joint distribution. So the limit distribution of that random vector.
Comment: Can you explain how you showed that the limit distribution of $$\sqrt{T}\begin{pmatrix}\bar{r}_T-\mu_r \\ \bar{r^2}_T-E[r_t^2]\end{pmatrix}$$ is sufficient to get the asymptotic joint distribution of the sample mean and sample variance? It seems like maybe some combination of the delta method and Slutsky's theorem would be required, but I still can't figure it out.
Answer: The problem I will try to solve is the asymptotic joint distribution of
$$\sqrt{T}\begin{pmatrix}\bar{r}_T-\mu_r \\ \bar{r^2}_T-E[r_t^2]\end{pmatrix}$$
I will write this as
$$ \sqrt{n}\begin{pmatrix}\bar{X}_n-\mu \\ \bar{Y}_n-(\sigma^2 + \mu^2)\end{pmatrix}$$
where $X_1, \dots, X_n, \dots$ are i.i.d., for each $n$ we define $Y_n := X_n^2$, and then we write $\mathbb{E}X_1 =: \mu$ and $Var(X_1) =: \sigma^2$, so that $\mathbb{E}[Y_1] = \mathbb{E}[X_1^2] = Var(X_1) + (\mathbb{E}X_1)^2 = \sigma^2 + \mu^2$. This corresponds also to writing the indexing variable as $n$ instead of $T$ and the RV's as $X$ instead of $r$.
I will write it this way solely because I am more comfortable with this and want to avoid unnecessary mistakes due to discomfort with notation.
Anyway, it follows then by the multivariate central limit theorem that
$$ \sqrt{n}\begin{pmatrix}\bar{X}_n-\mu \\ \bar{Y}_n-(\sigma^2 + \mu^2)\end{pmatrix}  \overset{D}{\to} \mathscr{N}(0, \Sigma)$$
where $\Sigma$ is the matrix:
$$\begin{pmatrix} Var(X_1) & Cov(X_1, Y_1) \\ Cov(X_1, Y_1) & Var(Y_1) \end{pmatrix} = \begin{pmatrix} Var(X_1) & Cov(X_1, X_1^2) \\ Cov(X_1, X_1^2) & Var(X_1^2) \end{pmatrix}$$ $$ = \begin{pmatrix} \sigma^2 & \mathbb{E}(X_1^3) - \mathbb{E}(X_1)\mathbb{E}(X_1^2) \\ \mathbb{E}(X_1^3) - \mathbb{E}(X_1)\mathbb{E}(X_1^2) & \mathbb{E}(X_1^4) - (\mathbb{E}(X_1^2))^2 \end{pmatrix} $$ $$= \begin{pmatrix} \sigma^2 & \mathbb{E}(X_1^3) - \mu(\sigma^2 + \mu^2) \\ \mathbb{E}(X_1^3) - \mu(\sigma^2 + \mu^2) & \mathbb{E}(X_1^4) - (\sigma^2 + \mu^2)^2 \end{pmatrix}  \,.$$
To get from here to the joint asymptotic distribution of the sample mean and variance, first use the identity that the sample variance, $S_n^2$, is equal to $\bar{Y}_n - (\bar{X}_n)^2$. Therefore if we define:
$$ g: \begin{pmatrix} z_1 \\ z_2  \end{pmatrix} \mapsto \begin{pmatrix} z_1 \\ z_2 - z_1^2 \end{pmatrix} $$ this should give us the final result we want if we apply the Delta Method.
Please double check my work, but I think this gives that the asymptotic covariance matrix is:
$$\begin{pmatrix}\sigma^2  & \mathbb{E}(X_1 - \mu)^3 \\ \mathbb{E}(X_1 - \mu)^3 & \mathbb{E}(X_1 - \mu)^4 - \sigma^4 \end{pmatrix}$$
Here are some related links:

Statistics SE: asymptotic distribution of sample variance of non-normal sample
Asymptotic distribution of variance in important special cases
Example 5.9: How to get from the first joint asymptotic distribution to the second
How to find the covariance of sample mean and sample variance $Cov(M,S^2)$ for Poisson distribution?

In the case that the $X_i$ are normal, one can show that $S_n^2$ and $\bar{X}_n$ are independent, likewise that $\mathbb{E}[(X_1 - \mu)^4] = 3\sigma^4$, which leads to everything simplifying considerably. It seems that people as a result are often tempted to ignore the non-normal case (e.g. here).


CSS not linking in html

Question: I am trying to change background color of a web page.
To do so I am linking style.css externally to index.html using href:
<!DOCTYPE html>

My CSS is simply:
body
{
    background-color: aqua;
}

My project structure is:

Note index.html resides by itself on the project folder (freebookz), whereas style.css resides in a dedicated folder (css). Hence the reason for
href="css/style.css"

The problem is that the CSS is not linking.
I'm using Vscode and I've also tried replicating this project in Notepad++ and CSS still does not work.
I've tried force-reloading the page with SHIFT+CTRL+R to no avail.
Can someone point me to the error?
I've exhausted all attempts to make this work.
Answer: In your  tag check your media attribute, instead of double quotation mark, you have used this Unicode character """ (U+201D) .
Here is my code, paste it in your code, it would work.
<link rel="stylesheet" href="css/style.css" media="screen"/>

Let me know whether it is working or not ?
Answer: That's right, have you tried uncommenting it?
Example:
<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="css/style.css" media="screen"/>

Answer: <!DOCTYPE html>

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

hello this is paragraph

CSS not linking in html


Does the Gibbs Sampling algorithm guarantee detailed balance?

Question: I have it on supreme authority1 that Gibbs Sampling is a special case of the Metropolis-Hastings algorithm for Markov Chain Monte Carlo sampling. The MH algorithm always gives a transition probability with the detailed balance property; I expect Gibbs should too. So where in the following simple case have I gone wrong?
For target distribution $\pi(x, y)$ on two discrete (for simplicity) variables, the full conditional distributions are:
$$
\begin{align}
q_1 (x;y) & =\frac{\pi (x,y)}{\sum_z \pi (z,y)} \\
q_2 (y;x) & =\frac{\pi (x,y)}{\sum_z \pi (x,z)}
\end{align}
$$
As I understand Gibbs Sampling, the transition probability can be written:
$$
Prob\{(y_1, y_2) \to (x_1, x_2)\} = q_1(x_1; y_2) q_2(x_2; x_1)
$$
The question is, does
$$
 \pi(y_1,y_2) Prob\{(y_1, y_2) \to (x_1, x_2)\} \overset{?}{=} \pi(x_1,x_2) Prob\{(x_1, x_2) \to (y_1, y_2)\},
$$
but the closest I can get is
$$
\begin{align}
\pi(y_1,y_2) Prob\{(y_1, y_2) & \to (x_1, x_2)\} \\
& = \pi(y_1, y_2) q_2(x_2; x_1) q_1(x_1; y_2) \\
& = \frac{\pi(x_1, x_2)}{\sum_z \pi(x_1,z)}\frac{\pi(x_1, y_2)}{\sum_z \pi(z, y_2)}\pi (y_1, y_2) \\
& = \pi(x_1, x_2) q_2(y_2; x_1) q_1(y_1; y_2)
\end{align}
$$
That's subtly different, and does not imply detailed balance. Thanks for any thoughts!
Answer: You tried to show detailed balance for the Markov chain that is obtained by considering one transition of the Markov chain to be the 'Gibbs sweep' where you sample each component in turn from its conditional distribution. For this chain, detailed balance is not satisfied. The point is rather that each sampling of a particular component from its conditional distribution is a transition that satisfies detailed balance. It would be more accurate to say that Gibbs sampling is a special case of a slightly generalized Metropolis-Hastings, where you alternate between multiple different proposals. More details follow.
The sweeps do not satisfy detailed balance
I construct a counterexample. Consider two Bernoulli variables ($X_1,X_2$), with probabilities as shown in the following table:
\begin{equation}
\begin{array}{ccc}
        & X_2 = 0     & X_2 = 1 \\
X_1 = 0 & \frac{1}{3} & \frac{1}{3} \\
X_1 = 1 & 0           & \frac{1}{3}
\end{array}
\end{equation}
Assume the Gibbs sweep is ordered so that $X_1$ is sampled first. Moving from state $(0,0)$ to state $(1,1)$ in one move is impossible, since it would require going from $(0,0)$ to $(1,0)$. However, moving from $(1,1)$ to $(0,0)$ has positive probability, namely $\frac{1}{4}$. Hence we conclude that detailed balance is not satisfied.
However, this chain still has a stationary distribution that is the correct one. Detailed balance is a sufficient, but not necessary, condition for converging to the target distribution.
The component-wise moves satisfy detailed balance
Consider a two-variate state where we sample the first variable from its conditional distribution. A move between $(x_1,x_2)$ and $(y_1,y_2)$ has zero probability in both directions if $x_2 \neq y_2$ and thus for these cases detailed balance clearly holds. Next, consider $x_2 = y_2$:
\begin{equation}
\pi(x_1,x_2) \mathrm{Prob}((x_1,x_2) \rightarrow (y_1,x_2)) = \pi(x_1,x_2)\,p(y_1 \mid X_2 = x_2) = \pi(x_1,x_2) \, \frac{\pi(y_1,x_2)}{\sum_z \pi(z,x_2)} \\
= \pi(y_1,x_2) \, \frac{\pi(x_1,x_2)}{\sum_z \pi(z,x_2)} = \pi(y_1,x_2) \,p(x_1 \mid X_2 = x_2) = \pi(y_1,x_2) \mathrm{Prob}((y_1,x_2) \rightarrow (x_1,x_2)).
\end{equation}
How the component-wise moves are Metropolis-Hastings moves?
Sampling from the first component, our proposal distribution is the conditional distribution. (For all other components, we propose the current values with probability $1$). Considering a move from $(x_1, x_2)$ to $(y_1, y_2)$, the ratio of target probabilities is
\begin{equation}
\frac{\pi(y_1,x_2)}{\pi(x_1,x_2)}.
\end{equation}
But the ratio of proposal probabilities is
\begin{equation}
\frac{\mathrm{Prob}((y_1,x_2) \rightarrow (x_1,x_2))}{\mathrm{Prob}((x_1,x_2) \rightarrow (y_1,x_2))} = \frac{\frac{\pi(x_1,x_2)}{\sum_z \pi(z,x_2)}}{\frac{\pi(y_1,x_2)}{\sum_z \pi(z,x_2)}} = \frac{\pi(x_1,x_2)}{\pi(y_1,x_2)}.
\end{equation}
So, the ratio of target probabilities and the ratio of proposal probabilities are reciprocals, and thus the acceptance probability will be $1$. In this sense, each of the moves in the Gibbs sampler are special cases of Metropolis-Hastings moves. However, the overall algorithm viewed in this light is a slight generalization of the typically presented Metropolis-Hastings algorithm in that you have alternate between different proposal distributions (one for each component of the target variable).
Comment: The Gibbs sampler is a composition of Metropolis-Hastings moves with acceptance probability 1. Each move is reversible but the composition is not, unless the order of the steps is random.
Comment: Great answer, thanks (minor edit: y_2 -> x_2 in your third section). When calling the Gibbs sweep one step, is the existence of the stationary distribution (along with irreducibility and recurrence) a sufficient condition for convergence to the stationary distribution from any initial state?
Comment: Could you explain more why $Prob((x_1,x_2) \rightarrow (y_1, x_2)) = \frac{\pi(y_1, x_2)}{\sum_{z}\pi(z, x_2)}$? For me, the right equation looks like considring transitions from other states. For example, $(z_1, x_2) \rightarrow (y_1, x_2)$. I think the transition we want is just $(x_1,x_2) \rightarrow (y_1, x_2)$.
Comment: @Xi'an is there a proof that shows the random Gibbs-sampler is reversible?
Comment: @xabush: yes, by detailed balance


Group context on pages generated by views

Question: I have two group page
node/%/posts and node/%/activity.
Inside these pages, I have a mini panel which requires group context to display. For some reason, the pages generated by views are not recognized as group context though its a menu tab inside the group. Did anyone had the same issue ?
Answer: This has been an issue on the Organics Groups page. Please refer to comment #6 for the solution.
The other way to work around this is to Use page manager to create pages instead of using views. Page manager helps to maintain the context of the group across its pages.


Qual a diferença entre chaves e parênteses em uma arrow function no JavaScript?

Question: Qual é a diferença relevante entre chaves ({ }) e parênteses (( )) em um retorno de uma função?
const example = () => ( ... );

Versus:
const example = () => { ... };

Comment: Acho que vale a pena trocar o título da pergunta para "Qual a diferença entre {} e () em uma arrow function no JavaScript", uma vez que este não é um recurso _exclusivo_ do React, mas do JavaScript. O que acha? :)
Comment: Faço isso amanhã se ninguém formular uma resposta. Por isso comentei "o relevante". Tô de passagem.
Comment: Colchete vai retornar a última instrução. Chave não vai retornar nada. A não ser que você defina com `return`, como em uma função/método qualquer...
Comment: Se quiser escreve uma resposta, exemplifique, etc ... @LipESprY
Comment: @LuizFelipe fiz a alteração.
Comment: Colchetes ou parenteses?
Comment: `() => ( )`, assim vazio, é erro de sintaxe... ou a dúvida é com algo dentro de `()`?
Comment: @sam editado e obrigado.
Comment: @Sergio não é vazio ... é com instrução, como vai se comportar, obrigado.
Answer: Antes de tudo, vale ressaltar que isso não se trata de algo exclusivo do React. É um recurso sintático do JavaScript. Foi introduzido no ECMAScript 2015 (ES6), com a adição das arrow functions. Entre os vários recursos introduzidos por essa nova forma de se criar uma função, pode-se citar a avaliação de um bloco de código ou uma única expressão.

Os métodos mais antigos para se definir funções funções no JavaScript exigem que você necessariamente crie um bloco. Por exemplo:
function doStuff() {
  // Eu sou um bloco!
}

const doOtherStuff = function() {
  // Eu sou um bloco!
};

As arrow functions, por outro lado, não. Permitem ao desenvolvedor optar por utilizar uma única expressão. Se necessário, claro, blocos ainda podem ser usados para ser o corpo (body) da arrow function.
Desse modo, se a sua arrow function retorna algo entre parênteses (), significa que seu corpo é uma única expressão, que será avaliada durante sua invocação. Vale frisar que não é necessário usar parênteses para denotar uma expressão. Nesse caso específico, geralmente os parênteses são colocados em expressões que ocuparão múltiplas linhas, como vários componentes JSX, que são expressões, já que, no fundo, não passam de chamadas à React.createElement.

const fn1 = () => 'Hello, world!';

const fn2 = (x, y) => x + y;

const fn3 = (x, y, z) => (
  x +
  y +
  z
);

console.log(fn1());
console.log(fn2(1, 2));
console.log(fn3(1, 2, 3));

Já se a arrow function tiver sido definida com as chaves ({}), seu corpo será um bloco, que poderá executar múltiplas expressões e declarações (statements). Nesse caso, a função retornará um valor definido explicitamente através do return. Caso contrário, undefined será retornado.
Alguns exemplos da arrow function cujo corpo (body) seja um bloco:

const fn1 = () => {
  return 'Olá, mundo!'
};

const fn2 = (x, y) => {
  // `if` é um exemplo de declaração (statement):
  if (x > y) {
    return 'X é maior que Y.';
  }
};

console.log(fn1()); // Olá, mundo!
console.log(fn2(9, 1)); // X é maior que Y.
console.log(fn2(1, 9)); // undefined

Embora isso não tenha sido colocado na pergunta, vale lembrar que os parênteses também podem ser utilizados para agrupar várias expressões (separadas por vírgulas), avaliando uma a uma mas retornando somente a última. Veja mais na documentação.
Para aprofundamento, sugiro a leitura deste capítulo do excelente livro "JavaScript for impatient programmers", que cobre as diferenças entre expressões e declarações.
Comment: Você terminou a resposta na metade da minha, mas coloquei mesmo assim por causa do último item que não mencionou, já tive problemas com isso e demorei pra entender o erro
Answer: Isso não tem nada a ver com React, JSX ou qualquer biblioteca ou superset (TypeScript, por exemplo), são apenas sintaxes do JavaScript:
Na segunda, as chaves definem o início e fim de um bloco de código, que pode ter múltplias expressões e outros blocos de código, separados por ; ou quebra de linha:
() => {
   foo();bar()
   for (const fun of functions) {
       fun()
   }
}

Ao definir as chaves, a função não retornará nada (ou seja, undefined) a não ser que seja feito explicitamente com a palavra chave return
A primeira é apenas um parênteses para agrupar uma expressão, que será retornada pela função, logo () => (qualquercoisa) é equivalente a () => qualquercoisa, geralmente é usado para deixar claro o início e fim da expressão:
() => (

Um exemplo qualquer

)

Se você quiser retornar um objeto literal, seu uso é necessário para que as chaves não sejam confundidas com o início e fim do bloco de código, o que geraria um erro de sintaxe:
// Correto
() => ({
    foo: 'bar'
})

// Erro
() => {
    foo: 'bar'
}

Answer: Ambas respostas anteriores já definem bem a diferença. Só faltou ressaltar uma questão:
Ao usar os parênteses, automaticamente será retornado a última expressão.
Exemplo:
var a = 10;
var b = 10;
var c;
var d;

var foo = () => (c = a+b, a);
console.log(foo()); // define o valor de 'c' retorna 'a' (10)
console.log(c) // 20

var bar = () => (d = a+b, c = d+a, d);
console.log(bar()); // define o valor de 'd', 'c' e retorna 'd' (20)
console.log(c); // 30

Quando se quer retornar apenas uma expressão, não faz sentido usar os parênteses. Vira uma questão de estética.
Exemplo:
var a = 10;
var b = 10;

var fuba = () => a+b;

console.log(fuba()); // 20

Vale ressaltar, também, que caso tenha mais de uma expressão sem delimitar com os parênteses, a primeira será retornada apesar de executar as demais.
Exemplo:
var a = 10;
var b = 10;
var c;

var foo = () => c = a+b, a = 50;

console.log(foo()); // define o valor de 'c' (a+b), 'a' (50) e retorna 'c' (60)
console.log(c) // 60

Comment: Acho que vale constar que não são os parênteses que criam esse comportamento de retornar a última expressão. Isso é uma capacidade do operador `,` (_comma operator_). [Saiba mais aqui.](http://speakingjs.com/es5/ch09.html#comma_operator)
Comment: @LuizFelipe muito bem colocado! Mas se vc usa os parênteses, é bom saber que será retornado a ultima expressão. Certo? Qualquer pequeno detalhe ajuda o leitor.
Comment: Sim, é algo que ajuda a entender, embora o comportamento seja causado pela vírgula, e não pelos parênteses. :)


Show that subtraction of matrices is neither commutative nor associative. Please review my work.

Question:
Show that subtraction of matrices is neither commutative nor associative.

My Work
Let $A$ and $B$ be $m \times n$ matrices with elements $a_{ij}$ and $b_{i j}$, respectively.
Commutativity says that $A + B = B + A$.
$A - B = a_{i,j} - b_{i,j}$
$B - A = b_{i,j} - a_{i,j}$
Since subtraction of numbers is not commutative, we have that $a_{i,j} - b_{i,j} \not= b_{i,j} - a_{i,j}$.
$\therefore A - B \not= B - A$.
Let $A, B, $ and $C$ be $m \times n$ matrices with elements $a_{ij}$, $b_{i j}$, and $c_{i,j}$ respectively.
$(A - B) - C = (a_{i,j} - b_{i,j}) - c_{i,j}$
$A - (B - C) = a_{i,j} - (b_{i,j} - c_{i,j}) = a_{i,j} - b_{i,j} + c_{i,j} = (a_{i,j} - b_{i,j}) + c_{i,j} \not= (a_{i,j} - b_{i,j}) - c_{i,j}$
I would greatly appreciate it if people could please take the time to review my work for correctness and provide feedback.
Comment: Why don't you just find (counter)example?
Comment: Taking the easy way out is a very good idea in mathematics, when it is possible. If there's an easy way out why not take it? Your proof is correct, but it can be made a lot simpler: consider the case $m=n=1$. $5-2\neq2-5$, thus the statement is false. If you want more generality then $a-b\neq b-a$ but I don't see the point
Comment: Providing a counter-example is **not** a proof by contradiction. As the statements you are trying to prove are not false in general, demonstrating the existence of a counter-example is the only rigorous approach that is gong to work: trying to show that the statements are always false must fail. The constructive way of demonstrating the existence of a counter-example if to give an explicit counter-example.
Comment: For non-zero $A,B, C,$ $$A-B\neq B-A$$ and $$A-(B-C)\neq (A-B)-C.$$
Comment: @user2723984 You're right. I should have used a counterexample.
Comment: @JohnWatson I could, but that, in my eyes, would be taking taking the easy way out.
Comment: @JohnWatson Because the problem is from a rigorous textbook on linear algebra, and none of the provided proofs are proof by contradiction. I wanted to write a solution that maintained the style of the author.
Comment: @ThePointer: Your motivations are good, but a proof in this instance would involve specific numbers and does not represent an easier way.
Comment: @RobArthan  Oops, you're right. I misspoke. And you're right about the 0s; I should have stated that the matrices are nonzero.
Comment: @RobArthan If I had stated that the matrices are nonzero, then would my proof be correct?
Comment: I'd say no, because $1-1=1-1$ is still true
Answer: Your work is incorrect for when the matrices are all 0. A counterexample is the way to show what you want to show. The reason is that if you want to show $\forall x \in X P(x)$ is false, you must show, $\exists$ $x\in X$ such that $-P(x)$ is true


Como obter uma rota infinita no Codeigniter?

Question: Eu tenho duas urls:

http://you.axitech.com.br/busca/qualquercoisa
http://you.axitech.com.br/busca/qualquercoisa/outracoisa

E estou tendo usar estes routes:

$route['busca/(:any)'] = "Busca/index/$1";
$route['busca/(:any)/(:num)'] = "Busca/index/$2/$";

Eu gostaria de usar uma url infinita mas não consigo o resultado desejado. Alguém pode me dar um help? Quando eu acesso a primeira url, funciona corretamente porém a segunda url não funciona. O que eu preciso está representado na imagem abaixo:

Então, eu estava vendo aqui e o $_POST está indo corretamente mas não está entrando no index, ou seja, se eu tento sobrescrever e eliminar o /index dá erro. Resumindo, acho que o erro está no roteamento mesmo.
Comment: Busca/index/$2/$ me parece mero erro de digitação. nâo seria só por o $(numerodoparametro) corretamente em todos os casos? $1/$2/$3 etc?
Answer: Tente usar:
<code>$route['busca/(:any)'] = "Busca/index/$1";
$route['busca/(:any)/(:num)'] = "Busca/index/$1/$2";
</code>
Assim você acessará:
http://www.seusite.com.br/busca/qualquercoisa/umnumero
E ele poderá ser processado assim:
<code>public function index($palavra, $numero = false){

}
</code>
Para você fazer rotas infinitas como você disse, você acabará gerando erros, pois como você não sabe o que está sendo passado na URL e quando, então seria díficil.
Você terá que criar as rotas de acordo com os parâmetros que serão recebidos.
Comment: É, basicamente o que eu comentei na pergunta. não postei como resposta pq não é solução pro "infinito" que foi pedido (apesar de eu concordar que não faz sentido ser infinito se de qq forma vai ter que saber como lidar com os parâmetros).


C recursive function won't return true

Question: I have a search function which employs recursion to perform a binary search of an array, values[], for a value:
int recurseSearch(int value, int values[], int min, int max) {

    if (value > values[max] || min > max) return 1;

    int midpoint = (max+min)/2;

    if (values[midpoint] > value)
        //search in left
        recurseSearch(value, values, min, midpoint);

    else if (values[midpoint] < value)
        //search in right
        recurseSearch(value, values, midpoint, max);

    else if (values[midpoint] == value)
        return 0;

    else
        return 2;

    return 3;
}

The code that calls this simply calls recurseSearch(value, values, 0, n);
For the sake of verifying, I will set values[5] to equal {3, 11, 32, 54, 66}, value to be 3 (i.e. this should return 0), and n to therefore be 5.
So this gets called: recurseSearch(3, values, 0, 5);
Now I would expect this to eventually return, and print, 0, since 3 is indeed in the array. Upon debugging everything is going well up until the midpoint is 0, and therefore values[midpoint] == value is true, and so the return 0 line should run. However, what happens instead is that it does, but then comtrol aparently moves to the end (closing }) of the function, but then moves back up and runs the return 3; on line (here) 21.
I cannot understand why the return 0 statement doesn't just return out of the function and why the return 3 doesn't run at all

N.B. This problem is solved by removing the return 3; line, however this causes clang to complain, and the command for running (make) that I'm using, fatally have a hissy-fit, which I would much rather avoid
Comment: You could perhaps avoid the hissy-fit by setting a return value at each conditional, and then use a single return to return that value.  The code would also benefit from having fewer returns within it.
Comment: In your code `return 3` is the catch all. When the child function returns 0 to the parent caller, the parent caller proceeds to the end of the `if...elseif..else` block and ends up returning 3.
Comment: However, removing `return 3` causes end of function without return. Again, when the child returns, the parent proceeds to the end of the function. You are also neglecting to handle the return value of the child. Shouldn't you return to the grandparent what the child return to the parent?
Answer: I have not looked carefully at your code so there might be other bugs in it, but it sounds like you want the return value from the deepest recursive call to be passed up the stack all the way to the caller.  In that case, you would remove the return 3; and simply return the value of each the recursive call you are making:
int recurseSearch(int value, int values[], int min, int max) {

    if (value > values[max] || min > max) return 1;

    int midpoint = (max+min)/2;

    if (values[midpoint] > value)
        //search in left
        return recurseSearch(value, values, min, midpoint);

    else if (values[midpoint] < value)
        //search in right
        return recurseSearch(value, values, midpoint, max);

    else if (values[midpoint] == value)
        return 0;

    else
        return 2;
}

The way you originally wrote your code, the return values from the recursive calls were being ignored entirely, and the return 3; statement would be executed instead.
Comment: So it seems we have four cases: (1) `values[midpoint] > value`, (2) `values[midpoint] < value`, (3) `values[midpoint] == value` and (4) "the moon is made of green cheese".
Comment: You have to make sure that every code path ends in a return statement, so there is no way for the function to execute without encountering a return statement.  If you compile the code I posted in my answer, the compiler should not give you that error.  Did you try compiling it?  Note that I added `return` before each call to `recurseSearch`.  When you see that error, you need to look at your code and think about every possible way it could execute, and make sure it always reaches a `return` statement.
Comment: Per @EOF's comment, just remove the final `else` and leave a `return 2` at the bottom of the function.  That final `else` does not change the semantics of the code since `return 2` will always be called at that point anyway, and its removal eliminates the compiler-doesn't-realize-it's-never-reached "moon is made of green cheese" return case.
Comment: Thank you for your quick response; is there any way, then, to fix the compiler complaining (sometimes fatally) that *"control may reach end of non-void function"*?
Comment: @joe_young: Remove the `else` after every `if` that `return`s.
Comment: @n.m. case 4 should never happen in real life, but I chose to just make minimal modifications to the OP's code I am not taking responsibility for it being totally free of bugs.
Comment: To make the first and second conditions false, is easy. But I wonder what combinations will make all 3 conditions false.
Comment: Thank you very much for your answer; it turns out that it was the `return`s before calling `recurseSearch()` each time that I needed

C recursive function won't return true


How to resurrect an AWS cluster using command line tools that I cannot ssh into?

Question: About two weeks ago I was suddenly unable to ssh into my AWS machines, they just time out.  Really, the best information I can get from an ssh -vvv <ip> is ssh: connect to host <ip> port 22: Connection refused.  if the ip address has changed no one told me about it.
Since I still have the information about the machines from when I set them up, I'm wondering if there's a way to resurrect an AWS cluster using command line tools.
Here is all of the information I have about the machines in the cluster:
- instance IDs
- region
- groupName
- VpcId
- SubnetId
- SubnetId
- public IP addresses

Using the AWS CLI, is there a way to resurrect these instances?
EDIT I'm pretty sure the instances are stopped, judging by this:  When I do aws describe-instances --region <region> --instance-ids <id> I see "State" { "Code": 80, "Name": "stopped"}.
Comment: Is it possible that your IP address changed and you had a security group enabling ssh access only to your old IP address?
Comment: When Ben said is my best guess too, it's your security group or NACL. Open up SSH on 0.0.0.0/0 temporarily and see if you can ssh in. If you can then work out your IP and narrow the range down to a /32.
Comment: I am not sure about that BenForce and @Tim.  I am really new at this, how do I "Open up SSH on 0.0.0.0/0"?
Comment: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html you need to learn how to use AWS or hire someone, this is a real basic
Comment: Your question is self-contradictory. Connection refused is not a timeout. And that does make a difference to what are the possible explanations.
Comment: Your edit says the instances are stopped. Have you considered starting them?  http://docs.aws.amazon.com/cli/latest/reference/ec2/start-instances.html
Answer: You'd want to use reboot-instances. (Assuming you imply, by the use of "resurrect", that they're in a down state and need a reboot. If you mean to imply something other than that, be more specific.)
Comment: I'm pretty sure the instances are `stopped`, judging by this:  When I do `aws describe-instances --region  --instance-ids ` I see `"State" { "Code": 80, "Name": "stopped"}`.  I think that means they are still able to be resurrected right?
Answer: The command should be:
aws ec2 reboot-instances --region $REGION --instance-ids $INSTANCE_ID
And replace $REGION and $INSTANCE_ID with the correct information. You will need to have valid session keys for this command to work.
If your instances were in the "Stopped" state (or shut down), they'll lose their public IP addresses (unless they had an Elastic IP attached), so you'll have to run:
aws ec2 describe-instances --region $REGION
to get a status on all the instances you have permissions to view, and find out their new public IP addresses.
Reference from the AWS CLI Documentation: http://docs.aws.amazon.com/cli/latest/reference/ec2/reboot-instances.html
Comment: I can't vote yet. +1 though
Comment: I have the correct boto creds, so I should be fine there.  I'll try rebooting the instances to see if they can be recovered.  HOWEVER, are you sure that the instance id won't change when they get rebooted???
Comment: Instance-id will not change on reboot. They will persist until the instance is terminated (which is AWS's term for deleted). Also, the private IP will persist as well, you only really have to worry about the public IP changing, and even that will persist if you issue the reboot command on a running instance. However, if the instance is "Stopped" (AWS's term for "shut down"), the public IP is released and you can't get it back, you'll just get another random public IP when you start it up again.


Boundary of a connected sum: is it connected?

Question: Let $M^3$ and $N^3$ be compact orientable manifolds with connected boundary. When we perform the connected sum operation, will the resulting manifold $X = M \#N$ have a connected or disconnected boundary?
For instance, if $M$ and $N$ are two solid tori, their connected sum will be a genus $2$ handlebody, and hence have a connected boundary, or will it be another $3$-manifold whose boundary has $2$ connected components?
Comment: If $M$ and $N$ are disks $D^3$ then isn't their connected sum a cylinder $S^2 \times [0, 1]$, with boundary $S^2 \sqcup S^2$?
Comment: Aren't you doing the connected sum of the boundaries of the solid tori? What do you mean by connected sum of manifolds with boundary?
Comment: I am trying to understant Theorem 1.1 in this beautiful paper: https://arxiv.org/pdf/1903.11772.pdf
Answer: The trouble is that for manifolds with connected boundary $M_1, M_2$ there are two notions of connected sum:

The ordinary connected sum, denoted $M=M_1\# M_2$ where you take out open balls $B_1, B_2$ from the interiors of $M_1, M_2$ and glue $M_i-B_i$ via a homeomorphism of the new boundary spheres $\partial B_1, \partial B_2$.  Then, clearly, $M$ has two boundary components, homeomorphic to $\partial M_i, i=1, 2$.

The boundary connected sum, denoted $N=M_1\#_{\partial} M_2$, where you pick two closed (tame) disks $D_i\subset \partial M_i$ and  glue $M_1, M_2$ via a homeomorphism $D_1\to D_2$. Then $N$ will have connected boundary, homeomorphic to $\partial M_1 \# \partial M_2$.

(In both cases, there are some issues with the choice of gluing homeomorphisms, I will ignore these. Separately, there are issues with the category in which everything is done: TOP, PL or DIFF, in dimension 3 this does not matter.)
Thus, the answer to your question is: It depends on your notion of connected sum.


Prove that the equivalence class $\mathbb R^3/V$ is isomorphic to $\mathbb{R}$

Question:
Let, $V$ be a subspace of $\mathbb{R}^3$ such that $V=\{(a,b,c)\in\mathbb{R^3}|a=b\}$. Show that $\mathbb R^3/V$ is isomorphic to $\mathbb{R}$.

I can understand that two 3 tuples $(a,b,c)$ and $(x,y,z)$ are related ie belong to the same equivalence class if $(a-x,b-y,c-z)\in V$ ie. if $a-x=b-y$.
What should I do after that?
Answer: We have $V=span\{(1,1,0),(0,0,1)\}$ now we know that
$$
\dim\frac{\mathbb{R}^3}{V}=3-\dim V=1
$$
so, if $v$ it's a generator of the quocient, the map $v\mapsto 1$ extends to a linear isomorphism between $\frac{\mathbb{R}^3}{V}$ and $\mathbb{R}$.
Answer: $V=\{(a,a,c)|a,c\in\Bbb R\}=\rm{span}\{(1,1,0),(0,0,1)\}\cong\Bbb R^2$.  And $\Bbb R^3/\Bbb R^2\cong\Bbb R$.


Steps used to solve this riccati differential equation?

Question: I am reading through examples of linear filtering problems for SDE's, and the process first requires solving a (deterministic) riccati differential equation. In one of the examples, this is given by:
$$\frac{dS_t}{dt} = \frac{-1}{m^2}S^2_t + c^2$$
to solve it, they first rearrange it as
$$\frac{m^2 dS_t}{m^2 c^2 -S^2_t} = dt$$
and then state (without working or explanation) that this gives
$$\left| \frac{mc+S_t}{mc-S_t} \right|= \left| \frac{mc+a^2}{mc-a^2} \right| \exp \left( \frac{2ct}{m} \right)$$
And I'm unsure how to get from one to the other.
Clearly, since $t$ has emerged, it involves integrating both sides. But besides that I'm lost. Could someone explain this or give some steps/outline for me to do myself?
Answer: Don't see this as Riccati equation, see it as separable ODE with constant solutions at $\pm mc$. Then the last form has a partial fraction decomposition
$$
\frac{mdS}{S+mc}-\frac{mdS}{S-mc} = 2cdt
$$
which after integration and determination of the integration constant should give your solution form.