What factors are most important to DAW performance (in 2020)

Question: When choosing or upgrading your PC/Mac with music recording/production in mind, in what order should CPU (speed, cores)/Memory/Disk/other be prioritised?
Even in something like Garageband you might easily have a dozen tracks each with EQ, FX modelling, etc which must be able to playback perfectly when producing or recording and of course when it comes to render a mix every second is a pain.
Specific recommendations are off-topic but I think it's reasonable to ask what is a sensible minimum, or where to splash the extra $$$?
Answer: RAM and read/write speed are the most important factors. Rendering a recording is not dependent on clock speed for smooth recording, just fast output. If you can throw more CPU cores, that's better, but if you're composing and making recordings, you'll be spend more time figuring out what you want to do next than rendering out files. For instant response - live playing - you can daisy chain multiple machines in VST to create processing power.
As far as rendering and creating demos, a midgrade quad core i7 and 16gb RAM is faster than I am, but I only have a last-gen dual core brain.
Answer: Simple. You want everything ;)
Large track count needs fast drive access - eg a second internal SSD
High plugin count needs high core count.
Once you have both lots of tracks & lots of plugins, you then need high clock speed to keep it all running smoothly.
Skimp on any one of them & you will bottleneck the machine.
Oh… you can skimp on the graphics card.
Comment: ha. I was interested if say 8 vs 4 cores would make a huge difference - lots of software it doesn't but one would _assume_ multi-track is a perfect case for this? You didn't mention RAM but again: lots? LIke crazy amounts, or just a decent amount?
Comment: Same as anything, you can never have a computer that's *too fast*. Same applies to RAM. I actually run an old Mac Pro, 12-core [+HT] dual Xeon, 3.46GHz, 64GB RAM, 2 1TB SSDs, 4 4TB HDs. I can still run out of power if I'm trying to do a full orchestra of sample playback, live. 'Simple' recorded audio plus plugins, I've often had well over 100 tracks running with no issues.
Comment: Speaking of graphics card, for efficient workflow one may want to consider using several large, high resolution monitors. But otherwise indeed, as of today audio software doesn't use GPUs for sound processing.
Comment: @Mr.Boy I think primary benefit from large RAM is when you use many sample-based virtual instruments. For simple recording, or instruments based on algorithms it may not matter so much.


JSONKit: changing and serializing JSON attribute's value

Question: I am using JSONKit to parse JSON string into NSDictionary:
NSDictionary *deserializedData = [jsonString objectFromJSONString];

My question is: how can I change the dictionary values and get a changed JSON String?
I've tried to change the dictionary values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:@"ratings"];

But the app crashes in that line. What am I doing wrong?
Thanks in advance!
Answer: While the other answers are correct, what you really want in this case is:
NSMutableDictionary *deserializedData = [jsonString mutableObjectFromJSONString];

The mutableObjectFromJSONString method will create a mutable dictionary directly, which saves time and memory.
Answer: NSDictionary is an immutable dictionary, you need NSMutableDictionary to change the data. I'm not sure about JSONKit, but the built-in Cocoa JSON parser has a flag to return the data in mutable containers.
In worst case, you can do something like that:
NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:[jsonString objectFromJSONString]];
[data setObject:[NSNumber numberWithInt:iRatings] forKey:@"ratings"];

Answer: //
// we begin with our string in json format
//
NSString *jsonString = [[NSString alloc] initWithString:@"{\"1\":\"Hole 1: Rossy Robinson - $25\",\"2\":\"Hole 7: Davey Ambrose - $25\",\"3\":\"Hole 14: Ross Robinson - $25\"}"];

//
// convert the json string to an NSMutableDictionary
//
NSError *e;
NSMutableDictionary *JSONdic = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];

//
// change a value and add a new value in the dict
//
NSLog(@"before: object for key 1 is: %@", [JSONdic objectForKey:@"1"]);
[JSONdic setObject:@"xxx" forKey:@"1"];
[JSONdic setObject:@"Phil McQuitty" forKey:@"2"];

//
//convert dictionary object to json data
//
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&e];

//
// convert the json data back to a string
//
NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\

//
// print out the final results
//
NSLog(@"back to string: %@", jsonText);

Answer: You try to change an immutableobject.
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];

This is a mutable dictionary and you can change the values in it.
Answer: You try like this:
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];

and then change the values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:@"ratings"];

For NSDictionary we cannot add or change values, thats why application is crashing.


How do I set up the DN for a SSL cert with a hostname of greater than 64 characters?

Question: Everywhere I read says to have the server hostname in the commonName field and the subjectAltName field. The problem is that the hostname that I want to sign has greater than 64 characters. Therefore, the hostname wont fix in that field. I have seen sites such as this which even say that it is a security vulnerability not to have the hostname as the commonName. How should I do this?
Answer: Check this RFC:

RFC5280

This previous questions at stackoverflow:

certificate-subject-x-509
what-strings-are-allowed-in-the-common-name-attribute-in-an-x-509-certificate

As for a workaround, you can set a short CNAME entry in your DNS.
Comment: That wont work: the reason being that the hostname is a sha2 hash, I cant shorten it without losing meaning.
Answer: THe answer is that the cname is only an alternate. The cname and the san dont have to match.


$E(\frac{1}{1+x^2})$ under a Gaussian

Question: This question is leading on from the following question.
https://math.stackexchange.com/questions/360275/e1-1x2-under-a-normal-distribution
Basically what is the $E\left(\frac{1}{1+x^2}\right)$ under a general Gaussian $\mathcal{N}(\mu,\sigma^2)$. I tried rewriting $\frac{1}{1+x^2}$ as a scalar mixture of Gaussians ($\propto \int\mathcal{N}(x|0,\tau^{-1})Ga(\tau|1/2,1/2)d\tau$). This also came to a halt, unless you folks have got a trick under your belt.
If this integral isn't analytical any sensible bounds?
Comment: why can't you do the same as in the question you linked to? (which implies it is not analytic ( since it evaluates to erfc with a few constants)
Comment: Because I don't follow what he has done completely. Also erfc is fine
Answer: Let $f_\sigma(x) = \frac{1}{\sqrt{2\pi}\sigma}\exp\left(-\frac{x^2}{2\sigma^2}\right)$ be the Normal$(0,\sigma)$ PDF and $g(x) = \frac{1}{\pi}\left(1+x^2\right)^{-1}$ be the PDF of a Student t distribution with one d.f.  Because the PDF of a Normal$(\mu,\sigma)$ variable $X$ is $f_\sigma(x-\mu) = f_\sigma(\mu-x)$ (by symmetry), the expectation equals
$$\mathbb{E}_{\sigma,\mu}\left(\frac{1}{1+X^2}\right) =  \mathbb{E}_{\sigma,\mu}\left(\pi g(X)\right) = \int_\mathbb{R} f_\sigma\left((\mu-x)^2\right) \pi g(x)dx.$$
This is the defining formula for the convolution $(f\star \pi g)(\mu)$.  The most basic result of Fourier analysis is that the Fourier transform of a convolution is the product of Fourier transforms.  Moreover, characteristic functions (c.f.) are (up to suitable multiples) Fourier transforms of PDFs.  The c.f. of a Normal$(0,\sigma)$ distribution is
$$\widehat{f}_\sigma(t) = \exp(-t^2\sigma^2/2)$$
and the c.f. of this Student t distribution is
$$\widehat{g}(t) = \exp(-|t|).$$
(Both can be obtained by elementary methods.)  The value of the inverse Fourier transform of their product at $\mu$ is, by definition,
$$\frac{1}{2\pi}\int_\mathbb{R} \widehat{f}_\sigma(t)\pi\widehat{g}(t) \exp(-i t \mu) dt =\frac{1}{2}\int_\mathbb{R} \exp(-t^2\sigma^2/2-|t|-i t \mu) dt.$$
Its calculation is elementary: carry it out separately over the intervals $(-\infty,0]$ and $[0,\infty)$ to simplify $|t|$ to $-t$ and $t$, respectively, and complete the square each time.  Integrals akin to the Normal CDF are obtained--but with complex arguments.  One way to write the solution is
$$\mathbb{E}_{\sigma,\mu}\left(\frac{1}{1+X^2}\right) = \frac{\sqrt{\frac{\pi }{2}} e^{-\frac{(\mu +i)^2}{2 \sigma ^2}} \left(e^{\frac{2 i \mu }{\sigma ^2}} \text{erfc}\left(\frac{1+i \mu }{\sqrt{2} \sigma }\right)-\text{erf}\left(\frac{-1+i\mu}{\sqrt{2} \sigma }\right)+1\right)}{2 \sigma }.$$
Here, $\text{erfc}(z) = 1 - \text{erf}(z)$ is the complementary error function where
$$\text{erf}(z) = \frac{2}{\sqrt{\pi}}\int_0^z \exp(-t^2)dt.$$
A special case is $\mu=0, \sigma=1$ for which this expression reduces to $$\mathbb{E}_{1, 0}\left(\frac{1}{1+X^2}\right)  = \sqrt{\frac{e\pi}{2}}\text{erfc}\left(\frac{1}{\sqrt{2}}\right)=0.65567954241879847154\ldots.$$
Here is contour plot of $\mathbb{E}_{\sigma,\mu}$ (on a logarithmic axis for $\sigma$).
Comment: +1. Small note: $\sqrt{\frac{e\pi}{2}}\text{erfc}\left(\frac{1}{\sqrt{2}}\right)$ equals $0.6556795424\ldots$ for me which agrees with @fabee's numerical answer.
Comment: Nice. I actually totally missed that this is the density of the sum of a Gaussian and a t-distributed variable (up to normalization). +1 for deriving the general formula for arbitrary $\mu$ and $\sigma$.
Comment: @COOL Thanks--I copied the wrong answer.  (I did several numerical calculations; the one I mis-reported was actually for $\mu=1,\sigma=1/2$.)  I'll paste in the right one.
Answer: This is an idea how to solve it which uses the identity
$$\frac{1}{S}=\int_0^\infty \exp(-tS)dt$$
which was proposed by Did here. You could use
\begin{align}E\left(\frac{1}{x^2+1}\right) &= \frac{1}{\sqrt{2\pi}}\int_0^\infty \int_{-\infty}^{\infty}\exp\left(-t(x^2+1)\right)\exp\left(-\frac{x^2}{2}\right)\mathrm dx \mathrm dt\\
&=\int_0^\infty \exp\left(-t\right)\left(1+2t\right)^{-\frac{1}{2}} \mathrm dt\\
&=\sqrt{\frac{e\pi}{2}}\left[\mbox{erf}\left(\sqrt{t+\frac{1}{2}}\right)\right]_0^\infty\\
&=\sqrt{\frac{e\pi}{2}}\left(1-\mbox{erf}\left(\sqrt{\frac{1}{2}}\right)\right)\end{align}
Comment: You have conflated the error function with the Gaussian CDF: they are not the same.  Try a numerical calculation--you will see the error.
Comment: +1 For the approach.  I believe the factor of $1/\sqrt{2\pi}$ does not belong in the result, though.
Comment: That's the normalization constant $\frac{1}{\sqrt{2\pi\sigma^2}}$ for the Gaussian (comes from the expectation). So, unless I am missing something, I think it does belong there.
Comment: You are correct, the factor was wrong. But it happened before I used the error function. I computed the expectation of $\exp(-t x^2)$ w.r.t. $x$ and forgot to remove the normalization constant afterwards. Thanks for the hint.

$E(\frac{1}{1+x^2})$ under a Gaussian


Showing that $u(x)=(1+x^2)^{-k/2} (\ln(2+x^2))^{-1}$ belongs to $\mathcal W^{1,p}(\Bbb R)$.

Question: Consider the function $$u(x)=(1+x^2)^{-\frac{k}{2}} (\ln(2+x^2))^{-1}$$
$x\in\Bbb R$ with $k\in(0,1)$. Prove that $u\in \mathcal W^{1,p}(\Bbb R)$ for every $p\in[1/k,+\infty]$ and that $u\notin L^q(\Bbb R)$ for $q\in[1,1/k)$.
By definition, I have to prove that $u(x)\in L^p(\Bbb R)$ and that the weak derivative $Du$ exists and it belongs to $L^p(\Bbb R)$.
I think I computed $Du$ correctly, but I am having problems showing that $u$ and $Du$ belong to $L^p(\Bbb R).$
How can I show that $$\int_{\Bbb R}|u(x)|^p<+\infty $$ $$\int_{\Bbb R}|Du(x)|^p<+\infty. $$
Thanks in advance.
Answer: I'll show you how to prove $u\in\ L^p$. It is clear that $u$ is smooth. We have to look at the behavior of $u$ at $\infty$. For $x$ large,
$$
u(x)^p=(1+x^2)^{-\frac{k\,p}{2}} (\ln(2+x^2))^{-p}\le 2^{-p}|x|^{-k\,p}(\ln|x|)^{-p}.
$$
If $k\,p>1$ this is integrable. If $k\,p=1$, since $p\ge1/k>1$, it is also integrable.
Similar arguments will show that $Du\in L^p$.
Comment: Could you please explain in more detail why if $kp>1$ the function is integrable or just tell me where to find the theory that explains it? Thank you very much.
Comment: If $r>1$, then $$\int_1^\infty x^{-r}\,dx=\frac{1}{1-r}x^{-r+1}\Bigr|_1^\infty=\frac{1}{r-1}<\infty.$$
Comment: I'm sorry to bother you again, but why is it sufficient to show that the function $|x|^{-kp}$ is integrable to say that the whole function $2^{-p}|x|^{-k\,p}(\ln|x|)^{-p}$ is integrable? One last thing, why for $kp=1$ the considered function is integrable even though $\int_{1}^{\infty}x=\ln|x|\rvert_1^\infty$ is not finite? Thanks again.
Comment: Negative powers of the logarithm are bounded near infinity. And $x(\log x)^r$ is integrable if $r>1$.


Make content be aware of the section

Question: I have a site divided by in multiple section which are actually some taxonomy views (taxonomy/term/term_ID).
It works like this:

I have some specific blocks for each section.
Content can be found in multiple sections

The problem is that (because the node is part of multiple section) I don't know how to display the same blocks on the node page as the ones in the section the user just left.
Any ideas? Thanks
Answer: You can use context module and create two different contexts by adding conditions as path.
Enable the reactions as blocks and add same blocks in different sections using two context that you created !

Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

Hope it solves the problem :-)
Comment: The question was about the context module.
Answer: I ended up using contextpphp module and adding a SESSSION variable as a reaction to each section. Then checked this variable as a condition for another context.

Make content be aware of the section


.htaccess file not working on godaddy server

Question: I updated my site tutorialdata.com which uses .htaccess for redirecting rule. When I checked on localhost it works fine, but when I launch it does not work properly. Only a few pages are displayed properly, most of them show blank pages.
Code used for .htaccess
<code>RewriteBase www.tutorialdata.com/

RewriteCond %{REQUEST_URI} examples/(.*)/(.*)/(.*)/(.*)
RewriteRule ^examples/(.*)/(.*)/(.*)/(.*)$ examples.php?action=pgm&l=$1&c=$2&s=$3&p=$4

RewriteCond %{REQUEST_URI} examples/(.*)/(.*)/(.*)
RewriteRule ^examples/(.*)/(.*)/(.*)$ examples.php?action=subcat&l=$1&c=$2&s=$3

RewriteCond %{REQUEST_URI} examples/(.*)/(.*)
RewriteRule ^examples/(.*)/(.*)$ examples.php?action=cat&l=$1&c=$2
</code>
How can I remove this error?
Comment: what is your url structure, which url its coming as blank and which are not showing ?
Comment: http://www.tutorialdata.com/examples or http://www.tutorialdata.com/online-test are coming as blank and other than main page of tutorial are also display blank pages
Answer: This has been posted similarly before so it is a duplicate but I will answer anyways.
I'm assuming you know how to enable the ModRewrite as your local server works correctly.
This may be the problem as possibly GoDaddy may not allow you to change the httpd.conf file.
If this is the case you will need to look at the GoDaddy FAQ and then contact their support for more information.
Comment: I might also add that you probably did this but didn't include it in the post, is that you added the line for `RewriteEngine on`


Strange Logarithm Phenomenon

Question: I was looking at the following two equations and was trying to solve them when I noticed a very strange phenomenon. These were the equations I was trying to solve: $y=\log_3 x$ & $y=\log_x 3$. I know that multiplying these equations together would give us $y^2=1$ (based on change of base principle). When I try using a different approach, however, I notice that I receive an incorrect answer. Here is my thought process: $3^y=x$ and $x^y=3$ (based on the two equations). If we substitute $3^y$ in for $x$ in the second equation, we will end up with $(3^y)^y=3$. By exponent laws, this is just $3^2y=3$. This gives us the incorrect answer of $y=1/2$. I am fairly sure the problem is in the interpretation of $(3^y)^y$, but how do I know with exponent to deal with first? What do I do?
Comment: Can you tell me what Kind of equations do you mean?
Answer: You're forgetting the rules. $(a^y)^z=a^{y\times z}$, whereas $(a^y)(a^z)=a^{y+z}$.
Answer: Your mistake was in $$(3^y)^y=3\implies 3^2y=3$$ instead of  $$(3^y)^y=3\implies 3^{y^2}=3$$
Your $y^2 =1$ is correct due to change of base formula $$ \log_ b a = \frac {\ln a}{\ln b}$$

Strange Logarithm Phenomenon


Action vs virtual methods

Question: Consider I have a game-creation framework, with a basic class called Game.
// Action version
public class Game
{
    public Action<float> OnUpdate;
    public void Update(float mFrameTime) { OnUpdate.Invoke(mFrameTime); }
}

// Virtual version
public class Game
{
    public virtual void Update(float mFrameTime) {}
}

Which one is the best approach?
(design-wise and performance-wise)
Subscribing something to the OnUpdate action (and not inheriting the Game class), or inheriting the Game class and overriding the virtual method?
Comment: FYI the [tag:XNA] framework uses a virtual method. Personally I'd trust their judgement unless your use case is different. :)
Answer: This depends on who the target audience is for the Update notification.  If it's for only derived classes then a virtual method is a fine approach.  If it's for derived classes and or arbitrary consumer then the event style pattern is the correct approach.
Answer: I would rather raise events than have the Action<T>. This is a common pattern in .NET:
public class Game
{
    public event EventHandler<SomeEventArgs> Update;
    protected virtual void OnUpdate(float mFrameTime) { // invoke event here }
}

Comment: What exactly are the advantages of raising an event instead of using an Action?
Comment: events are delegates (with access limitations). there is no dif. delegates also can have multiple subscribers (try it :). Design wise, events are typically for well, events, and plain delegates are typically for callbacks. [edit: adding emphasis that events ARE delegates - they are the exact same thing, it's an alias with some extra compiler restrictions on the access - and you get the add/remove props if you want)
Answer: It depends what the rest of your framework looks like and what you plan to do with this class. If this class simply alerts other classes that its time to update, then you'll want an event based system. If this is a base class for all games to derive from, then you'll probably want an override. No answer is 100% correct - it all depends on what exactly you are trying to accomplish with your design.
Answer: Unfortunately I lack the knowledge to answer which of those options would be more efficient from a performance perspective, but from a design perspective I would advise overriding the Update method for the following reasons:

It keeps all your update logic in one spot.
It allows you to easily monitor the ordering of update actions.

As others have said, it depends on the purpose of the class, and I am making assumptions based on the fact that it's a 'game' class. There's no reason you couldn't implement both, with a virtual method that triggers an event. This would allow for the bulk of update code to be located centrally, with the option for elements to subscribe to the update event as needed.
When I've approached the same problem myself I've typically adopted a virtual-method approach, though I've broken down update into multiple sections for convenience and control purposes.

Action vs virtual methods


Modal Interchange chord progression (bVIIM7 moving to IM7)

Question:
I was reading a theory book and it's talking about "Modal Interchange."
The key is in C Major and I can't understand how BbM7 went to CM7. Isn't BbM7 a secondary triad Sub Dominant? And as I know, a secondary triad Sub Dominant can't just skip to the Primary triad Tonic..
So what is happening here?
Comment: What theory book is this?
Comment: Thanks Hyun - much easier to find in a search now!
Comment: Can you please edit your title to ask the question. It is not helpful to just have "modal interchange chord." Thanks.
Comment: @DrMayhem Sorry about that ! I fixed it !
Answer: What's this idea that one chord CAN'T skip to another?   Bbmaj7 demonstrably CAN go straight to Cmaj7.   Do you like the sound?  Good.  Add it to your bag of musical resources.   If you subscribe to some system of 'theory' that says it can't be done, find a better sysyem of theory!
Theory describes.  It does not give permission.
I'm going to keep saying this until it sinks in!   Seems to be taking a long time :-)
Comment: Yes I believe theory could be bended. But even those cases it has some reasons why that works and sounds fine.
Comment: There may be deep conceptual reasons why one musical event sounds better than another.  But the 'reasons' we are usually given more often justify something merely on the grounds that it's been noticed and categorised.  There are systems of categorisation based on functional harmony.  But they are not exclusive.  'It's next door' is also a perfectly good excuse for moving to a chord!
Comment: @HyunYooPark - who states that Dm7 can't go straight to C maj? Lots of music does exactly that, so this guy must have lived under a stone for a while. As Laurence says about 'theory'. That's just what it is. If everyone stuck to 'the rules', we'd all still be singing some pretty boring stuff!
Comment: Laurence, I know sometimes I give you a bit of a hard time for being brutally direct, but you are absolutely on the money with that middle paragraph.
Comment: @DrMayhem - too true! It seems that there are more and more questions such as these. No-one's listening to Laurence!
Comment: I read that "Secondary Triad" chords ( iim7 ,iiim7 ,Vim7 , ) can't skip to the next function (ex. In C Maj key , Dm7 (Secondary Triad Sub Dominant) can't go to C Maj (Primary Triad Tonic) without going to its next function "Dominant" But the Primary Triads ( I , IV , V ) could skip to the next function ( ex. In C Maj key F - C or C - G ) so I was wondering if the Modal Interchange chord bVIIM7 ( Sub Dominant ) was a Primary Triad since the Sub Dominant was skipping to C ( Tonic ) or there might be other reasons that makes it possible
Comment: You're approaching this from the wrong direction.  Theory isn't a set of rules telling what you MAY do, it's a set of descriptions of what sounds good, or of what fits a certain style.
Answer: i 'm studing a theory book that talk about the bVIIM7 function.These chords are non diatonic chords inherited from the Myxolidian mode.Their function us a SUB-DOMINANT function.
For instance in G Major you can find an FM7 because in G mixolydian the F is not #, as in a G7 chord. The bVIIM7 chords tend to resolve on I. But as a sub-dominant chord, you can find it in a IV-V-I cadence where the bVIIM7 take place of the IV. This the case in the pop song i'm studying where FM7 (bVIIM7) is preceded by a C (IV) and followed  a D7 (V7) and a G (I). This emphasizes its a SUB-DOMINANT function ( I Need you by America  - 1971)
Cheers !


can't inherit from superclass

Question: I have a simple code like below where the class Employee should inherit from the class Person.
class Person:
  def __init__(self, firstname, lastname, age):
    self.firstname = firstname
    self.lastname = lastname
    self.age = age
  def getname(self):
    return self.firstname, self.lastname
  def getage(self):
    return self.age

class Employee(Person):
  def __init__(self, first, last, empid, age):
    Person.__init__(self, first, last, age):
    self.empid = empid
  def getemp(self):
return self.getname() + ", " + self.empid

employee = Employee("Bart", "Simpson", 1006, 16)
print(employee.getemp())

It gives me this error:
File "/tmp/pyadv.py", line 156
    Person.__init__(self, first, last, age):
                                               ^
    SyntaxError: invalid syntax

I checked Python documentation about classes and it didn't have that superclass initialization inside the __init__() of the subclass. But I found that in other websites like here, where Dog inherits from Pet.
So, what am I missing?
Comment: You have a spurious colon at the end of that line.
Comment: @kindall, ok, I hadn´t noticed that. But how is this off-topic???
Comment: "This question was caused by a problem that can no longer be reproduced or a simple typographical error"
Answer: You're not missing anything. You need to get rid of the : on that line.
: only comes after the original definition ie: def getname(self): and is always followed by an indented line that declares the function. When you are calling a function you don't do this.
Answer: Change
Person.__init__(self, first, last, age): to
super().__init__(first, last, age)

can’t inherit from superclass


Nginx: Temporary Files Cleanup Automatically

Question: I installed Nginx Admin (v4.5 Stable) in plugins of WHM. i feel it's making load on server when there a lot of files generated in /tmp/nginx_client/ directory. i want some cronjob which run Temporary Files Cleanup operation automatically. Or is there any predefined action to do this ? Any help would be much appreciated. Thanks
Answer: open cron file:
<code>crontab -u root -e
</code>
write down the following lines
<code>#flush nginx tmp files.
# 360 = 6hrs
*/59 * * * * find /tmp/nginx_client/* -mmin +360 -delete
</code>
also tmpwatch can help you.


Marklogic -How to add the collection name in cts:uris

Question: Query:
let $collection := "sampledata"

for $uri1 in cts:uris((),(),(
cts:element-query(xs:QName("root"),
cts:and-query((
cts:element-attribute-value-query(xs:QName("root"),xs:QName($value1),$value2),
cts:element-attribute-value-query(xs:QName("root"),xs:QName($value3),$value4),
cts:element-value-query(xs:QName("year"),$value5),
cts:element-value-query(xs:QName("month"),$value6),
cts:element-attribute-value-query(xs:QName("num"),xs:QName("value"),$value7)
)))) )

return $uri1

How to add the collection name in above mentioned xquery.
Answer: You can use cts:collection-query(), as in:
cts:and-query((
    cts:collection-query("sampledata"),
    cts:element-query(...)
    ))

See:
http://docs.marklogic.com/cts:collection-query
By the way, when just returning the uri, there's no need the for/return iteration.  The result is the same as just returning cts:uris().
Hoping that helps,


How do I update a menu after a button press in PyGTK?

Question: I am not that familiar with PyGTK. Please see the following code. Is it possible to make it do the following?

There are two buttons, which we refer to as "generate" and "view".
The "generate" button will generate random values for variables A and B.
The "view" button will pop up a menu showing A and B.

The problem with the following code is that the "view" menu shows A and B, but the menu does not update as the user presses the "generate" button.
I ran the code with Python 2.6.6.
Please also suggest any ways that I can improve the code (formatting, style, PyGTK conventions, ...). Thank you in advance.
   """Generate values for two variables A and B."""
# ------------------------------------------------------------------------------
# Winston C. Yang
# Created 2010-12-04
# ------------------------------------------------------------------------------
# Python modules. Be alphabetical.
import random
# ------------------------------------------------------------------------------
# Other Python modules. Be alphabetical.
import gtk
import pygtk
pygtk.require("2.0")
# ------------------------------------------------------------------------------
class Generator:

    """Generate values for two variables A and B."""

    def __init__(self):

        # Create a dictionary in which a key is a variable name and a
        # (dictionary) value is the variable value.
        self.d_variable_value = {}
        # ----------------------------------------------------------------------
        window = gtk.Window()
        window.set_title("Generate")
        window.connect("destroy", self.quit_event)
        # ----------------------------------------------------------------------
        # Create a vertical box with two buttons.
        vbox = gtk.VBox()

        # Create a button to generate values for A and B.
        b = gtk.Button("Generate A and B")
        vbox.pack_start(b)
        b.connect("clicked", self.generate_variable_values)

        # Create a button to view A and B.
        b = gtk.Button("View A and B")
        vbox.pack_start(b)
        b.connect_object("event", self.button_press, self.create_menu())
        # ----------------------------------------------------------------------
        window.add(vbox)
        window.show_all()
    # --------------------------------------------------------------------------
    def quit_event(self, widget=None, event=None):
        """Quit."""
        gtk.main_quit()
    # --------------------------------------------------------------------------
    def generate_variable_values(self, widget=None):
        """Generate values for A and B."""
        self.d_variable_value = {
            "A" : random.randint(0, 10),
            "B" : random.randint(0, 10),
            }

        print "I generated " + str(self.d_variable_value)
    # --------------------------------------------------------------------------
    def button_press(self, widget, event):
        """button_press method."""
        if event.type == gtk.gdk.BUTTON_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            return True

        return False
    # --------------------------------------------------------------------------
    def create_menu(self):
        """Create a menu showing A and B."""
        # How can I update the menu after the user presses the
        # "generate" button?

        # If there are no values for A and B, generate them.
        if not self.d_variable_value:
            self.generate_variable_values()

        # Show A and B in a menu.
        menu = gtk.Menu()

        for key, value in sorted(self.d_variable_value.items()):

            text = key + " " + str(value)
            item = gtk.MenuItem(text)
            item.show()
            menu.append(item)

        return menu
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    Generator()
    gtk.main()

Answer: This line b.connect_object("event", self.button_press, self.create_menu()) is connecting self.button_press to the event signal on a gtk.Menu created by self.create_menu(). This line is never executed again, so the menu is always the same.
What I did was connect the event signal for the View A and B button to the self.button_press handler, and that handler creates an updated menu every time it's run.
# ------------------------------------------------------------------------------
# Python modules. Be alphabetical.
import random
# ------------------------------------------------------------------------------
# Other Python modules. Be alphabetical.
import gtk
import pygtk
pygtk.require("2.0")
# ------------------------------------------------------------------------------
class Generator:

    """Generate values for two variables A and B."""

    def __init__(self):

        # Create a dictionary in which a key is a variable name and a
        # (dictionary) value is the variable value.
        self.d_variable_value = {}
        # ----------------------------------------------------------------------
        window = gtk.Window()
        window.set_title("Generate")
        window.connect("destroy", self.quit_event)
        # ----------------------------------------------------------------------
        # Create a vertical box with two buttons.
        vbox = gtk.VBox()

        # Create a button to generate values for A and B.
        b = gtk.Button("Generate A and B")
        vbox.pack_start(b)
        b.connect("clicked", self.generate_variable_values)

        # Create a button to view A and B.
        b = gtk.Button("View A and B")
        vbox.pack_start(b)
        b.connect("event", self.button_press)
        # ----------------------------------------------------------------------
        window.add(vbox)
        window.show_all()
    # --------------------------------------------------------------------------
    def quit_event(self, widget=None, event=None):
        """Quit."""
        gtk.main_quit()
    # --------------------------------------------------------------------------
    def generate_variable_values(self, widget=None):
        """Generate values for A and B."""
        self.d_variable_value = {
            "A" : random.randint(0, 10),
            "B" : random.randint(0, 10),
            }

        print "I generated " + str(self.d_variable_value)
    # --------------------------------------------------------------------------
    def button_press(self, button, event):
        """button_press method."""
        if event.type == gtk.gdk.BUTTON_PRESS:
            menu = self.create_menu()
            menu.popup(None, None, None, event.button, event.time)
            return True

        return False
    # --------------------------------------------------------------------------
    def create_menu(self):
        """Create a menu showing A and B."""
        # How can I update the menu after the user presses the
        # "generate" button?

        # If there are no values for A and B, generate them.
        if not self.d_variable_value:
            self.generate_variable_values()

        # Show A and B in a menu.
        menu = gtk.Menu()

        print self.d_variable_value
        for key, value in sorted(self.d_variable_value.items()):

            text = key + " " + str(value)
            item = gtk.MenuItem(text)
            item.show()
            menu.append(item)

        return menu
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    Generator()
    gtk.main()


What if an octave was three times the frequency of the root?

Question: In Western music, probably others, a root note, say middle C, and the octave above are differ by an order of two in regards to frequency of the note.
When played together, they sound completely harmonious, if a little boring. And there are 11 notes between them, each jumping up about 2^1/12 between them, with some corrections made for Western music that I don't care about here.
What if instead of an octave frequency differing by a factor of 2, it differed by a factor of 3?
Part of what makes a factor of 2 in 12 semitones work is that 2^(7/12) ~ 3/2 and 2^(5/12) ~ 4/3 for the fifth and fourth respectively. Would a different number of intervals work for an 3x octave? Has anyone tried this and did it work or are our ears too attuned to the Western scales?
Comment: I suggest dividing a "tritave" into 19 equal parts.
Comment: What is the motivation of this question? Why the number 3, rather than 5, 7 or π? You seem to neither know how it would sound, nor know how to calculate the interval sizes... perhaps asking about how to do it would be a better direction for exploration?
Comment: No, 2 is not just a status quo. For most people, sounds an octave apart sound very similar, which is perhaps due to the inner ear structure, which gives the factor of 2 a very special place. Factor of 3, while consonant, doesn't have the same property. With various equal divisions of 3 you will get some intervals which sound ok (in Western standards), and some which sound bad. I expect the same for mostly any number.
Comment: You say "in Western standards", and that's a key point right there. What sounds similar or consonant is at least in part a cultural phenomenon. In other words, very much the status quo.
Comment: **FYI:** Anybody who wants to hear a 3:1 interval, Just play a "C" on your piano, and then play the "G" an octave and a half higher (or, play any note, and then play whatever note is 19 semi-tones higher.) It's not exactly 3:1 (thanks, J.S. Bach!) but it's _really_ close: Approx 2.997:1.
Comment: @mathlander interesting.  I've thought of dividing a fifth into seven equal parts, but your approach yields somewhat smaller parts.  Maybe we should divide 768:5 into 87 equal parts.
Comment: pi wouldn't sound good, I don't think. Has to be a whole number and 2 is just the status quo, so 3 is the next best thing. No, please answer the question as stated.
Comment: @SolomonSlow Bach has little to do with the ratio between C and G being different from 3:1.  In fact, many of the circulating temperaments used in Bach's day did have several justly tuned fifths, in contrast to earlier meantone temperaments where most of the twelfths would have been rather smaller -- in some cases as small as 2.986:1 (a quarter-comma tempered twelfth is 2.991:1).  Some circulating temperaments even had wide fifths; for example the fifth from A flat to E flat in Werckmeister IV 3.006:1 -- https://en.wikipedia.org/wiki/Werckmeister_temperament
Comment: @LeonhardEuler True, you said in Western music. Your nitpicking skills are amazing.
Comment: Also: [Wikipedia - Category:Non–octave-repeating scales](https://en.wikipedia.org/wiki/Category:Non%E2%80%93octave-repeating_scales)
Comment: @user1079505 Do you have any references about "the inner ear structure" relating to the factor of 2 octave? The second part of your comment is the same as my question.
Comment: See this answer, and the link there https://music.stackexchange.com/a/44792/63781
Comment: @RobertM. I don't say "in Western standards".
Answer: The tripling of the root frequency being considered as the unison is the basis of the Bohlen-Pierce scale. This scale in its equal-tempered chromatic form has thirteen 'semitones' of approximately 146.3 cents between the root and the 'tritave' (semantic equivalent of the octave), and in its diatonic form has ten notes (inclusive) between the root and the tritave. It has 'major' and 'minor' chords, and many of the concepts from standard music theory can be applied to the B-P scale analogously.
Comment: I had never heard of this, so I went looking and I've been listening to some examples, especially Elaine Walker's stuff. Holy...it's amazing.
Comment: The semantic equivalent of _octave_ (_eighth_ step from latin _octava_) would not be _tritave_ (which is even linguistically wrong, the _third_ step would be the _tertia_). If it is made up of 10 diatonic steps (inclusive) it would be the _decime_.
Comment: To address the "numerical coincidences" in last part of the OP's question: the Bohlen-Pierce scale exploits the fact that 3^(3/13) ≈ 9/7, 3^(4/13) ≈ 7/5, and 3^(6/13) ≈ 5/3.
Comment: @RobertM. Would you have an example of song (Youtube or other) by Elaine Walker which is representative of this style? I'd love to discover it!
Comment: @Basj https://www.youtube.com/watch?v=60SYLdMYvcE or http://ziaspace.com/ZIA/mp3s/StickMen.mp3
Comment: Years ago, I remapped a midi-capable piano so that semitones became half-semitones, everything centered at middle C. Sure, by that point I'd been heavily conditioned... but I could not figure out any "new" music that I could tolerate listening-to! :)
Comment: The actual scale: https://upload.wikimedia.org/wikipedia/commons/8/82/BP_Just_Lambda_Scale.ogg
Comment: @JamesK Nive indeed! Question: would https://www.youtube.com/watch?v=60SYLdMYvcE be playable with a normal 12-semitone tempered scale? It doesn't seem so far from standard chords, and the voice seems not far from a standard scale.
Comment: I'm pretty sure you need either specialist instruments (the modified keytar she plays) or quite a bit of "unlearning" where to finger the violin.  An instrument, like a violin, that can in principle make any pitch could be played.  An instrument like a piano couldn't.  Nor could a guitar, as the semitone interval is "hard-wired" into the spacing of the frets.
Comment: @Lazy Octave is such a terrible name for the doubled fundamental, referring to eight steps of *different sizes*, that there seems little point in trying to salvage it.
Comment: @RussellBorogove Look up Gurdjieff's idea of the enneagram. You can safely ignore the silly "enneagram of personality" stuff.
Comment: @Basj Also https://www.youtube.com/watch?v=ImT4XMVr-5s. But you can also search for Bohlen-Pierce or Elaine Walker yourself. ;)
Comment: @RobertM. Yes sure, I already did, and listened to a few songs, but it's always interesting to have other people's recommandations ;)


Inserir só a linha preenchida em php

Question: Tenho este código:
<?php

$j=0;

    while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {

$tabela1 .= '
';

$tabela1 .= ' <input type="text" size="45" name= "NomeUtente[]" id= "NomeUtente" value="'.$rows_cursos['nome'].'">	';

$tabela1 .= ' <input type="text" size="1" name= "Quarto[]" id= "Quarto" value="'.$rows_cursos['Quarto'].'">	';

$tabela1 .= ' <input type="datetime" name= "DataRegisto[]" id= "DataRegisto" value="'. date("Y-m-d H:i:s") .'">	';

$tabela1 .= ' <input type="checkbox" name= "Miccao['.$j.']"> Realizado <input type="text" name= "Tipo1[]" id= "Tipo1" size="30" >	';

$tabela1 .= ' <input type="checkbox" name= "Dejeccao['.$j.']"> Realizado <input type="text" name= "Tipo[]" id= "Tipo" size="30" >	';

$tabela1 .= ' <select name="Colaborador[]" id="Colaborador">
   <option value="xxxxxxxxxxxx">xxxxxxxxxxxxx</option>
</select>	';

$tabela1 .= '
';

$j++;
    }

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= '
';

echo "<form method='POST' action=''>";
echo $tabela1;

echo "<input type='submit' name='registar' value='Registo'>";

echo "</form>";

echo "
";
echo "
";

?>

Para inserir tenho o seguinte:
<?php
if(isset($_POST['registar']))
{
$NomeUtente = $_POST['NomeUtente'];

for ($i=0;$i<count($_POST["NomeUtente"]);$i++) {
$utente = $_POST['NomeUtente'][$i];
$quarto = $_POST['Quarto'][$i];
$data = $_POST['DataRegisto'][$i];
$miccao = $_POST['Miccao'][$i];
$tipo1 = $_POST['Tipo1'][$i];
$dejeccao = $_POST['Dejeccao'][$i];
$tipo = $_POST['Tipo'][$i];
$colaborador = $_POST['Colaborador'][$i];

$miccao = $miccao == "on" ? "Realizado" : "";
$dejeccao = $dejeccao == "on" ? "Realizado" : "";

    $sql = "INSERT INTO registoMiDe (NomeUtente, Quarto, DataRegisto, Miccao, Tipo1, Dejeccao, Tipo, Colaborador) VALUES ('$utente', '$quarto', '$data', '$hora', '$miccao', '$tipo1', '$dejeccao', '$tipo', '$colaborador')";
$res = mysqli_query($conn,$sql);

}
}
?>

Agora só devia inserir na tabela as linhas em que seleciono uma ou as duas checkboxes, mas assim está a inserir as linhas todas quando faço registar na tabela da base de dados. Estava a funcionar bem, enquanto não mostrava o valor no campo DataRegisto
Esta foi a alteração que realizei e deixou de funcionar:
$tabela1 .= ' <input type="datetime-local" name= "DataRegisto[]" id= "DataRegisto" >	';

para
$tabela1 .= ' <input type="datetime" name= "DataRegisto[]" id= "DataRegisto" value="'. date("Y-m-d H:i:s") .'">	';

Answer: Tente fazer assim:
... código anterior ...

$utente = $_POST['NomeUtente'][$i];
$quarto = $_POST['Quarto'][$i];
$data = $_POST['DataRegisto'][$i];
$miccao = isset($_POST['Miccao'][$i]) ? $_POST['Miccao'][$i] : false; // verfica se está marcado
$tipo1 = $_POST['Tipo1'][$i];
$dejeccao = isset($_POST['Dejeccao'][$i]) ? $_POST['Dejeccao'][$i] : false; // verifica se está marcado
$tipo = $_POST['Tipo'][$i];
$colaborador = $_POST['Colaborador'][$i];

if($dejeccao !== false || $miccao !== false){ // aqui está o pulo do gato
    // se dejeccao estiver marcado OU miccao estiver marcado ...

    $miccao = $miccao == "on" ? "Realizado" : "";
    $dejeccao = $dejeccao == "on" ? "Realizado" : "";

    $sql = "INSERT INTO registoMiDe (NomeUtente, Quarto, DataRegisto, Miccao, Tipo1, Dejeccao, Tipo, Colaborador) VALUES ('$utente', '$quarto', '$data', '$hora', '$miccao', '$tipo1', '$dejeccao', '$tipo', '$colaborador')";
    $res = mysqli_query($conn,$sql);
}

... código posterior ...

Desta forma ele irá inserir APENAS os registros com checkbox marcados.
Answer: De acordo com essa parte do código:
$miccao = $miccao == "on" ? "Realizado" : "";
$dejeccao = $dejeccao == "on" ? "Realizado" : "";

Você pode envolver a linha que faz o INSERT no banco com um if verificando se uma das variáveis não está vazia. Ficaria assim:
if( $miccao != "" || $dejeccao != "" ){
 // linha do INSERT
}

Aplicando ao código:
<?php
if(isset($_POST['registar']))
{
$NomeUtente = $_POST['NomeUtente'];

for ($i=0;$i<count($_POST["NomeUtente"]);$i++) {
$utente = $_POST['NomeUtente'][$i];
$quarto = $_POST['Quarto'][$i];
$data = $_POST['DataRegisto'][$i];
$miccao = $_POST['Miccao'][$i];
$tipo1 = $_POST['Tipo1'][$i];
$dejeccao = $_POST['Dejeccao'][$i];
$tipo = $_POST['Tipo'][$i];
$colaborador = $_POST['Colaborador'][$i];

$miccao = $miccao == "on" ? "Realizado" : "";
$dejeccao = $dejeccao == "on" ? "Realizado" : "";

if( $miccao != "" || $dejeccao != "" ){
    $sql = "INSERT INTO registoMiDe (NomeUtente, Quarto, DataRegisto, Miccao, Tipo1, Dejeccao, Tipo, Colaborador) VALUES ('$utente', '$quarto', '$data', '$hora', '$miccao', '$tipo1', '$dejeccao', '$tipo', '$colaborador')";
    $res = mysqli_query($conn,$sql);
}

}
}
?>

Comment: verdade... Era mais simples do que eu propus. kkkk

Inserir só a linha preenchida em php


Erro de conversão ao tentar inserir no banco com entity e c#

Question: Esse é o método para inserir:
public virtual void Inserir(T item)
        {
            contexto.Set<T>().Add(item);
            contexto.SaveChanges();
        }

Criei um método passando os parâmetros para meu objeto e depois chamar o método inserir, assim(tentei evitar o "linguição", mas não consegui):
private void InserirBalanca(int ticket, DateTime dtlancamento, string fornecedor, string motorista, string placa, decimal peso,
                                    decimal umidade, decimal impureza, decimal pesoliq, decimal desconto, decimal valorsec, decimal saca,
                                    decimal tabela, string pesagem)
        {
            SiloContext contexto = new SiloContext();
            IRepositorio<Balanca> insere = new Repositorio<Balanca>(contexto);

            var balanca = contexto.Balancas;

            foreach(var blc in balanca)
            {
                blc.Ticket = ticket;
                blc.DtLancamento = dtlancamento;
                blc.Fornecedor = fornecedor;
                blc.Motorista = motorista;
                blc.Placa = placa;
                blc.Peso = peso;
                blc.Umidade = umidade;
                blc.Impureza = impureza;
                blc.PesoLiq = pesoliq;
                blc.Desconto = desconto;
                blc.ValorSec = valorsec;
                blc.Saca = saca;
                blc.Tabela = tabela;
                blc.Pesagem = pesagem;
                balanca.Add(blc);
            }

            insere.Inserir(balanca);
        }

Nessa linha insere.Inserir(balanca);, está dando erro de cast, veja a imagem:

Consultei esse erro na net, mas não veio resultado, creio que é por causa do nome Balanca.
Comment: São recebidos dados para inserir uma única balança correto? se sim , qual motivo para realizar um for each?
Answer: cara, o seu balanca vem do contexto.Balancas; logo, é um DbSet. O método inserir espera receber um objeto Balanca
também não entendi o pq do foreach, mas, de acordo com seu código o que você está querendo fazer deveria ficar +- assim:
        foreach(var blc in balanca)
        {
            blc.Ticket = ticket;
            blc.DtLancamento = dtlancamento;
            blc.Fornecedor = fornecedor;
            blc.Motorista = motorista;
            blc.Placa = placa;
            blc.Peso = peso;
            blc.Umidade = umidade;
            blc.Impureza = impureza;
            blc.PesoLiq = pesoliq;
            blc.Desconto = desconto;
            blc.ValorSec = valorsec;
            blc.Saca = saca;
            blc.Tabela = tabela;
            blc.Pesagem = pesagem;
            insere.Inserir(blc);
        }

Edit:
Conforme eu e Alexandre comentamos, não entendemos o porque do foreach, ou seja, porque você percorre todos os registros armazenados no banco, e sai inserindo todos novamente com os novos valores passados. Você deveria apenas criar um novo objeto Balanca e inserir. Ficaria assim:
    private void InserirBalanca(int ticket, DateTime dtlancamento, string fornecedor, string motorista, string placa, decimal peso,
                                decimal umidade, decimal impureza, decimal pesoliq, decimal desconto, decimal valorsec, decimal saca,
                                decimal tabela, string pesagem)
    {
        SiloContext contexto = new SiloContext();
        IRepositorio<Balanca> insere = new Repositorio<Balanca>(contexto);

        var blc = new Balanca();
        blc.Ticket = ticket;
        blc.DtLancamento = dtlancamento;
        blc.Fornecedor = fornecedor;
        blc.Motorista = motorista;
        blc.Placa = placa;
        blc.Peso = peso;
        blc.Umidade = umidade;
        blc.Impureza = impureza;
        blc.PesoLiq = pesoliq;
        blc.Desconto = desconto;
        blc.ValorSec = valorsec;
        blc.Saca = saca;
        blc.Tabela = tabela;
        blc.Pesagem = pesagem;

        insere.Inserir(blc);
    }

Espero ter ajudado.
Comment: Eu fiz o foreach, por não saber fazer de outra forma, ou seja, carregar meu objeto com dados e depois persistir. Como eu disse, não consegui evitar o linguição e estou até procurando uma outra forma de fazer, que não seja dessa forma, mas por enquanto vou testando assim. Eu já havia resolvido, mas marquei sua resposta.
Comment: @pnet editei a resposta para explicar a questão do foreach, veja se lhe ajuda.
Comment: Ok, melhorou sim.


Markov chains - transition matrix - probabilty formula and application help?

Question: Consider the $3\times3$ transition matrix
$$
\begin{array}{c|ccc}
  &A &B &C \\
\hline
A &0.2 & 0.3 &0.5\\
B &0.3 & 0.5 &0.2\\
C &0.3 & 0.3 & 0.4
\end{array}.
$$
Given that the chain starts in state $B$ what is the probability that after three transitions it is back in state $B$ having visited $A$ and $C$?
I have a few exam paper questions similar to this but I can only find one sort of formula related to this in my notes and it's not very clear and no examples. I was wondering if someone could give me a formula for these types of problems and show me how to apply it to this question and how to use it for others?
Many thanks in advance. :)
Answer: $$B\Rightarrow C\Rightarrow A\Rightarrow B$$
$$P(x_0=B,x_1=C,x_2=A,x_3=B)=P(x_0=B)\ P(x_1=C|x_0=B)$$
$$\qquad \qquad \qquad P(x_2=A|x_1=C)\ P(x_3=B|x_2=A)$$
$$P(x_0=B,x_1=C,x_2=A,x_3=B)=1\times 0.2\times 0.3\times 0.3=0.018$$
or
$$B\Rightarrow A\Rightarrow C\Rightarrow B$$
$$P(x_0=B,x_1=A,x_2=C,x_3=B)=P(x_0=B)\ P(x_1=A|x_0=B)$$
$$\qquad \qquad \qquad P(x_2=C|x_1=A)\ P(x_3=B|x_2=C)$$
$$P(x_0=B,x_1=A,x_2=C,x_3=B)=1\times 0.3\times 0.5\times 0.3=0.045$$
and in total
$$P=0.063$$
-----------Transition Matrix------------
\begin{array}{c|ccc}
  &A &B &C \\
\hline
A &P(A|A) &P(B|A) &P(C|A)\\
B &P(A|B) &P(B|B) &P(C|B)\\
C &P(A|C) &P(B|C) &P(C|C)
\end{array}
which means if you select (2,1) it means that you look up for the probability of transition from B to A. Rows are for current state and columns for next state.
Comment: @Swayy check for edit.
Comment: So say a chain starts in state C what is the probability that after two transitions it is in A?
Comment: I meant to add:
$C \rightarrow B \rightarrow A$ or $C \rightarrow A \rightarrow A$ or $C \rightarrow C \rightarrow A$

So taking the first one:

$P(x_0 = C)P(x_1 = B |x_0 = C)P(x_2 = A | x_1 = B)P(x_0=C, x_1 = B, x_3 = A)$ I guess what I'm asking is where are the numbers coming from. I'm a little confused. Thanks :)
Comment: That's perfect! Thanks so much! :)


Pegar id de dois elementos html?

Question: Eu tenho um array de inputs e uso pra gravar no banco
/*ANSWERS */
foreach($params['questionnaire_questions_answers'] as $key => $item){
    $student_anamineses_answers = DB::table('student_anamineses_answers')->insert(
        array(
            'student_anamnese_id' => $id,
            'questionnaire_question_id' => 2,/*VER COMO GRAVAR O questionnaire_question_id DINAMICAMENTE */
            'answer' => $item
        )
    );
}
/*ANSWERS */

O problema é questionnaire_question_id está em outro input:
<input type="hidden" name="questionnaire_question_id[]" value="'+ item.id +'" />\
<textarea required name="questionnaire_questions_answers[]" cols="80"
   placeholder="Digite a resposta aqui" rows="3" id="perguntas"></textarea>')

É um sistema de perguntas e respostas. Eu gravo a pergunta tabela chamada question e depois preciso gravar as respostas na tabelas answers. Eu faço um foreach pra pegar o id do textarea questionnaire_questions_answers e assim poder gravar a resposta na tabela answers. Só que eu preciso pegar o id do questionario, q eu passo no input questionnaire_question_id. Quando eu faço um foreach nos textareas eu consigo pegar os dados (answers) e gravar no bano, mas não sei como fazer pra pegar o id do questionario e gravar na mesma tabela answers.
Como percorrer esse input e gravar as informações em questionnaire_question_id?
Comment: Eu não entendi bem, o problema, esse input ele é enviado junto dos outros dados ? consegue explicar o processo que está acontecendo, a pergunta está um pouco vaga.
Comment: Também não entendi muito bem o que deseja, você deseja aceder o `questionnaire_question_id` que está associado com a  `questionnaire_questions_answers`? Se assim for quando percorrer um  guarde o `index` e use no array do outro elemento. Penso que deseja fazer isto `questionnaire_questions_answers[0]` `questionnaire_question_id[0]`
Comment: editei a pergunta pra ver se facilita o entendimento
Answer: Como os dois ids são variáveis distintas você tem que saber qual é a posição que deseja aceder.
Pode usar o foreach mas terá de criar previamente uma variável para armazenar a posição actual para depois conseguir relacionar com o outro array. Exemplo:
/*ANSWERS */
$acc = 0;
$outros_ids = $params['questionnaire_question_id'];
foreach($params['questionnaire_questions_answers'] as $key => $item){
    $student_anamineses_answers = DB::table('student_anamineses_answers')->insert(
        array(
            'student_anamnese_id' => $id,
            'questionnaire_question_id' => $outros_ids[$acc++],/*VER COMO GRAVAR O questionnaire_question_id DINAMICAMENTE */
            'answer' => $item
        )
    );
}
/*ANSWERS */

Outra solução poderia ser a utilização da função array_shift que remove o primeiro valor de um array e retorna-o.
/*ANSWERS */
$outros_ids = $params['questionnaire_question_id'];
foreach($params['questionnaire_questions_answers'] as $key => $item){
    $student_anamineses_answers = DB::table('student_anamineses_answers')->insert(
        array(
            'student_anamnese_id' => $id,
            'questionnaire_question_id' => array_shift($outros_ids),/*VER COMO GRAVAR O questionnaire_question_id DINAMICAMENTE */
            'answer' => $item
        )
    );
}
/*ANSWERS */

Pelo que percebi da sua pergunta é isto o que pretende fazer, corrija-me se tiver errado.

Pegar id de dois elementos html?


How can I fix recurring PHP 503 Errors on my Apache-mod_proxy_fcgi-PHP-FPM Server?

Question: i'm having trouble with my php-fpm setup. Maybe you guys can point me in the right direction.
First off, everything is working fine. But every now and then, I'll get 503 Errors. Those errors are gone once I reload the website. They only ever appear on php sites and are not isolated to one domain or one framework. I am receiving the 503 errors in PHPmyAdmin, Wordpress and Typo3. Those are the 3 sites I have tested. They are on seperate vhosts and have different php-fpm pools, but they share the same php-fpm master prozess.
The server I am running is Apache 2.4 (MPM-Event Workers), without mod_php or cgi/fastcgi. Instead, I'm using mod_proxy and mod_proxy_fcgi to pass every .php file to my php-fpm process.
One thing to note is, the server is not yet in production, so there is little to no traffic at all. Server Hardware is strong, 12 VCores und 32 GB Ram.
My mod_proxy and mod_proxy_fcgi setups are default - I haven't changed anything there.
My vhost config (the proxy part):
<FilesMatch "\.php$">
        SetHandler "proxy:unix:///opt/php-5.6.11/var/run/php5-fpm-mywebsite.sock|fcgi://mywebsite/"
    </FilesMatch>
    <Proxy fcgi://mywebsite/ enablereuse=on retry=0>
</Proxy>

Note: I have had max=10 in the Proxy directive before and it seemed to produce the 503 error more often. Now that I have removed max=10, it seems to occur less. Might just be coincidence though.
My PHP-FPM Pool Config (the relevant parts):
listen = var/run/php5-fpm-mywebsite.sock
listen.owner = mywebsite
listen.group = www-data
listen.mode = 0660
listen.backlog = 65535

user = mywebsite
group = www-data
listen.allowed_clients = 127.0.0.1

pm = ondemand
pm.max_children = 20
pm.process_idle_timeout = 15s

request_terminate_timeout = 300s
rlimit_files = 131072
rlimit_core = unlimited
catch_workers_output = no

My PHP-FPM Config (the relevant parts):
emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 10
events.mechanism = epoll

My PHP.ini for the PHP-FPM Master Process.
Everything not listed here, is either default php settings or should not be relevant:
memory_limit = 400M
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 600
max_input_time  = -1
max_input_vars = 10000
suhosin.get.max_vars = 10000
suhosin.post.max_vars = 10000

[Zend]
zend_extension=/opt/php-5.6.11/lib/php/extensions/no-debug-non-zts-20131226/ioncube.so
zend_extension=opcache.so
opcache.revalidate_freq=0
;opcache.validate_timestamps=0
opcache.max_accelerated_files=50000
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.fast_shutdown=1

[APC]
extension=apcu.so
apc.enabled=1
apc.shm_segments = 1
apc.shm_size=256M
apc.ttl=7200
apc.user_ttl=7200
apc.gc_ttl=3600
apc.stat=1
apc.enable_cli=0
apc.file_update_protection=2
apc.max_file_size=2M
apc.include_once_override=0
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.cache_by_default=1
apc.use_request_time=1
apc.slam_defense=0
apc.stat_ctime=0
apc.canonicalize=1
apc.write_lock=1
apc.report_autofilter=0
apc.rfc1867=0
apc.rfc1867_prefix =upload_
apc.rfc1867_name=APC_UPLOAD_PROGRESS
apc.rfc1867_freq=0
apc.rfc1867_ttl=3600
apc.lazy_classes=0
apc.lazy_functions=0

extension=memcache.so
extension=memcached.so

Note: Memcached has 1 GB of memory allocated to it.
Apache Error Log
The actual error message from the apache error.log. The error message if always the same. (I have enabled verbose proxy logging):
[proxy:debug] [pid 141760:tid 140526898214656] mod_proxy.c(1159): [client myclient] AH01143: Running scheme unix handler (attempt 0), referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy_fcgi:debug] [pid 141760:tid 140526898214656] mod_proxy_fcgi.c(879): [client myclient] AH01076: url: fcgi://mywebsite//var/www/html/mywebsite/htdocs/typo3site/website/index.php proxyname: (null) proxyport: 0, referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy_fcgi:debug] [pid 141760:tid 140526898214656] mod_proxy_fcgi.c(886): [client myclient] AH01078: serving URL fcgi://mywebsite//var/www/html/mywebsite/htdocs/typo3site/website/index.php, referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy:debug] [pid 141760:tid 140526898214656] proxy_util.c(2147): AH00942: FCGI: has acquired connection for (mywebsite)
[proxy:debug] [pid 141760:tid 140526898214656] proxy_util.c(2200): [client myclient] AH00944: connecting fcgi://mywebsite//var/www/html/mywebsite/htdocs/typo3site/website/index.php to mywebsite:8000, referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy:debug] [pid 141760:tid 140526898214656] proxy_util.c(2237): [client myclient] AH02545: fcgi: has determined UDS as /opt/php-5.6.11/var/run/php5-fpm-mywebsite.sock, referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy:debug] [pid 141760:tid 140526898214656] proxy_util.c(2409): [client myclient] AH00947: connected //var/www/html/mywebsite/htdocs/typo3site/website/index.php to httpd-UDS:0, referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy_fcgi:error] [pid 141760:tid 140526898214656] [client myclient] AH01067: Failed to read FastCGI header, referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy_fcgi:error] [pid 141760:tid 140526898214656] (104)Connection reset by peer: [client myclient] AH01075: Error dispatching request to : , referer: http://mywebsite/website/typo3/install/index.php?TYPO3_INSTALL[type]=cleanup
[proxy:debug] [pid 141760:tid 140526898214656] proxy_util.c(2162): AH00943: FCGI: has released connection for (mywebsite)

Now my question:
How can I fix recurring PHP 503 Errors on my Webserver?
My thoughts:

Maybe mod_proxy_fcgi in UDS mode. But isn't it bad to deactive UDS, performance wise? Can I tweak anything there?
mod_proxy or mod_proxy_fcgi not working correctly with php-fpm or not set up properly?
APC or ZendOPCache or Memcached messing things up? I wouldn't say its the Memory allocated to them, because there is hardly anything going on on the server and there is plenty of free memory
Some Problems with the php.ini config?
Some Problems with the php-fpm config or php-fpm pool config?

I'm not an export on those things, so I'm having a hard time figuring things out. Apache with php-fpm doesn't seem that common either, most google results are nginx based, which doesn't help me much.
Maybe someone here can help me?
Thanks alot!!
Comment: Try removing the `enablereuse=on` option on your Proxy line. That solved the same problem for me.
Comment: How is it that you are running both APC and OPcache?
Comment: Is there anything that says I cant do it? Up until now I thought it was ok? See here: http://stackoverflow.com/questions/27205809/what-is-userland-caching-apcu-extension-in-php
Comment: You can only have one opcode cache. And that question deals with APCu, not APC.
Comment: Wait what, sorry, youre confusing me. I have installed apcu, not apc as shown in the extention above. Have installed it from here: https://pecl.php.net/package/APCu
Answer: Remove the enablereuse=on option on your Proxy line, so that it reads
<Proxy fcgi://mywebsite/ retry=0>

That solved the " Error dispatching request to : , referer... " problem for me.
Answer: I had the same exact issue and after trying to understand what was the cause I found that for us the reason was a buggy plugin.
In particular we fixed the issue by disabling this wordpress plugin: https://wordpress.org/plugins/custom-css-js/
We were using php 7 and wordpress 4.5.6.
So for us was not due to a misconfiguration php, apache or any cache system.
Neither the problem was a no resource available (CPU/RAM) issue.
The problem was due to a buggy plugin.
Was very hard to find which plugins caused the issue.
We understood thanks to php debugging options, so I suggest to add these lines below into wp-config.php to debug:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);

Best luck!
Answer: As the other posts suggested, the enablereuse=on should not be used when PHP-FPM daemon is running via a Unix socket.
The Apache documentation for mod_proxy_fcgi confirms this by saying,

UDS does not currently support connection reuse

UDS means Unix Domain Sockets, which means when you're running PHP-FPM as a socket (.sock), instead of the default TCP port method.
Nathan Zachary goes into great detail about configuring Apache + PHP-FPM as a socket, among other related topics.
I experienced crazy, unpredictable Apache responses immediately after doing a POST with enablereuse=on and UDS. As soon as I removed enablereuse=on and restarted the services the issue went away entirely.
More on symptoms and debugging this issue from the mod_h2 folks.
Comment: While this is not a direct answer to the question, interesting and useful to know. Thanks.
Comment: Interestingly this statement was removed from the apache documentation simply with the comment [UDS does support reuse](https://github.com/apache/httpd/commit/2a3f6ec221f5eeebc6ac1acb0623b500ef5c0841).  I can't claim to know if/when this was fixed.
Answer: Is listen = var/run/php5-fpm-mywebsite.sock correct ?
As for virtual host case, you can try these configuration :

Apache ( in VirtualHost tag )
ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/DOCUMENT_ROOT_OF_VHOST/$1

PHP-FPM pool
listen = 127.0.0.1:9000

If you have no concerns about .htaccess , nginx is recommended.
Answer: I had an issue similar to this and fixed it by moving the folders out of /var/lib/php/opcache/ and then restarting php-fpm.
Possibly Relevant: A user was spamming a PHP URL last night, causing these errors to repeat in our Apache log.
[pid 925] worker.c(1613): AH00288: scoreboard is full, not at MaxRequestWorkers

I am guessing that it caused some cache corruption in a folder located in /var/lib/php/opcache.
For some reason, resetting opcache via the opcache control panel, nor restarting apache/php-fpm, seems to clear those folders out. You have to do it manually.
But that seems to have worked for me.
Answer: We were hitting the default 60 seconds timeout. I added the line ProxyTimeout 300 to the .conf file within the directory /etc/apache2/sites-enabled to make Apache2 wait longer for PHP.
Check how fast you get the HTTP 503 error. If it is within a few seconds, this answer is not for you.
You can find the documentation here: https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#proxytimeout


How to read-write json file outside WAR package?

Question: I am writing a REST API in Java EE 1.6 using JBoss 7 and basic EE frameworks. I compile the WAR package and then deploy it to Jboss standalone folder. I was creating a database to store the API configuration, but it is so little (and needs to be full loaded with the servlet) that I decided a JSON file is enough.
I want to read and write JSON code to a file outside the WAR package, but in the same server JBoss resides (could even be in the same directory as WAR file or other predefined directory).
The reason is that I need this file to be read and written by other applications also.
So How can I perform that reading and writing in the Servlet? I prefer solutions that includes less dependencies as possible, like no container or framework dependencies, except the JSON and IO libraries, if possible.
Thanks in advance!
Comment: This file should not be on public path, so clients can't download it.
Answer: It turns out that File() class can do the job by specifying the directory where file is in the first parameter. Then use it's methods to read, write or append data.


Drupal jquery behaviors & views - Ajax multiple times / wrong arguments - triggerHandler('RefreshView')

Question: I am having some problems using ajax to trigger an views update (D7).
Basically there is a map (leafletMap) and when it is moved/changed/zoomed, a function gets a list of node ids and triggers a views ajax refresh.
Those node ids are passed into a contextual filter, so only matching packages in that view are displayed below the map.
The problem with the ajax is it often fires multiple ajax requests. When I inspect the extra requests one or two will have the correct arguments, but one will have the old arguments and then the view will refresh with the wrong nodes.
I've tried using return false and binding what I can to this or context. As you can see I've tried unbind()ing the
 but nothing seems to help. Often the first set of ajax calls append the wrong view, but then the next one works. And so on. To be honest I'm a bit out of my depth.
Basically I need there to be one ajax call with the correct arguments, or at least multiple ajax calls that use the correct arguments.
Any hints, ideas or suggestions would be most welcome. Many thanks.
TLDR; The below code triggers an ajax refresh of a view. This view has a contextual filter. It is triggering multiple ajax requests, some of which retain the old ajax arguments & therefore refresh incorrectly. Thanks!
Drupal.behaviors.packageFilter = {
    attach: function (context, settings) {

      if (typeof window.leafletMap === 'undefined' || window.leafletMap.length == 0) {
        return;
      }
      this.leafletMap = window.leafletMap[0];
      this.leafletMap.$map.once(function () {
        this.leafletMap.map.on('moveend', this.refreshView.bind(this));
        return false;
      }.bind(this));
      // Reset arguments back to default when not filtering map.
      $.each(Drupal.settings.views.ajaxViews, function (key, value) {

        if (value.view_name === 'packages') {
          Drupal.settings.views.ajaxViews[key].view_args = '';
        }

      });
      $('.views-exposed-form-packages-search', context).attr('action', '/packages.json');
    },

    refreshView: function (context, settings) {

      Drupal.attachBehaviors('ViewsAjaxView');

      // This gets markers from the map and converts them to node ids
      var visibleMarkers = this.leafletMap.getVisibleMarkers();
      var totalMarkers = this.leafletMap.markers.length;

      // Do not run if map isn't filtered.
      if (visibleMarkers.length < totalMarkers) {

        var visibleMarkers = this.leafletMap.getVisibleMarkers();

        var nids = '';
        $.each(visibleMarkers, function (i, v) {
          nids += v.node.nid + '+';
        });
        nids = nids.slice(0, -1);

        // nids is an array of node ids for the view to return

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name === 'packages') {
            // this should add the node ids as an views ajax argument
            // to a contextual filter
            Drupal.settings.views.ajaxViews[key].view_args = nids;
          }

        });

        var throbber = '

';
        $('.views-submit-button').append(throbber);

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name == 'packages' && value.view_args == nids) {
            $('.view-id-packages').triggerHandler('RefreshView');
          }

        });

        $('.view-id-packages').unbind();

      }
    }
  }

Answer: For the sake of posterity & future visitors with this issue, here is how I eventually got it to work.
refreshView: function (context, settings) {
  // Unbind event to prevent multiple ajax refreshes.
  $('.view-id-packages').unbind();
  Drupal.attachBehaviors('ViewsAjaxView');

  // When map changes, update the grid of packages below the map.
  var visibleMarkers = this. leafletMap.getVisibleMarkers();

  // Get all the node IDs to pass into the views contextual filter.
  var nids = '';
  $.each(visibleMarkers, function (i, v) {
    nids += v.node.nid + '+';
  });
  nids = nids.slice(0, -1);

  // Update the Drupal ajax object to use our new set of node IDs.
  $.each(Drupal.settings.views.ajaxViews, function (key, value) {
    if (value.view_name === 'packages') {
      Drupal.settings.views.ajaxViews[key].view_args = nids;
    }
  });

  // Add the throbber on since it doesn't show automatically.
  var throbber = '

';
  $('.views-submit-button').append(throbber);
  // Trigger the ajax.
  $('.view-id-packages').triggerHandler('RefreshView');
}

And then my view > advanced > contextual filter looks like:


Como fazer um select dentro de uma condição?

Question: Como posso fazer para criar um script em SQL onde é executado um SELECT, e conforme o resultado de uma coluna deste primeiro, executa uma determinada condição de uma outra tabela?
exemplo:
select * from tabela as t
SE t.saldo = 0 entao WHERE t2.outracondicao = 'condicao'

Comment: Possível duplicata de [Colocar If no Where](https://pt.stackoverflow.com/questions/262558/colocar-if-no-where)
Comment: Poderia colocar a estrutura das tabelas na sua questão? Não haverá já questões idênticas à sua aqui no SO?
Answer: SELECT *
FROM tabela AS t
WHERE (t.saldo = 0
       AND EXISTS (SELECT 1
                   FROM tabela2 AS t2
                   WHERE t2.outracondicao = 'condicao'))
  -- OR t.saldo <> 0

Quando o saldo for igual a zero, só será executada a pesquisa se a condição da segunda tabela for atendida (como você não mostrou a estrutura das tabelas, mantive na resposta as "informações" que estão na pergunta).
O trecho comentado (--OR t.saldo <> 0) pode ser usado, caso você precise. Ele executará a consulta caso o saldo seja diferente de zero.

Outra alternativa é que a validação seja feita antes da consulta. Se a validação em tabela2 independe de tabela, pode ser feito assim:
IF EXISTS (SELECT 1 FROM tabela2 AS t2 WHERE t2.outracondicao = 'condicao')
BEGIN
    SELECT *
    FROM tabela AS t
    WHERE t.saldo = 0
END

Conforme sugestão de @rbz, criei um exemplo online para validação.
Comment: Nossa cara, agora só que eu vi `t2.outracondicao`. Por isso que vocês estão fazendo `JOIN`... Até apaguei meu outro comentário na pergunta! hahaha valeu!
Comment: Mas se o select não é recursivo, como ele ficará "lendo" o valor do saldo, e "refazendo" o filtro (where)?
Comment: No caso, `saldo` só é validado se a condição que ele precisa da `tabela2` existir.. então traria todos os valores com saldo igual a zero  (se `t2.outracondicao = 'condicao'`)
Comment: Sim, mas o `t.saldo` é da tabela principal. A cada tupla, fará um WHERE? E ainda assim aqui `SELECT 1` ficou confuso. Por favor, faz um SQLFiddle que eu estou com um nó na cabeça! ahahah
Comment: Foi uma boa ideia. _fiddle_ criado.. resposta alterada ;]
Answer: nesse caso, se você tiver dois campos em comum dentro das duas tabelas, pode utilizar o WHERE IN
Digamos que há o campo ID na tabela2 que também está presente na tabela1. Você poderia fazer do seguinte modo:
SELECT * FROM tabela2 WHERE id IN (SELECT id FROM tabela1 WHERE saldo='0')
Essa query irá buscar todos os registros da tabela2 que também estão presentes na tabela1, mas apenas com saldo 0.
Comment: Lucas, acho que um ponto diferente da sua resposta é que você retorna tudo da `tabela2`, mas na pergunta ele pede `select * from tabela` (tabelas diferentes). Além disso, se `id` for um _código_ (preenchimento manual/controlado), a comparação é correta; porém se for um _contador_ (_identity_), possivelmente serão diferentes nas duas tabelas (um não corresponderá ao outro)
Comment: rLinhares, sim, seria interessante sabermos a estrutura das tabelas, como elas se conectam (e se realmente o fazem) e qual a aplicação dos dados. Obrigado pela observação.
Answer: Esse modo poderá te ajudar:
SELECT t.* FROM tabela t
JOIN tabela2 t2
    ON t2.id = t.id
WHERE
    t2.outracondicao = (CASE
                        WHEN t.saldo = 0
                            THEN 'condicao'
                        END)

Comment: Não sei se entendi muito bem a solução, achei meio confuso o join. De qualquer forma, se o saldo for diferente de zero, ele tentaria comparar o `t2.outracondicao` com `NULL`, não?!
Comment: Isso, ele compararia com NULL, para trazer tudo é necessário fazer um ELSE t2.outracondicao.

WHERE t2.outracondicao = (CASE
                                                WHEN t.saldo = 0 THEN 'condicao'
                                                ELSE t2.outracondicao
                                           END)


Bash string how to remove characters after colon but before ampersand

Question: Not sure how to slice this string to remove just the characters after the colon but include the stuff after the ampersand
image="eclipse-temurin:254324@SHA256=f1bb9b6ed77176166"

Expected outcome should be image=eclipse-temurin@SHA256=f1bb9b6ed77176166
Comment: There's no ampersand (`&`). You mean at-sign `@`.
Comment: And what about the double quotes?
Comment: @RenaudPacalet The double quotes aren't in the string, that's just shell syntax when assigning variables.
Comment: @Barmar Well, the shown expected outcome seems to indicate that it is the whole assignment that must be modified, not just the assigned value...
Comment: @RenaudPacalet Maybe, but it could just be poor wording and he means that the expected result is that the variable is equal to that. That's how I interpreted it.
Answer: I assume by 'ampersand' (&), you mean 'at' (@). If so, Try:
image="eclipse-temurin:254324@SHA256=f1bb9b6ed77176166"
echo ${image/:*@/@}

Comment: The pattern is a globbing pattern, not regular expression. So it should just be `:*@`, no `.`
Comment: Thanks. I fixed it. My erroneous pattern worked in testing because `.*` is still valid (one character followed by any number of characters).
Comment: `.*` only matches the specific character `.` in a glob/fnmatch pattern, not _any_ one character as it does in regex. The "any one character" in glob/fnmatch is `?`
Comment: So it does. Silly me.


Why is the k-means++ algorithm probabilistic?

Question: The k-means++ algorithm provides a technique to choose the initial k seeds for the k-means algorithm. It does this by sampling the next point according to a multinomial distribution over the unchosen points (where the probability of a point being chosen as the next center is proportional to $D(x)^2$ with $D(x)$ being the distance of the point $x$ to its nearest center).
The point with the largest distance has the greatest probability of being chosen, but why can I not choose this point every time? What advantage do I gain by being 'fuzzy' with my seed selection?
Answer: You gain in theoretical guarantees on the solutions: the solution found by k-means initialized this way is close to the correct k-means solution (in expectation) with a known constant, cf. these slides for example.
With the method you mention (which was previously used in the literature), you can build some configurations where it behaves badly (think of a point on a separating hyperplane but far far away) for sure (since deterministic).
Answer:
K-means can get stuck in local minima.

Because of this, it is a best practise to run multiple times and keep the best result (best by SSQ).
If you always choose the farthest point, you will get the same result every time. So you do want some randomness!

The farthest point is not the best centroid candidate. It usually is too far out.

The point has the highest probability of being chosen, but the average point chosen is much closer. If there are 10 points at distance^2 10, and one point at distance^2 11, then the algorithm is more likely to choose one of the cluster points than that last outlier.


How to sort field_info_instances return value by field weight?

Question: I'm using field_info_instances() to retrieve the information for all the fields used by a content type, for example calling it as field_info_instances('node','bundle_name').
In the returned array, the fields aren't ordered as I expected. I need to get the fields ordered per weight.
For example, a field weight is 8, in the Manage fields list.

Despite this, it's shown on the top, in the output from field_info_instances().

Is there any possibility to get the fields ordered?
Answer: You probably want something like this
$info = field_info_instances('node','bundle_name');

uasort($info, function($a, $b) {
  $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;

  if ($a_weight == $b_weight) {
    return 0;
  }

  return ($a_weight < $b_weight) ? -1 : 1;
});

// $info is now sorted by weight.


The cofibre of a type $n$ $p$-local CW complex has type $n+1$

Question: I am trying to prove this relatively simple statement from 'Nilpotence and periodicity in Stable Homotopy Theory'

Suppose $X$ as in the periodicity theorem has type $n$. Then the cofibre of the map 1.54 has type $n+1$

The definitions needed:

$X$ is a $p$-local finite CW-complex of type $n$
A finite $p$-local CW complex is a CW complex $X_{(p)}$ associated with a finite CW complex $X$ (this is the topological analogue of localising at  a
prime)
A $p$-local finite complex $X$ has type $n$ if $n$ is the smallest integer such that $\overline{K(n)_*}(X)$ is non-trivial (where $\overline{K(n)_*}(X)$ is the $n$-th Morava K-theory)
The map of 1.54 is a map $f:\Sigma^dX \to X$ such that $K(n)_*(f)$ is an isomorphism and $K(m)_*(f)$ is trivial for $m > n$
Let $W$ be the cofibre of the map $f$

We know that from the  cofibre sequence $X \to \Sigma^d X \to W \to \Sigma X \to \Sigma^{d+1}X \to ...$ that we get a long exact sequence in the Morava K-homology
$$ \cdots  \to \overline{K(m)}_t(\Sigma^d X) \stackrel{f^*}{\to} \overline{K(m)}_t(X) \to \overline{K(m)}_t(W) \to  \overline{K(m)}_{t-1}(\Sigma^d X)\stackrel{f^*}{\to} \cdots$$
For $m>n$ we get $f^*=0$ and we know that $\overline{K(m)_*}(X) \ne 0$ (by another result) and so we get short exact sequences
$$ 0 \to \overline{K(m)}_t(X) \to \overline{K(m)}_t(W) \to  \overline{K(m)}_{t-1}(\Sigma^d X) \simeq \overline{K(m)_{t}}(\Sigma^{d+1}X) \to 0$$
The result follows if the sequence splits (and indeed this is what Ravanel claims),that:
$$\overline{K(m)}_*(W) = \overline{K(m)}_*(X) \oplus \overline{K(m)}_{*}(\Sigma^{d+1}X)$$
I can't see a justification for this splitting - is there any obvious reason this sequence splits?
Answer: By Prop 1.5.2 on p. 7, every graded module over $K(n)_*$ is free, and $K(n)_*(X)$ is a graded module over $K(n)_*$. That gives your splitting.
Comment: Thank you, much simpler then I was imagining!


Acceleration of a particle varies with distance as $-kx$. The particle is initially given a velocity $v_0$. Find time take to reach initial point

Question: $\newcommand{\d}{\mathrm{d}}$I am having a problem here because acceleration varies with distance, and I am not able to relate it with time
\begin{align}
a &=-\frac{kx}{m} \\
v\frac{\d v}{\d x} &= -\frac{kx}{m}
\end{align}
For $x_{\max}$
\begin{align}
0-v_{0}^2 &= -\frac{kx^2}{m} \\
x &= \sqrt{\frac{mv_0}{k}}
\end{align}
But I still can't find time
Comment: You have been given an example of simple harmonic motion https://en.wikipedia.org/wiki/Simple_harmonic_motion#:~:text=In%20mechanics%20and%20physics%2C%20simple,of%2C%20the%20object's%20displacement%20vector.
Comment: Hint: solve line 2 to get v in terms of x. Then substitute v = dx/dt and solve for x in terms of t.
Comment: Well, this is a math discussion area..... but never mind - questions are **inevitable**.....
Answer: $\newcommand{\d}{\mathrm{d}}$We have,
$$
v \,\d v =-Cx \,\d x \\
\int_{v_0}^{v(x)} v \,\d v = -C\int_0^x x\,\d x \\
\frac{v(x)^2-v_0^2}{2}=-Cx \\
v(x)=\sqrt{v_0^2-2Cx},
$$
where $C=\frac km$. Using $v=\frac{\d x}{\d t}$, $$\frac{\d x}{\sqrt{v_0^2-2Cx}} = \d t$$ Now just integrate both sides to get an expression for $x(t)$, after which you need to solve $x(t)=0$.


Applying increasing weights on more recent observations with time series data in a linear regression in Python

Question: So I am using a linear regression with time as a trend variable (specifically, I am taking the # of months since user's first activity as the linear feature of time, and also including the log, sqrt, squared, etc., transformations of that for non-linear time features) and dummy variables for 11/12 months of the year to account for seasonality. I will use forward selection of some sort to pick time features.
My time series is a bit ridiculous, so I find that trend often changes as time goes on. Check out the attached image for one that I am looking at
As such, does anyone know a way I could add an inverse of exponential decay of some sort to the weights in the regression? As in, let's say I have 60 rows of data, from the very first month of user activity to the most recent month. I want to train the regression on all of these, but I want the regression to weight the most recent observations more. There doesn't seem to be a good weighted regression package in Python besides Huber regression, but I cannot apply the weighting I want in that.
I do not think the fact that user_age_in_months is greater at more recent periods than in the first few periods makes a significant difference, especially since I am min-max scaling, and this is different from an exponentially weighted moving average.
This is the closest answer I've seen to this question, but it doesn't really give an example and this isn't as applicable to Python: Assigning more weight to more recent observations in regression
Thanks!
Comment: Some quick ideas: weighted regression is equivalent to OLS data scaled by the square root of your weights. You could also model your trend as an AR(1) $b_t = a_0 + a_1 b_{t-1} + \epsilon_t$ and work out what your estimate of $b_t$ would be based upon past data. On that approach some things to search for might be bayesian filter, Kalman filter, hidden markov model, particle filter.
Answer: Many ML packages give you an option to specify sample weights out of the box. One of the answers to the CV question that you cited gives an example of how this can be done in R. In Python ecosystem, scikit-learn provides an analogical parameter (sample_weight) that you can pass to many different regression models (linear, trees, SVMs, see e.g. here) while fitting.
You can use an arbitrary function to calculate the weights for each sample (in this case, that could be an exponential function of time), and pass it as a Numpy array.


Existence of a limit: concept

Question: When it comes to limit we say $\lim_{x \rightarrow a} f(x)$ exists if and only if
\begin{equation}
\tag{1}
  \lim_{x \to a+} f(x) =  \lim_{x \to  a-} f(x)
\end{equation}
(equating both sides of limit)
It simply implies that $f(x)$ should approach to same value from both sides.
I derive the limit values using the basic limit theorems as in this   link. So far fine. When it comes to one sided limits separately,  I apply the same theorems with left or right direction in mind. If I am able to derive a reasonable value from theorem I can say that one sided limit exists for that particular direction. But I don't think,it is sound in conceptual thinking. I am looking for a mathematical definition of existence of One sided limit as in equation (1) for general limit
What is the mathematical explanation for the existence of   one sided limits such as \begin{equation}
\tag{2}
  \lim_{x \to a+} f(x)
\end{equation}
 ,
 \begin{equation}
\tag{3}
  \lim_{x \to  a-} f(x)
\end{equation}
Is it possible to have a example where
\begin{equation}
\tag{4}
  \lim_{x \to  -a} f(x)  ,  \lim_{x \to  a} f(x)
\end{equation} do not  exists when we consider it separately
Further explanation with example
  A function f(x) is said to be continuous on the right of a if it satisfies conditions
1) $\lim_{x \to  +a} f(x)$ exits
 2) $ f(a)$ is defined
 3)  $\lim_{x \to  +a} f(x)$ =f(a)

DOUBT  How do we decide $\lim_{x \to  +a} f(x)$ exits or not?. We know already how to check existence       with $\lim_{x \to  a} f(x)$   as in equation(1)
Comment: Look at the folowing function $f$, such that. $f(x)=x+1$ for $x>=0$ and $f(x)=x$ for $x<0$. Try to find one-sided limits at 0. Using the definition of one-sided limit you can easily prove that limit from the right is 1 and limit from the left is 0.
Comment: Thanks for the suggestion . I have edited more explanation
Answer: Well, there are many theorems which can be used to evaluate one sided limits (in exactly the same manner as they are used for the usual two sided limits). A successful evaluation of the limit means that it exists. Apart from this there are few theorems which allow us to infer the existence of a limit without performing any evaluation.
One such theorem is the following :

Theorem: Let $f$ be increasing on some interval of type $(a-h, a) $ and let $f$ be also bounded above on this interval. Then $\lim_{x\to a^{-}} f(x) $ exists. A similar result holds for functions increasing and bounded below on $(b, b+h) $ and the limit $\lim_{x\to b^{+}} f(x) $.
Answer: Consider the Heaviside function. Note that as we approach the point $c$ from the right, the limit is $1$, whereas from the left, it is $0$. Hope this is an illuminating example. The limit does not exist if we approach from both sides.
Comment: Thanks for the suggestion . I have edited more explanation
Answer: I hope I understand your question correctly. So you are searching for the definition of one-sided limit.   So $f(x)$ approaches the limit $L$ from the positive(right) side as $x$ aproaches $a$ if and only if for any $\epsilon>0$ there exists $\delta>0$ such that from the inequality $0<x-a<\delta$ we can conclude that $|f(x)-L|<\epsilon$.   Similarly, $f(x)$ approaches the limit $L$ from the negative(left) side as $x$ aproaches $a$ if and only if for any $\epsilon>0$ there exists $\delta>0$ such that from the inequality &0
Answer: Firstly,  One sided limit simply means that the domain of the function is restricted to one of the sides of a where x is approaching in a function f(x).
Now your question on how to know that the one sided limit exists or not then see if
     f(x)=1/x   is your function
Now let x approach 0 from right hand side.
So,
      x=1/10          : f(x) = 10
<code>  x= 1/10000   :f(x) =10000
</code>
So as you are going near to 0 the value of the function is going bigger and bigger even beyond any limit.
So off course limit doesn't exist but you must know what it means by non existence of a limit.  :)

Existence of a limit: concept


Fastest way showing the limit exists without finding the limit?

Question: Let $\{a_n\}$ and $\{b_n\}$ be two integer sequences such that $a_1=b_1=1,$
\begin{align*}
a_n=a_{n-1}+b_{n-1},\qquad\qquad b_n =r\,a_{n-1}+b_{n-1}.
\end{align*}
Where $r$ is a natural number $>1$. ($r$ is a fixed value)
Write $c_n={b_n}/{a_n}$, how to prove the following limit exist without finding it?
\begin{align*}
\lim_{n\to\infty} c_n.
\end{align*}

Attempt

I used mathematical induction to prove $\{c_{2n}\}$ is monotonically decreasing and $\{c_{2n+1}\}$ is monotonically increasing.
Then, note that
\begin{align*}
c_{n+1}=\frac{b_{n+1}}{a_{n+1}}&=\frac{r\,a_n+b_n}{a_n+b_n}\\
&=r-\frac{r-1}{\frac 1{b_n/a_n}+1}<r
\end{align*}
Therefore, $0<c_n<r$.
$\vdots$

Instead of continuing using this method (too complicated), any other faster ways to prove "exist"?
I tried to use the definition of Cauchy sequence and contraction mapping (they are 2 methods), but I don't think they work here.
Any hints or tips are appreciated:)
Answer: Write your formulas in a matrix form:
$$\begin{bmatrix}a_n\\b_n\end{bmatrix} = \begin{bmatrix}1&1\\r&1\end{bmatrix}\begin{bmatrix}a_{n-1}\\b_{n-1}\end{bmatrix}$$
i.e.
$$w_n=Aw_{n-1}$$
Notice that if you normalize every vector after applying $A$, that is if you consider
$$v_n=\frac{Av_{n-1}}{||Av_{n-1}||}$$
instead $w_n$, then it will generate the same $\{c_n\}$. This is because

normalization changes magnitude of the given vector, not its direction
$A$ is a linear transformation; changing the magnitude of its input doesn't change the direction of its output
and finally $c_n$ depends on the n-th direction only.

This formula for $v_n$ above is exactly what power iteration does. The following citation is useful (it has been translated to match our chosen names and starting index):

If $A$ has an eigenvalue that is strictly greater in magnitude than its other eigenvalues and the starting vector $v_{1}$ has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue, then a subsequence $\{v_n\}$ converges to an eigenvector associated with the dominant eigenvalue.

Think about eigenvalues (say: $\lambda$) and how they depend on $r$. You will have to consider a quadratic equation w.r.t. $\lambda$ and its discriminant, which will be of first degree w.r.t. $r$. By analyzing the two you will find that for $r>1$ there are always two distinct real eigenvalues (and none of them is $0$, this will be important in a moment). Apply proper Vieta's formula to show they cannot sum to $0$. They cannot be equal, they cannot be opposite, so one eigenvalue is strictly greater in magnitude for sure.
If the starting non-zero vector had zero component in the direction of one of the two eigenvectors, then it would be the other eigenvector. Applying $A$ to it would act as multiplying by eigenvalue (which is nonzero). This means $w_1, w_2, w_3, …$ would have the same direction, so $c_1, c_2, c_3, …$ would be equal and $\{c_n\}$ would trivially converge. In our case however $c_1=1$ and $c_2\neq1$. This means $v_1$ has non-zero component in the direction of any of the two eigenvectors; in particular in the direction associated with the dominant eigenvalue.
So the conditions are met, $\{v_n\}$ converges to some eigenvector. It has some direction which corresponds to the limit of $\{c_n\}$.
Q: But wait! If $\begin{bmatrix}0\\1\end{bmatrix}$ was this eigenvector associated with the dominant eigenvalue, wouldn't the limit be $\infty$ or $-\infty$?
A: I think it would, it doesn't matter though. Calculate $A\begin{bmatrix}0\\1\end{bmatrix}$ and you will see it's not an eigenvector.
Comment: So far this seems to be the only proof that doesn't at some point have the value of the limit in it, as it never calculates what the eigenvectors actually are.
Comment: @eyeballfrog Indeed, it's the same core idea about reducing it to the case of a linear homogeneous recurrence, but (neatly) done in matrix form.
Comment: @eyeballfrog `the only proof that doesn't at some point have the value of the limit in it` My answer proves the limit exists without giving it, too. (Note that $A_2, B_2$ are never calculated there, they are just known to exist - very much like the above doesn't actually calculate the eigenvectors.)
Comment: @dxiv Fair point. In fact, unless I'm mistaken, your proof and this one are equivalent.
Answer: Not sure if the following fits the requirement to avoid finding the limit, but anyway... Consider the change of variable $$x_n=c_n-\frac{r}{c_n}$$ then $$x_{n+1}=-f(c_n)x_n$$ with $$f(c)=\frac{(r-1)c}{(c+1)(c+r)}$$ Now, for every $c>0$,
$$(c+1)(c+r)\geqslant(r+1)c$$ hence $$f(c)\leqslant s$$ with $$s=\frac{r-1}{r+1}<1$$ Thus, $$|x_n|\leqslant s^{n-1}\cdot|x_1|$$ which implies that $$x_n\to0$$ hence $$c_n\to\text{____}$$
Comment: Nice answer! Could you explain how $f$ is created?
Comment: By computing carefully $$x_{n+1}=c_{n+1}-\frac{r}{c_{n+1}}$$ in terms of $c_n$ and factoring $x_n$ in the result.
Comment: I read your proof carefully just now and it seems nice as usual. (+1)
Answer: Again, not sure if this satisfies your criteria, but if we let $f : [0,\infty) \to \mathbb{R}$ by
$$ f(z) = \frac{r+z}{1+z} $$
then $f$ is decreasing, $0\leq f \leq r$, and $c_{n+1} = f(c_n)$. So if we let
$$ \beta = \limsup_{n\to\infty} c_n, \qquad \alpha = \liminf_{n\to\infty} c_n $$
then we have $ \beta = f(\alpha)$ and $\alpha = f(\beta)$, i.e., both $\alpha$ and $\beta$ are non-negative fixed points of $g = f\circ f$. Since this function has a unique non-negative fixed point, this proves that $\alpha = \beta$.
Comment: How do we know it has a unique fixed point?
Comment: @eyeballfrog, You can solve $g(x) = x$ directly. It reduces to a quadratic equation with zeros $x = \pm \sqrt{r}$. But certainly solving this equation is related to knowing the possible limit candidate, which I am not sure if OP likes.
Comment: Yeah that was what I was thinking of as the problem. It does require evaluating the fixed point which is the limit. Not super sure why OP wants us to not do that, but still.
Answer: From the first relation $b_{n-1}=a_n-a_{n-1}$, then substituting into the second one:
$$
a_{n+1} = 2 a_n +(r-1)a_{n-1} \tag{1}
$$
From the second relation $ra_{n-1}=b_n-b_{n-1}$, then substituting into the first one and simplifying:
$$
b_{n+1} = 2b_n+(r-1)b_{n-1} \tag{2}
$$
Therefore $a_n$ and $b_n$ satisfy the same linear homogeneous recurrence with characteristic polynomial $t^2-2t-(r-1)$, only with different initial conditions.
Let $t_{1}=1 - \sqrt{r},\, t_{2}=1 + \sqrt{r}$ be the roots of the characteristic polynomial, with $|t_2| \gt |t_1|$.
Then $a_n=A_1t_1^n+A_2t_2^n$ and $b_n=B_1t_1^n+B_2t_2^n$ for some constants $A_i, B_j$ determined by the initial conditions. It can be easily verified that $A_2 \ne 0$, therefore $c_n = b_n / a_n \to B_2 / A_2$.
Answer: Note that
$$c_{n+1}=\frac{ra_n+b_n}{a_n+b_n}=1+\frac{r-1}{\frac{a_n+b_n}{a_n}} =1+\frac{r-1}{1+c_n}.$$
Wanting to show that the map $$f(x)=1+\frac{r-1}{1+x} $$
is a contraction, is a bit problematic
However, $$ f(f(x))=1+\frac{r-1}{2+\frac{r-1}{1+x}}=1+\frac{(r-1)(1+x)}{2(1+x)+r-1}=\frac{(r+1)x+2r}{2x+r+1}$$
has derivative
$$ \frac{(r+1)(2x+r+1)-2((r+1)x+2r)}{(2x+r+1)^2}=\frac{(r-1)^2}{(2x+r+1)^2}<1$$
for non-negative $x$.
Comment: Thanks for the answer. $f\circ f$ is proved to be a contraction. Does it mean we should consider the even and the odd terms of $c_n$ separately? Then, how to prove two fixed points in even and odd situations are equal?