13th Chords Movable in Minor Thirds?

Question: How are these 13th chords still "in key" when moved up in minor thirds?  If I'm thinking in key of GM, next up from G13 would be A#13; A# isn't in key of G major....(?)
Comment: I believe you forgot to attach some context to this question. Also, in the key of G major, G13 is not diatonic.
Comment: Also, G to A# is technically an augmented second; G to Bb would be a minor third :)
Comment: The short answer is: they are not in key. But the real question seems to be: why do you need to know that?
Comment: Robben Ford, in one of his Truefire courses, said that moving a G13 in minor 3rds will still remain "in the proper key".  His lesson was discussing 13ths, and he was using a G13-C13-D13 progression.  I'm an amateur and confused more than usual
Answer: There seems to be missing context to this question, but I'll fill in some assumptions.
These thirteenth chords are dominant thirteenth chords.
Also, these dominant thirteenth chords would purportedly be diatonic dominant thirteenth chords.
There is only one diatonic dominant chord in any major/minor key.
In the key of G major the diatonic dominant thirteenth chord is D13. All other dominant thirteenth chords will be chromatic in the key of G major. Those chromatic dominant thirteenth chords may have secondary dominant function, be non-functional, etc.
Answer: Robben Ford is a blues player, and it's likely when he talks about being 'in key' it's not in the more strict sense of diatonic harmony. The other answers have pointed this out clearly, so I won't repeat.
However in blues, and to a large extent jazz, you can move around pentatonic scales and get easy 'hacks' to new sounds while playing very familiar pentatonic scales. Blues is built on dominant 7th's, you would usually say that all chords in a blues progression are I, IV and V , or similar but all the chords changed to be dominant 7ths. This straight away makes it not that compatible with diatonic harmony but you can think of it as a style/tradition feature of blues.
In this context, the 13th chord, or perhaps more accurately the pentatonic scale that outlines it, CAN be moved up a minor 3rd as a technique/sound hack that more or less works with the root 7th chord.
In a G blues, if you play the Bb pentatonic over the 'tonic' G7 chord you outline the intervals #9, 4, 5, b7, 1. This is FAR from diatonic by any common analysis, but in the somewhat murky waters of the blues it still hits broadly 'correct' tones for the G7, with the added dissonance of the #9, but that's a common 'blue note' used anyway.
I can't be sure, but I think he is suggesting that playing the pentatonic scale (which roughly correlates to a 13th chord) moved up a minor 3rd still contains all useable notes against a given blues 'tonic' and may be an easy way to use a familiar fingering on guitar to easily add some interest to playing.
Going up a further b3, well it's still much the same thing but the resulting intervals get a lot more dissonant. But it's still a useable sound if you learn it, with a familiar fingering.
Using pentatonics, which fall under the fingers very nicely on guitar, we can easily find more sounds for solos. moving them around is an easy way of exploring more 'out' solos while still making very coherent musical sounds, as our ears hear the pentatonic 'coherence' and forgive the dissonance compared to a more strict definition of key. I think that's maybe what he is getting at here.
You can do the same for other chords other than 7th's. It's approaching the problem in reverse, rather than learn a new scale pattern for each sound you want to create just take a familiar one (the pentatonic scale) and work out how those much played scales with tonnes of muscle memory can be used if laid over a stated harmony with various different roots.
I have a book somewhere that analyses all pentatonic scales built off each root for most chords you are likely to experience, and what the resulting 'sound' will be. In this way they hope to unlock many different sounds and ways of coherently playing 'out' while still maintaining a familiar shape on the instrument. I use snippets of it in my playing, as I can construct a coherent pentatonic line based on the b5 of a chord (when that works) and dissolve it to another coherent pentatonic line on the b3 and finally the pentatonic scale on the 1. The result is I sound like I have played 'very out', then 'a bit out', then 'very in' when all I was really doing is playing pentatonic boxes on varying roots. Melodically coherent because the shape is very familiar, but hopefully fairly interesting as a new harmonic exploration in a solo.
I THINK thats what he is talking about here, without further context..
Comment: Well said.  Thanks for your time on that answer.  As a teacher myself, I know very well that one unclear word or two can send a student into a confusion spiral.  I may be coming  out of it now.  Being a math nerd obsessed with detail has its drawbacks
Answer: 13th chords consist of ^1 ^3 ^5 ^♭7 ^9 ^11 and ^13. Often ^11 is omitted, and so is ^5 on some instruments, notably guitar.
So, in key G, G B D F A C E are the maximum notes used.
Moving up (or down) by whatever interval, be it a semitone or m3, and taking all the notes up/down by the same interval, will give other 13th chords. Including A♯, better termed as B♭, which is actually the minor third above G - A♯ is not, as pointed out in comments.
And, if moving up by m3, why should any of the new notes belong to the old key..?
Comment: That's what was confusing me.
Comment: Regarding your last question, only two notes of a Bb13 chord are different from the notes of the G13 chord, and they are the two least important (in jazz, which is a reasonable context to assume for any question about 13th chords) notes of the Bb13 chord: the root and the 5th. Oh wait, three notes. The A has to be flat as well. Hmmm. That still leaves more than half the notes intact but it makes a lot less sense to me.
Comment: How about this. Bb13 in the context of C major (since a G13 is dominant) gives a flat 3, flat 6 and flat 7, so it's in the parallel minor of the G13 chord. So maybe in the Beethoven sense of major and minor modes are still the "same key" they are in the same key?

13th Chords Movable in Minor Thirds?


Can we add a scalar and a vector? $a+b+\mathbf x = \mathbf y $?

Question: I'm given the equation
$$
a+b+\mathbf x = \mathbf y
$$
With the vectors $\mathbf x=(x_1,x_2,x_3)$, $\mathbf y=(y_1,y_2,y_3)$ and the two scalars $a$, $b$.
Is the following correct?
As a vector equation:
\begin{align}
a+b+\mathbf x &= \mathbf y \tag 1\\
a + b + (x_1,x_2,x_3)&=(y_1,y_2,y_3) \tag 2 \\
(a+b+x_1,a+b+x_2,a+b+x_3)&=(y_1,y_2,y_3) \tag 3
\end{align}
And the vector equation as three separate scalar equations:
\begin{align}
a+b + x_1 = y_1 \tag 4\\
a+b + x_2 = y_2 \tag 5\\
a+b + x_3 = y_3 \tag 6\\
\end{align}
Also, if it is illegal, does $a+b+\mathbf x = \mathbf y$ have any meaning or is it just nonsense?
Comment: Don't do it. It is illegal.
Comment: Who gave you this equation? Adding a scalar and a vector is ill-defined, _unless_ it has previously been explicitly stated what it means. This is definitely non-standard, and without such an explicit clarification, it is meaningless.
Comment: wait..that's illegal
Comment: @Jam: I agree. There is nothing special about the vector $(1,1,1)$.
Comment: Regarding whether you can add two different objects in general, consider that addition is a *function*, i.e., a mapping from one specific domain set to a range set. In particular, for addition of $a+b$, both $a$ and $b$ need to be in the **same set** (or at least type-converted naturally like $1\mapsto 1+0i$). If they aren't in the same set, then $a+b$ is undefined.
Comment: "Can I add a vector and a scalar".  No.  You can not.
Comment: You can do an operation that takes a scalar and a vector as input and you can call it addition.  But you have to define what that operation is and if you call it "addition" it should somehow have to justify that it satisfies conditions that we expect "addition" to have.  I'd argue that as "addition" is assumed to be a binary operation that takes two objects of the same type so *no* operation between scalars and vectors would satisfy *me* as being "addition".
Comment: But why are you asking about adding *two* scalars?  If you can add one you can add two.  And if you *can't* add one you can't add two.  (And you can't add one.)
Comment: Consider vector $(a,a,a)$ and add it.
Comment: Wee-woo-wee-woo, the math police will come if you try illegal additions. But in all serious, you have implicitly turned $a$ *into* the vector $(a,a,a)$. It is perfectly legal to add them now but why is that the only choice? You could just as well have chosen $(a,0,0)$.
Comment: You have not in any sense defined what "add" means or would mean. It's not so much about illegality as it is about making sense.
Answer: Use notation that will be easily understood
$$
(a+b)\left<1,1,1\right>+\bf{x}=\bf{y}
$$
Comment: But only if forced at gunpoint.
Answer: Others have already stated that the answer is no, but I want to reinforce why this is in a formal way. The problem here is that you are viewing scalar and vector addition as the same thing, when in fact they are not. Although we use the same symbol, "$+$", for both operations, they are not the same thing because they operate on different sets. Suppose we have a vector space $V$ over a field $K$ - then scalar multiplication is an operation between two scalars that outputs another scalar. Formally speaking, $+:F\times F\to F ~ ; ~ +:(a,b)\mapsto a+b$ given some $a,b \in F.$ Vector addition takes in two vectors and outputs another vector. But we happen to use the same symbol for it because of its similarities to scalar addition. So, $+:V\times V \to V ~ ; ~ +:(\mathbf{u},\mathbf{v})\mapsto \mathbf{u}+\mathbf{v}$ given some $\mathbf{u},\mathbf{v}\in V.$ But trying to do $a+\mathbf{u}$ isn't defined, since we don't have any addition operators that can add elements of different sets like $?:F\times V \to V ~;~ ?:(a,\mathbf{u})\mapsto a+\mathbf{u}$. It's about as sensible as trying to add apples and oranges, so to speak.
Comment: We do have operators that can act on elements of different sets. For instance, we can multiply a vector by a scalar. So there are nuances here that you have ignored.
Comment: I mostly like this answer but think *"don't have **any** addition operators that can add elements of different sets"* is a big overstatement, especially since the asker has implicitly defined one as $+:F\times V\to V; (a,\mathbf{u})\mapsto (a+u_1,a+u_2,a+u_3)$. Maybe "have in general a unique and natural addition operator" would fit better.
Comment: Ok, I meant addition operators. I'll add that in.
Comment: Perhaps my wording is not the best. But I think the general idea is clear enough.


How can the placing of SYSDATE within a WHERE-clause influence the resultset?

Question: I encountered an rather strange situation on two Oracle 11 DB-Hosts, that i cannot reproduce anywhere else:
Given a rather simple table:
CREATE TABLE TESTTABLE ( XID NUMBER(10) NOT NULL,
                         XSTRING CHAR(14 BYTE) NOT NULL,
                         XDATE DATE NOT NULL )
LOGGING NOCOMPRESS NOCACHE NOPARALLEL MONITORING;

Filled with rather simple data:
INSERT INTO TESTTABLE(XID, XSTRING, XDATE)
VALUES(1119870, 'R008505       ', TO_DATE('08/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));

Then this query:
SELECT *
  FROM TESTTABLE
 WHERE xstring='R008505'
   AND (xdate >= SYSDATE OR xdate < '01.01.1900');

Returns the only row in the table (which is of course wrong), while the following query (with the SYSDATE-line swapped) returns 0 rows:
SELECT *
  FROM TESTTABLE
 WHERE xstring='R008505'
   AND (xdate < '01.01.1900' OR xdate >= SYSDATE);

Using TRUNC(SYSDATE) does not make any difference here.
How this could happen and how to fix this issue?
Comment: I was more interested in the filter predicates shown in the plan really. This seems to be a bug. Looks like possibly bug 9495697. Patching the database ought to help, if that's feasible. But you'll need to raise a service request with Oracle to get confirmation that it's the same issue.
Comment: Thought this sounded familiar... [essentially the same as this question](http://stackoverflow.com/q/21076649/266304)?
Comment: What patch level are you on? I don't see this on 22.214.171.124, or [on SQL Fiddle which is 22.214.171.124](http://sqlfiddle.com/#!4/5d646/1); both queries find zero rows. And what do the execution plans show for the two queries?
Comment: @AlexPoole Ora-Version is 184.108.40.206.0, the exection plans (full table scan) are identical.
Comment: @AlexPoole: Applying Patch 9495697 resolved the issue. Thanks a lot. In case you provide an answer i'd be glad to resolve.
Answer: This looks very similar to a previous question, which is possibly related to bug 9495697, though it wasn't confirmed in that case. I can't share the bug details from MOS, but someone else has already done so.
As in that case, the symptoms you're experiencing on the base 184.108.40.206 release don't manifest for me on 22.214.171.124, or on SQL Fiddle, which is running 184.108.40.206.
If it is that bug then applying the 184.108.40.206 patch set should cure it, or a patch is available for just this issue; not sure if you need to raise a service request and get confirmation that the symptoms do match that specific bug before applying the patch though.


Starting a service when the device's screen is unlocked in Android

Question: I would like to run my service when the screen is unlocked and stop it when the screen is locked. I looked into these answers and implemented them. However, when I lock my screen the service stops as required, but when I unlock the screen it doesn't starts again.
The code for to run this service is as follows:
public class PhonePositionService extends Service {
@Override
    public void onCreate() {
    //ADDED CODE
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver mReceiver = new BootCompletedIntentReceiver();
    registerReceiver(mReceiver, filter);
    {...}
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    int icon = R.drawable.ic_stat_bright;
    startForeground(NOTIFICATION_ID, getCompatNotification(icon));
    if (backgroundThread != null) {
      backgroundThread.start();
    }
    return START_STICKY;
  }
}

In some other file, my broadcast receiver code is as follows:
public class BootCompletedIntentReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   if(Intent.ACTION_SCREEN_ON.equals(action)) {
     // start the service
     Intent pushIntent = new Intent(context, PhonePositionService.class);
     context.startService(pushIntent);
   } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
     // stop the service
     Intent pushIntent = new Intent(context, PhonePositionService.class);
     context.stopService(pushIntent);
   }
  if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
    Intent pushIntent = new Intent(context, PhonePositionService.class);
    context.startService(pushIntent);
  }
 }
}

Then why is it so that when I unlock my phone the service does not start again?
Comment: You can add one more callback for retrieving user action by following [answer](https://stackoverflow.com/a/3463127/5308778)
Answer: First of all its not possible to detect if user has unlocked the phone until you have Admin Privilages. The issue you are facing is because you are stopping the PhonePositionService using stopService() when Screen is OFF:
public class BootCompletedIntentReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   if(Intent.ACTION_SCREEN_ON.equals(action)) {
     // start the service
     Intent pushIntent = new Intent(context, PhonePositionService.class);
     context.startService(pushIntent);
   } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
     // stop the service
     Intent pushIntent = new Intent(context, PhonePositionService.class);
     //This will stop the service
     context.stopService(pushIntent);
   }
  if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
    Intent pushIntent = new Intent(context, PhonePositionService.class);
    context.startService(pushIntent);
  }
 }
}

It would lead to some memory leak since BroadcastReceiver is not unregistered.
It is discouraged to keep service running in foreground for forever since it could lead to (fast) battery drainage.
I would recommend you to find other alternatives. But if your core functionality is impacted and you still want to proceed you can do following work around:
Make BootCompletedIntentReceiver as inner class for PhonePositionService. And instead of starting and stopping the service you perform your action directly.
public class PhonePositionService extends Service {
   @Override
   public void onCreate() {
       //ADDED CODE
       IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
       filter.addAction(Intent.ACTION_SCREEN_OFF);
       BroadcastReceiver mReceiver = new BootCompletedIntentReceiver();
       registerReceiver(mReceiver, filter);
       ...
    }
    ...
    private class BootCompletedIntentReceiver extends BroadcastReceiver {
       @Override
       public void onReceive(Context context, Intent intent) {
         String action = intent.getAction();
         if(Intent.ACTION_SCREEN_ON.equals(action)) {
          //DO action for SCREEN_ON
         } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
          //Do action for SCREEN_OFF
         }

       }
   }
}

Answer: That's because you are registering your receiver inside your service, which is a component like an activity that has a lifecycle and when it's destroyed your broadcast listener goes with it too. Actually I'm guessing you are leaking your Service here too, because you didn't unregister it which is another problem.
Since API 26 aka Oreo you cannot register you broadcast listener inside AndroidManifest.xml, If you want to target API 26+ your best bet is to register it in your Application class, but be aware when the system kills your app you will lose your broadcast listener too. However if you use a foreground service the system won't kill your service.
Edit:
Here is an example:
import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * @author : email@example.com
 * Created on: 2018-04-12
 */
public class App extends Application {

    @Override
    public void onCreate() {
    super.onCreate();
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(new BootCompletedIntentReceiver(), filter);
    }
}

Don't forget to set this class inside your manifest file.
<application
    android:name=".App"
    android:allowBackup="true"

Note you need a foreground service to be run always to not miss the events.
PS: There's another solution which is a bit hacky, target a lower API version and register your listener inside the manifest file.
Looks like targeting a lower API is out of table. It seems google knew some developers would use it to get around this.
Comment: I unregistered it onDestroy() function. In the example codes I saw they all called registerReceiver() inside their onCreate function (activity or service). Where am i suppose to register it then? Can you provide some code examples in your answer please.
Comment: @Sarahcartenz I've added a sample code to my answer.


Pedals in Chopin's Nocturne in e minor

Question: This might be a silly question so pardon me. Recently I have been practicing Chopin's Nocturne Op.72 No.1 in e minor.I have a question regarding how to use the pedals. I have been listening to Rubinstein's recording as well as Đặng Thái Sơn's. What puzzles me is that both recordings sound like they were not using the pedal at all. Each note sounds so clear and none of them sound elongated. I am trying to mimick that effect but it seems impossible to do that. I am quite sure I am following the instruction on the sheet though...Any suggestion?
Comment: You could encourage more users to help you with this if you linked to the recordings you mention and posted an excerpt from the sheet music (or at least a link to the sheet music, IMSLP perhaps?)
Comment: I believe you can press down the pedals more lightly (i.e. not fully pressing them down, halfway or so), and this will reduce the effect of the sustain and should make the notes clearer as well.
Answer: I see several parameters that could explain what you hear in these recordings and why you can't reproduce it:

You don't have the same piano. A high quality and perfectly tuned piano tends to avoid the "soup of sounds" effect due to the pedal, and allows you to have nice pianissimi with the low notes, which is important in nocturnes (this requires a bit of technique too).
The pedal technic: good pianists usually have a very subtle use of the sustaining pedal through numerous and quick full or half pedals (they press the pedal only halfway down). Rubinstein and Đặng Thái Sơn do use the pedal a lot, but in a discreet way, to keep a clear sound.

The pedal indications on your sheet may not be helpful on your piano. If you have a urtext edition, for example, you will see Chopin's indications, and he played on pianos very different from our modern ones (to have an idea, you can listen to this nocturne played on a old Pleyel piano).

Pedals in Chopin's Nocturne in e minor


Change regression coefficient to percentage change

Question: I am running basic regression in R, and the numbers I am working with are quite high. when I run the regression I receive the coefficient in numbers change.  For instance, the dependent variable is "price" and the independent is "square meters" then I get a coefficient that is 50,427.120***. I was wondering if there is a way to change it so I get results in percentage change?
This is the code i am running:
reg.model1 <- Price2 ~ Ownership - 1 + Age +
  BRA + Bedrooms + Balcony + Lotsize
reg1 <- lm(formula = reg.model1, data = Data.apartment)

stargazer(reg1, type = "text")

Comment: Do you really want percentage changes, or is the problem that the numbers are too high? If so, can you convert the square meters to square kms, would that be ok?
Comment: Hi, thanks for the comment. I might have been a little unclear about the question. My problem isn't only the coefficient for square meters, it is for all of the coefficients. square meters was just an example. All my numbers are in thousands and even millions. some study that has run the similar study as mine has received coefficient in 0.03 for instance. i will post the picture of how the regression result for their look, and one of mine.
Answer: I think what you're asking for is what is the percent change in price for a 1 unit change in an independent variable. For this, you log-transform your dependent variable (price) by changing your formula to
reg.model1 <- log(Price2) ~ Ownership - 1 + Age + BRA + Bedrooms + Balcony + Lotsize
To interpret the coefficient, exponentiate it, subtract 1, and multiply it by 100. For example, if you run the regression and the coefficient for Age comes out as 0.03, then a 1 unit increase in Age increases the price by $ (e^{0.03}-1) \times 100 = 3.04$%  on average.
This link here explains it much better. Just be careful that log-transforming doesn't actually give a worse fit than before. Perhaps try using a quadratic model like  reg.model1 <- Price2 ~ Ownership - 1 + Age + BRA + Bedrooms + Balcony + Lotsize + I(Lotsize^2) and comparing the performance of the two.
Comment: Thank you very much, this was what i was asking for. :)
Answer: A regression coefficient is the change in the outcome variable per unit change in a predictor variable.
The simplest way to reduce the magnitudes of all your regression coefficients would be to change the scale of your outcome variable. For example, if your current regression model expresses the outcome in dollars, convert  it to thousands of dollars (divides the values and thus your current regression coefficients by 1000) or even millions of dollars (divides by 1000000). Or choose any factor in between that makes sense.
Expressing results in terms of percentage/fractional changes would best be done by modeling percentage changes directly (e.g., modeling logs of prices, as illustrated in another answer). Whether that makes sense depends on the underlying subject matter. Do you think that an additional bedroom adds a certain number of dollars to the price, or a certain percentage increase to the price? That should determine how you set up your regression.


R: Why does type III ANOVA require contrasts that sum to zero?

Question: The explanation offered here is "over parameterization" of the multi-way ANOVA model, but I don't understand this statement.
In my own fiddling with 2-way, binary factor ANOVA, I can see that the full models produce the same predictions while the reduced (drop1) models do not. The key seems to be the coding of the variable interaction (and vs. xor for treatment vs. sum). When I compare the full model (~ A*B) with a model including only B and xor(A,B), I get the "correct" difference in the sums of squared residuals for A, regardless of the type of contrasts used.
Why is one representation more valid for unbalanced data? What is the statistical reasoning behind this preference (^/* over &) and how does this relate to the issue of "over-parameterization"?
Comment: Never found an answer but I also stopped looking. My own experiments suggested to me that type III is equivalent to a LRT. I suppose type III is "silly" from a hypothesis testing standpoint since you are accounting for an interaction in the standalone effect of that same predictor, but such an approach is reasonable from a model selection standpoint. A linear model already assumes that (co)-linearity is a reasonably expressive model for the data generating process, while model selection alone does not require this assumption--a bilinear model could still "win out".
Comment: Venables actually referred to the factor coding issue as an indicator of "sillyness". The same contrasts issue allegedly applies to the R function *drop1*, which does "type II" ANOVA, i.e. removes only "reasonable" terms. Recently, I have stumbled acccross teh *relaimpo* package, which implements a method of averaging over "type I" ANOVA's in all possible permutations, thereby making the result no longer order depndent and providing a more reasonable index for variable importance.
Comment: That's interesting. Haven't needed to do an ANOVA in some time though.
Comment: I wonder how they keep their algorithm from being super-exponential in the number of predictors.
Comment: "how they keep their algorithm from being super-exponential in the number of predictors" They don't. The method (aka "dominance analysis") is therefore only feasible after variable selection or when there are few predictors from the start.
Comment: As this question is over a year old, I wonder whether you have found an answer meanwhile that you would like to share. I have only found the assertion that zero-sum contrasts are required, but nowhere an explanation. I only found a remark by Venables from 2000 that the fact that the result of a type III ANOVA depends on the factor coding is a sign that performing type III ANOVA is "something silly".
Answer: The clearest explanation of this that I've found is from Bill Venables, in his recent vignette, "Coding Matrices, Contrast Matrices and Linear Models".
Basically it's so that the underlying hypothesis behind testing for a main effect, corresponds with what people might intuitively expect a main effect to be. As far as I can tell there is no problem at all if you understand exactly what you're testing for in terms of a contrast of cell means. One can choose various model intercepts using relevel() and contr.treatment: it should be expected that p-values for main effects terms will change with the changing intercepts.
Answer: The full model is overdetermined and needs to drop one of the factors (which get turned into n-1 dummy variables instead of n dummy variables, see: The dummy variable trap). Which factor is dropped is arbitrary and this makes the location of the intercept arbitrary. See

Order of variables in R's lm
Both variables of my GLMM output are significant. Don't know how to interpret it?

The use of sum contrasts instead of treatment contrasts places the intercept in the middle, instead at one of the factors.
It changes a model like:
$$y_i = \beta_1 + \beta_2 x_i + \beta_3 z_i + \beta_4 x_1z_i + \epsilon_i$$
which is effectively
$$y_i = \begin{cases}
\beta_1 & \quad \text{if $x_i = 0$ and $z_i = 0$}\\
\beta_1+\beta_2 & \quad \text{if $x_i = 1$ and $z_i = 0$}\\
\beta_1+\beta_3 & \quad \text{if $x_i = 0$ and $z_i = 1$}\\
\beta_1+\beta_2+\beta_3+\beta_4 & \quad \text{if $x_i = 1$ and $z_i = 1$}\\
\end{cases}
$$
into
$$y_i = \beta_1 + \beta_2 (2x_i-1) + \beta_3 (2z_i-1) + \beta_4 (2x_i-1)(2z_i-1) + \epsilon_i$$
which is effectively
$$y_i = \begin{cases}
\beta_1-\beta_2-\beta_3+\beta_4& \quad \text{if $x_i = 0$ and $z_i = 0$}\\
\beta_1+\beta_2-\beta_3-\beta_4 & \quad \text{if $x_i = 1$ and $z_i = 0$}\\
\beta_1-\beta_2+\beta_3-\beta_4 & \quad \text{if $x_i = 0$ and $z_i = 1$}\\
\beta_1+\beta_2+\beta_3+\beta_4 & \quad \text{if $x_i = 1$ and $z_i = 1$}\\
\end{cases}
$$
The estimates for the full model will be the same, there is no difference there (only slightly different coëfficiënts, but effectively the same estimates).
The effect/difference is that the model after dropping a main effect will be falling back to a different model, because the intercept is placed differently.
Whether or not the use of these type of contrasts make sense is not a strict rule. The use of type III contrasts with an interaction term are not very easy to interpret (and often it makes no sense with whatever contrasts you do it). It may depend on the case where one whishes to place the intercept.


Prove that LM is parallel to AB

Question: the question is the following:

The problem is equivalent to show that $M$ is a midpoint of arc $\widehat{AB}$. I made a diagram on geogebra (points $C$ and $P$ got confused, sorry):

It is not hard to prove $AMYX$ is cyclic. I was hoping to find some congruent triangles that would help, but it didn't quite work: $AM=MB$ and $MY=MT$ so I put my hope of finding congruence there. I didn't want to work with the second meeting of $PB$ and the left circle, because it seems unnecessary. Got a lot of stuff going on here: $C$ is the circumcenter of $\triangle MTY$, $AT \perp TX$
EDIT: we got a Protassov configuration! I think the incenter of $\triangle ABC$ (in the top image, $\triangle ABP$ in the bottom) has a nice alignment with $T$ and a midpoint of arc $AB$
Answer: Mirror the blue circle in the line $LM$. Then the line $BC$ is simply another common tangent line of two circles. In other words, we are really trying to show that the dashed line defined by the red lines in the picture below is parallel to the symmetry axis.
The key point is to show that two of the common tangent lines (the green and one of the reds in the picture below) intersect on the circle.

The first step is to apply circle inversion with respect to the dashed circle in the picture below. I have indicated the corresponding old and new objects with like colours.

We are left to show that the green circle, defined to touch one of the lines and one of the blue circles while going through the point of symmetry, touches the line in precisely the intersection point of the red circle with the line.
I have included a clearer picture below and gave some points names.
Starting with the rectangle, construct the red circle and hence the point $X$. Let $P$ be the projection of $B$ on $XC$ and define the green circle to be the circumcircle of $X$, $P$ and $M$. By Thales, to show that this satisfies all we want of the green circle, it suffices to show equality between the blue angles.

The proof is surprisingly short. Since $YD$ touches the red circle, we have $|YD|^2 = |YM||YX|$. By symmetry $|YD| = |XB|$, so we even have that $|XB|^2 = |XM||XY|$.
From the similarity between triangles $XPB$ and $XBC$, we get that $|XB|^2 = |XP||XC|$. Combining this with the previous, gives us that $|XP||XC| = |XM||XY|$. In other words, we have shown that $YMPC$ are all on a circle. We immediately find $\angle BXC = \angle YCP = \angle PMX$, as was to be shown.
Comment: you did indeed, thanks!
Comment: A proof of that meeting is needed
Comment: I have added a proof sketch. I don't feel like spelling out the dull computations. If you happen to see a nice way to bring the win home, I would be curious to learn about it
Comment: @hellofriends I have now given a completely synthetic proof. No calculations needed anymore. Super cool problem. I'm happy to have found a satisfactory proof in the end
Answer: Given two circles with centers $K$, $L$, externally tangent at $E$, with common tangent $AH$ and tangent $LM$, join $MA$, make chord $MB=MA$, and draw $BD$ tangent to the other circle.
Since triangle $ABM$ is isosceles, then $\angle BAM=\angle MBA$. And since $\angle LMA$ between chord and tangent is equal to $\angle MBA$ in the alternate segment, then$$\angle LMA=\angle BAM$$Therefore$$LM\parallel AB$$
Note: On this interpretation of the question and its conditions, tangents $AH$ and $BD$ are extraneous.  But even if the tangents are included, and $A$ is therefore not random, $B$ cannot be supposed random, but must be chosen such that triangle $ABM$ is isosceles. In other words, $M$ is the midpoint of arc $AMB$. Otherwise $LM$, which is given in position for the given circles, will not be parallel to $AB$. A fuller statement of the conditions in this question would be helpful.

Addendum:
In light of the clarifying comments, that the above solution misinterprets the question, let me offer at least a proof for the special case of equal circles.
In the figure below, with $F$ as the intersection of the tangent at $E$ with tangent $LM$, it is clear by symmetry that tangent $CBFD$ passes through center $K$.
Since hypotenuse $KL=2KM$, then $\angle MKL=60^o$.
And since $\angle FKL=\angle KLF=30^o$, therefore exterior $\angle KFM=60^o$.
Further, since $\angle AKB= 90^o-30^o=60^o$, then $\triangle AKB$ is equilateral, $$\angle ABK=60^o=\angle KFM$$and$$LM\parallel AB$$And it is clear in this case that $M$ is the midpoint of arc $AMB$.
Comment: I think you misinterpreted the question. As I understood it, one intersects $LM$ with the common tangent line at $E$ and from this point, one draws the line tangent to the smaller circle. This line intersects the larger circle at $B$. Proving $|MA| = |MB|$ is equivalent to the problem
Comment: @Edward Porcella I agree with Mike Dass.
Comment: OK, thanks for the clarification

Prove that LM is parallel to AB


How do placeholders work in Flyway?

Question: I'm evaluating Flyway for use in my project. Our current SQL scripts contain placeholders for things like URLs which will have a different domain names depending on the environment (dev, qa, prod).
Specifically, we might have INSERT statements like
INSERT INTO FEED VALUES ('app.${env.token}.company.org/feed1', 'My Feed');

${env.token} needs to be replaced with 'dev', 'qa', or 'prod'.
We have about 50 different properties that could potentially need replacement in SQL scripts. The properties all reside in one or two properties files.
Is there a way to run the Flyway Ant migration task so that it pulls the replacement tokens and values from a properties file? Something along the lines of the Ant filter task?
Answer: If the token was subdomain:
INSERT INTO FEED VALUES ('app.${subdomain}.company.org/feed1', 'My Feed');

The values in flyway.conf:
flyway.url=jdbc:mydb://db
flyway.user=root
flyway.schemas=schema1
flyway.placeholders.subdomain=example

Or command line:
flyway -url=jdbc:mydb://db -user=root -schemas=schema1 -placeholders.subdomain=example migrate

Would run the script as:
INSERT INTO FEED VALUES ('app.example.company.org/feed1', 'My Feed');

Comment: In the event that the person finding this page is satisfied with environment variable replacement I'll round out your answer with this clip from the doc page:

"to replace a placeholder named key1 with the value value1, you can set the environment variable FLYWAY_PLACEHOLDERS_KEY1 to value1. Flyway will then convert the KEY1 part to lowercase (key1) and look for it, in conjunction with the placeholder prefix and suffix, in your SQL migrations. Flyway will then replace any occurrences it finds with value1."
Answer: Currently when supplying placeholders as properties, the property name should be prefixed with flyway.placeholders.
For example the ${env.token} placeholder can be specified directly as this Ant property: flyway.placeholders.env.token
There is currently no support for passing a property file directly, without using prefixes for the property names. Feel free to raise an issue in the Issue Tracker. :-)
Comment: Axel, can you add this explanation to documentation at here: https://flywaydb.org/documentation/migration/sql   I couldn't understand the correct use of placeholders before reading from here.
Answer: From my experience, it's much easier to use environment variables
instead of CLI or config file (especialy when using docker and k8s).
You can use environment variables in the following format -
export FLYWAY_PLACEHOLDERS_USER=${USER}

Then in you sql statement, use this variable like this -
INSERT INTO tmptable (user)
VALUES ('${user}')

read more about environment variables here
Answer: Maven version:
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-maven-plugin</artifactId>
            <configuration>
                <url>jdbc:mysql://localhost/cloud</url>
                <user>root</user>
                <password>root</password>
                <placeholderReplacement>false</placeholderReplacement>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>${mysql.version}</version>
                    <scope>runtime</scope>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

How do placeholders work in Flyway?


JQuery Ajax Post submission - with conditional validation before ajax post or pop alert

Question: Attempting what would appear to be a simple pre ajax-post validation against a short form.  This is working correctly and posting data perfectly until adding an attempt at a conditional value check against it.
JQuery is adding the values to the form on the fly until the user changes the values in the form fields and am checking against the default values since they will be added if the user leaves blank or default.
Thoughts were to (a)do a simple conditional for #tip and #num and THEN (b)ajax post if the condition was met.  Was trying to keep this simple and not use additional plugins or code.
Am I missing the obvious, or going about the this wrong way?
    function submitForm() {

    if( ($('#tip').val() != 'Enter Tip')
            AND ($('#num').val() != 'ID number') ) {

    $.ajax({type:'POST', url:'populatedb.php', data:$('#TipForm').serialize(), success: function(response) {
    $('.formresult').html(response);
    $("#TipForm").hide();
    }});
    return false;

       } else {
            alert("Please fill all form fields");
       }

    } // end submitForm()

Answer: I think you need this line
if(($('#tip').val() != 'Enter Tip' || $('#tip').val() !='') && ($('#num').val() != 'ID number' || $('#num').val() !=''))

instead of the following
if( ($('#tip').val() != 'Enter Tip') AND ($('#num').val() != 'ID number') )

Comment: Thank you Herra, it was the AND OR that tripped it up. Your response helped highlight that.


Retornando NullPointer no controller

Question: Eu tenho um método no controller que tem como função fazer um consulta no meu banco e após me retornar apenas um campo dessa busca, porém estou tomando nullpointer no primeiro for que estou usando. Gostaria de ajuda nisso.
As constantes são essas:
private List<String> listaNomeProjeto;
private List<String> listaNomePerfil;
private List<String> listaNomeJornada;

@RequestMapping(value = REDIRECT_PAGE_CADASTRO, method = RequestMethod.GET)
    public ModelAndView viewCadastro(Model model) {

        List<Projeto> listaCompletaProjeto = projetoService.findAll();

        for (Projeto listaProjetos : listaCompletaProjeto) {
            listaNomeProjeto.add(listaProjetos.getProjeto());
        }

        List<Perfil> listaCompletaPerfil = perfilService.findAll();

        for (Perfil listaPerfis : listaCompletaPerfil) {
            listaNomePerfil.add(listaPerfis.getPerfil().toString());
        }

        List<Jornada> listaCompletaJornada = jornadaService.findAll();

        for (Jornada listaJornadas : listaCompletaJornada) {
            listaNomeJornada.add(listaJornadas.getDsJornada().toString());
        }

        usuarioBean = new UsuarioBean(listaNomeProjeto, listaNomePerfil, listaNomeJornada);

        model.addAttribute("usuarioBean", usuarioBean);

        return new ModelAndView(REQUEST_MAPPING_PAGE_CADASTRO);
    }

Desde já agradeço!
Comment: Copie e cole o `stacktrace` inteiro do erro na sua pergunta, senão fica difícil saber qual o problema
Answer: Você não está inicializando suas listas, então no momento que o método add é chamado para a variável listaNomeProjeto, uma exceção é disparada já que ela é nula. Um modo de corrigir desconsiderando a sua regra de negócio (que não está clara) é o substituir as declarações para o seguinte:
private List<String> listaNomeProjeto = new ArrayList<>();
private List<String> listaNomePerfil = new ArrayList<>();
private List<String> listaNomeJornada = new ArrayList<>();

Talvez você deva considerar a criação das variáveis dentro do seu método:
@RequestMapping(value = REDIRECT_PAGE_CADASTRO, method = RequestMethod.GET)
public ModelAndView viewCadastro(Model model) {
  List<Projeto> listaCompletaProjeto = projetoService.findAll();
  List<String> listaNomeProjeto = new ArrayList<>();
  List<String> listaNomePerfil = new ArrayList<>();
  List<String> listaNomeJornada = new ArrayList<>();
  ...
}

Retornando NullPointer no controller


Concatenating image path from Database in asp.net core

Question: I am trying to concatenate a base path of image folder with a complete path coming from a DB in a .cshtml file to show image on the page but nothing is working out in my end. The best solution that I have tried is,
 @foreach (var item in Model)
                {
                    string img = @"~/pics"+Html.DisplayFor(modelItem=>item.ImagePath);

                            @*My Dynamic Article*@

@Html.DisplayFor(modelItem => item.Name)

Hello

}

But this too is outputting something strange, I see this path in the output on web browser,

Tell me some method that works fine with asp.net core MVC latest release. Thanks
Answer: To solve this problem, you can put the content of the img variable directly into the src attribute, and add the @ symbol directly in front of Html.DisplayFor(modelItem=>item.ImagePath).
Here is the work code:
                @foreach (var item in Model)
                {

                            @*My Dynamic Article*@

@Html.DisplayFor(modelItem => item.Name)

                                item.ImagePath)" width="95%" alt="Laser" />

Hello

}

Or you can directly get ImagePath by following:

Here is the test result:


Sampling from a database

Question: I am conducting a research study about breastfeedding. I receive a whole database of subjects which are suitable to my research. I have had to call each individual to ask for their approval to participate in the study since it also requieres the participation of their bosses and one co-worker. This means that I can only conduct research on individuals which boss and co-worker are willing to participate. I have receive several notifications of individuals who can not participate due to several reasons. From this standpoint my list of potential participants have been reduced. Is this type of sampling valid from a statistical perspective? My sample will be composed of approximately 30 individuals.
Comment: The good news: the answer will depend on the type of analysis you wish to do with these 30 individuals. The bad news: there are not too many questions you can answer with such data.
Comment: I was thinking about a regression analysis. Which other analysis may I conduct with such a small sample?
Answer: If you are restricted to draw a sample the the sampling is less probabilistic and henceforth be less reliable. It is also affected for statistical analysis also. I am fully agreed with JohnRos comment. I think you can make inference from the sample data but you may not great scope to analysis the data. That's all from me.

Sampling from a database


Como enviar de mais de uma id AJAX - PHP?

Question: No caso abaixo eu estou enviando os dados da ID: id_motor...
E seu euquiser enviar outra ID junto, tipo a id_motor e a id_modelo, como eu faria?

<code>  $(function(){
   $('#id_motor').change(function(){
    if( $(this).val() ) {
     $('#id_ano').hide();
     $('.carregando').show();
     $.getJSON('sub_ano.php?search=',{id_motor: $(this).val(), ajax: 'true'}, function(j){
      var options = '<option value="">Escolha o Ano</option>';
      for (var i = 0; i < j.length; i++) {
       options += '<option value="' + j[i].id + '">' + j[i].ano + '</option>';
      }
      $('#id_ano').html(options).show();
      $('.carregando').hide();
     });
    } else {
     $('#id_ano').html('<option value="">– Escolha o Ano –</option>');
    }
   });
  }); </code>

Do outro lado estou recuperando como:
$id_motor = $_REQUEST['id_motor'];
e teria que recuperar mais um, exemplo:
$id_motor = $_REQUEST['id_motor'];
$id_modelo = $_REQUEST['id_modelo'];
Answer: Utilizo o array "data" para passar os parâmetros utilizando jquery ajax:
<code>$('#id_motor').change(function(){

    $.ajax({
        url: 'sub_ano.php',
        type: 'GET',
        dataType: 'json', //espera o retorno em json
        data: {
            //aqui você passa quantos parametros precisar
            id_motor: $("#meuMotor").val(), //id do campo id_motor
            id_outro : $("#outro_id").val(), // id do campo outro_id
        },
        success: function(j){
            var options = '<option value="">Escolha o Ano</option>';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].id + '">' + j[i].ano + '</option>';
            }
            $('#id_ano').html(options).show();
            $('.carregando').hide();
        },
        error: function(){
            Alert("Erro ao processar requisição"); //deu algum erro na requisição
        }

    }); //fim do ajax

});
</code>


How to convert VP8 interframe into image with Pion/Webrtc?

Question: I have tried snapshot example to convert VP8 video stream to jpeg in Pion/Webrtc examples.
It works well, but interframes are not included. An error message displayed when I was fixing it.
vp8: Golden / AltRef frames are not implemented.
This error comes from golang's vp8 package.
The modified code is shown below:
if !videoKeyframe {
    decoder.Init(bytes.NewReader(sample.Data), len(sample.Data))

    _, err := decoder.DecodeFrameHeader()
    if err != nil {
        fmt.Printf("Header Error: %s\n", err)
        continue
    }

    _, err2 := decoder.DecodeFrame()
    if err2 != nil {
        fmt.Printf("DecodeFrame Error: %s\n", err2)
        continue
    }
}

I also tried to modify gstreamer-receive example. But it's hard for me to do in C.
Is there anyway to convert interframe to jpeg easily ?
Answer: Finally, I solved with libvpx-go
I modified code as shown below.
package main

import (
    "bytes"
    "fmt"
    "image/jpeg"

    //  "log"
    "os"

    "github.com/pion/rtp"
    "github.com/pion/rtp/codecs"
    "github.com/pion/webrtc/v3/pkg/media/samplebuilder"
    "github.com/xlab/libvpx-go/vpx"
)

// type Frame struct {
//  *image.RGBA
//  Timecode   time.Duration
//  IsKeyframe bool
// }

type VDecoder struct {
    enabled bool

    src   <-chan *rtp.Packet
    ctx   *vpx.CodecCtx
    iface *vpx.CodecIface
}

type VCodec string

const (
    CodecVP8  VCodec = "V_VP8"
    CodecVP9  VCodec = "V_VP9"
    CodecVP10 VCodec = "V_VP10"
)

func NewVDecoder(codec VCodec, src <-chan *rtp.Packet) *VDecoder {
    dec := &VDecoder{
        src: src,
        ctx: vpx.NewCodecCtx(),
    }
    switch codec {
    case CodecVP8:
        dec.iface = vpx.DecoderIfaceVP8()
    case CodecVP9:
        dec.iface = vpx.DecoderIfaceVP9()
    default: // others are currently disabled
        log.Println("[WARN] unsupported VPX codec:", codec)
        return dec
    }
    err := vpx.Error(vpx.CodecDecInitVer(dec.ctx, dec.iface, nil, 0, vpx.DecoderABIVersion))
    if err != nil {
        log.Println("[WARN]", err)
        return dec
    }
    dec.enabled = true
    return dec
}

func (v *VDecoder) Save(savePath string) { //, out chan<- Frame
    //  defer close(out)
    i := 0

    sampleBuilder := samplebuilder.New(20000, &codecs.VP8Packet{}, 90000)

    for pkt := range v.src {

        sampleBuilder.Push(pkt)

        // Use SampleBuilder to generate full picture from many RTP Packets
        sample := sampleBuilder.Pop()
        if sample == nil {
            continue
        }

        if !v.enabled {
            continue
        }

        dataSize := uint32(len(sample.Data))

        err := vpx.Error(vpx.CodecDecode(v.ctx, string(sample.Data), dataSize, nil, 0))
        if err != nil {
            log.Println("[WARN]", err)
            continue
        }

        var iter vpx.CodecIter
        img := vpx.CodecGetFrame(v.ctx, &iter)
        if img != nil {
            img.Deref()

            // out <- Frame{
            //  RGBA:     img.ImageRGBA(),
            //  Timecode: time.Duration(pkt.Timestamp),
            // }

            i++

            buffer := new(bytes.Buffer)
            if err = jpeg.Encode(buffer, img.ImageYCbCr(), nil); err != nil {
                //  panic(err)
                fmt.Printf("jpeg Encode Error: %s\r\n", err)
            }

            fo, err := os.Create(fmt.Sprintf("%s%d%s", savePath, i, ".jpg"))

            if err != nil {
                fmt.Printf("image create Error: %s\r\n", err)
                //panic(err)
            }
            // close fo on exit and check for its returned error
            defer func() {
                if err := fo.Close(); err != nil {
                    panic(err)
                }
            }()

            if _, err := fo.Write(buffer.Bytes()); err != nil {
                fmt.Printf("image write Error: %s\r\n", err)
                //panic(err)
            }

            fo.Close()
        }
    }
}

Just add 2 lines of code to save sequential images
vd := NewVDecoder(CodecVP8, rtpChan)

go vd.Save("/ramdisk/image_seq/xxx")

Enjoy!
P.S. don't forget to install libvpx-go 's dependencies before running go get and make sure libvpx 's version is 1.8
Comment: Thank you very much for this code! It helps me a lot. Do you have the encoder part? :)
Answer: If you need to convert interframe to jpeg the only way would be to decode every frame from your stream. I don't think there is any other way as interframes depend on previous frames.
Answer: Sync Solution
This is an alternative version of the same solution of CK So
It is based on libvpx-go but dose not use channels.
package main

import (
    "bytes"
    "fmt"
    "image/jpeg"
    "log"

    //  "log"
    "os"

    "github.com/xlab/libvpx-go/vpx"
)

// type Frame struct {
//  *image.RGBA
//  Timecode   time.Duration
//  IsKeyframe bool
// }

type VDecoderSync struct {
    enabled bool

    //src   <-chan []byte this blocked the thread even if fed.
    ctx   *vpx.CodecCtx
    iface *vpx.CodecIface
    i     int
}

type VCodecSync string

const (
    CodecVP8Sync  VCodecSync = "V_VP8"
    CodecVP9Sync  VCodecSync = "V_VP9"
    CodecVP10Sync VCodecSync = "V_VP10"
)

func NewVDecoderSync(codec VCodecSync) *VDecoderSync {
    dec := &VDecoderSync{

        ctx: vpx.NewCodecCtx(),
    }
    switch codec {
    case CodecVP8Sync:
        dec.iface = vpx.DecoderIfaceVP8()
    case CodecVP9Sync:
        dec.iface = vpx.DecoderIfaceVP9()
    default: // others are currently disabled
        log.Println("[WARN] unsupported VPX codec:", codec)
        return dec
    }
    err := vpx.Error(vpx.CodecDecInitVer(dec.ctx, dec.iface, nil, 0, vpx.DecoderABIVersion))
    if err != nil {
        log.Println("[WARN]", err)
        return dec
    }
    dec.enabled = true
    return dec
}

func (v *VDecoderSync) EncodeToJson(savePath string, pkt []byte, print_to_file bool) []byte {

    sample := pkt

    dataSize := uint32(len(sample))

    err := vpx.Error(vpx.CodecDecode(v.ctx, string(sample), dataSize, nil, 0))
    if err != nil {
        log.Println("[WARN]", err)
        return nil
    }

    var iter vpx.CodecIter
    img := vpx.CodecGetFrame(v.ctx, &iter)
    if img != nil {
        img.Deref()

        // out <- Frame{
        //  RGBA:     img.ImageRGBA(),
        //  Timecode: time.Duration(pkt.Timestamp),
        // }

        buffer := new(bytes.Buffer)
        if err = jpeg.Encode(buffer, img.ImageYCbCr(), nil); err != nil {
            //  panic(err)
            fmt.Printf("jpeg Encode Error: %s\r\n", err)
        }
        bytes_to_send := buffer.Bytes()

        if print_to_file {

            v.i++
            v.i = v.i % 30

            fo, err := os.Create(fmt.Sprintf("%s%d%s", savePath, v.i, ".jpg"))

            if err != nil {
                fmt.Printf("image create Error: %s\r\n", err)
                //panic(err)
            }
            // close fo on exit and check for its returned error
            defer func() {
                if err := fo.Close(); err != nil {
                    panic(err)
                }
            }()

            if _, err := fo.Write(bytes_to_send); err != nil {
                fmt.Printf("image write Error: %s\r\n", err)
                //panic(err)
            }
        }

        return bytes_to_send

    }
    return nil

}


Problema para imprimir centralizado no C

Question: Estou com o seguinte problema, no meu código eu quero que o programa imprima de forma centralizada o número 1 depois da "palavra", e para centralizar estou utilizando o parâmetro "%-20s \t" para tentar centralizar o número após a palavra, porém em palavras com mais de um acento, a mesma não segue a tabulação.
Segue o código fonte:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<locale.h>

int main(){
    setlocale(LC_ALL, "Portuguese");
    int i = 0;
    char nomes[3][15];
    strcpy(nomes[0], "palavra");
    strcpy(nomes[1], "palavrãozzz");
    strcpy(nomes[2], "palavrãozão");

    for(i = 0; i < 3 ; i++){
        printf("%-20s \t1\n", nomes[i]);
    }
}

A saída:

[Running] cd "c:\Users\Pierre\Desktop\1\" && gcc *.c -o main && "c:\Users\Pierre\Desktop\1\"main
palavra               1
palavrãozzz           1
palavrãozão           1

[Done] exited with code=0 in 0.242 seconds

Gostaria que a saída fosse:
palavra                 1
palavrãozzz             1
palavrãozão             1

Answer: A formatação do printf() foi feito para trabalhar com textos muitos simples, em ASCII. Na verdade todas funções básicas de C são para tarefas bem padronizadas, quando você sai um pouco da necessidade mínima programadores C usam bibliotecas de terceiros ou próprias para fazer a maioria das tarefas. Um exemplo pode ser visto no SOen.
A formatação do printf() não funciona bem com acentos.
Então a solução é criar algo diferente para lidar bem com isso, ou fazer um algoritmo que lide com textos acentuados, ou pelo menos fazer a impressão manualmente caractere por caractere e não usar a formatação do printf(). Ou ainda, o que eu acho que para um exercício de algoritmo que é o que 99% das pessoas fazem em C e não importa os detalhes, não usar acentuação:
#include <stdio.h>
#include <string.h>

int main() {
    char nomes[3][15];
    strcpy(nomes[0], "palavra");
    strcpy(nomes[1], "palavraozzz");
    strcpy(nomes[2], "palavraozao");
    for (int i = 0; i < 3 ; i++) printf("%-20s\t1\n", nomes[i]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Como corrigir texto sobreposto no cabeçalho com biblioteca MPDF

Question: Estou tendo um problema com o cabeçalho em relação ao texto de corpo ao gerar um PDF.
O cabeçalho está sendo sobreescrito pelo texto do corpo, como resolver isso?
Estou usando o método SetHTMLHeader para o cabeçalho e o métodoWriteHTML para o texto de corpo. Existe alguma forma de se aumentar o tamanho reservado para o cabeçalho com essa biblioteca, ou alguma outra coisa que resolva?
Meu código atual:
<?php
session_start();
include('mpdf60/mpdf.php');
$paragrafo = "";
for($x=1;$x<=12;$x++){
    $paragrafo.=$_SESSION['c'.$x]."
";
}
$cabecalho = $_POST['cabecalho'];

$mpdf=new mPDF();
$mpdf->SetDisplayMode('fullpage');

$mpdf->SetHTMLHeader($cabecalho);
$mpdf->WriteHTML($paragrafo);
$mpdf->Output();
exit;?>

Como eu queria que ficasse:

Como está ficando:
Comment: Pode colocar o código aqui?
Comment: @GiancarloAbelGiulian coloquei aqui
Comment: O código que monta o texto é só isso mesmo?
Comment: @DiegoFelipe  coloquei o começo do código agora
Comment: esse é o código completo do arquivo que monta o pdf @DiegoFelipe
Comment: Bom, você não está definindo a posição de impressão na página, apenas está mandando "imprimir" um monte de coisa. Não é a biblioteca que vai adivinhar onde você quer os textos, certo?
Comment: mas onde eu faço isso? nao entendi a documentação dessa biblioteca @Bacco
Comment: @AlexandreMartinsMontebelo não tem nenhum exemplo de como posicionar a informação na documentação? Talvez numa destas respostas tenha algo que possa ser aproveitado (não cheguei a ler, é apenas uma sugestão de pesquisa) http://pt.stackoverflow.com/search?q=mpdf+is%3Aquestion - De qualquer forma, vamos aguardar se alguém posta alguma resposta que ajude. Enquanto isso, se puder, dê uma espiadinha nos exemplos.
Comment: Olhando rapidamente, me parece que ao criar o PDF, você pode especificar as margens da página, mas não sei se isso ajudaria. Em inglês tem umas soluções com CSS, talvez sirva de ponto de partida. http://stackoverflow.com/questions/16538109/change-top-margin-of-second-page-using-mpdf Outra coisa que talvez solucionasse, seria acrescentar o material do header no corpo da página. Talvez não seja o caminho mais elegante.
Comment: eu tentei essa sua segunda opção primeiramente, de colocar tudo no corpo, só que o texto do cabeçalho ficava muito abaixo do esperado, ficava parecendo parte do corpo mesmo, nem com css resolvia, vou ver se da certo essa primeira solução @Bacco
Comment: Consegui! mudei os parâmetros ao instanciar a classe mpdf
Comment: @AlexandreMartinsMontebelo eu dei uma formatada na sua pergunta, mas já que resolveu, você pode postar a solução como resposta para sua própria pergunta, no campo abaixo.
Answer: Consegui! Obrigado @Bacco pelo link!
alterei a linha a seguir:
$mpdf=new mPDF();

por :
$mpdf = new mPDF(
             '',    // mode - default ''
             '',    // format - A4, for example, default ''
             0,     // font size - default 0
             '',    // default font family
             15,    // margin_left
             15,    // margin right
             58,     // margin top    -- aumentei aqui para que não ficasse em cima do header
             0,    // margin bottom
             6,     // margin header
             0,     // margin footer
             'L');  // L - landscape, P - portrait

Comment: Perfeito! Usei isso também e funcionou...
Comment: Muito bom! Usei aqui e também deu certo. Obrigado!
Comment: Funcionou Perfeitamente!


Studio monitors: Should we break them in and why?

Question: Having just acquired a spankin' new pair of monitors for my home studio, I'm currently in the process of "breaking them in".
Being an inquisitive mind, I started wondering: what is the purpose of this?
For those who aren't familiar with the term: "breaking-in" speakers is simplicity itself and consists in playing music over them for some time - typically 10-20 hours. This period of adjustment in order for the speakers to settle into their optimal working state, that will affect their sound, is recommended by manufacturers and reviewers alike.
Examples:

NOTE - The studio monitors will take break-in time to achieve optimum sonic performance. Under moderate use, play a favorite album between 15 to 25 hours.

Source: KRK Systems ROKIT G3 Series Manual

After setting the filters for my room and an extensive break-in period, they became both punchy and percussive in the low end, as well as fast and "airy" in the upper end of the frequency response.

Source: Neumann KH 120A Studio Monitors Review @ Mix Online
Is this really the case? And, if so: how does it work?
An ideal answer will address the physics involved: does the break-in period affect electronics, the speaker cones, the cabinet, all of the above; as well as the expected changes in sonic qualities following the break-in period. What differences can we expect to hear?
If any studies have been performed, references would be appreciated.
A negative answer ("break-in is a myth", as some claim) would ideally reference studies that demonstrate no measurable difference between "unbroken" and "broken-in" speakers.
Comment: This makes no sense to me (speaking an a mechanical engineer). If the process has any effect you need to specify what type of music, and at what level (10 hours of thrash metal with the volume turned up to 11 is probably going to have a different effect from 10 hours of music for solo flute!) If there are any significant "burn-in" or "infant death" effects, those ought to be dealt with by the manufacturer, not left for the customer to discover.  Maybe the real effect is to "burn in" your own ears to the sound of the new speaker system before doing anything critical with it.
Comment: "Most manufacturers and reviewers stress that this is necessary"... do they? This could use a couple of clear references... As alephzero says, this whole idea sounds unlikely, whereas it's definitely a good idea to accustom _your ears_ to the monitors. Else there's the risk that you'll "work against the speakers", correcting for something you attribute to the signal but is really specific to the speakers.
Comment: "I did actually find a manufacturer site that weakly suggested you may benefit from break-in of their speakers." But since when has audiophile equipment been marketed on the basis of science? At least this question isn't about cables that cost £2,500 for 10 feet of wire! (ref: http://www.audioaffair.co.uk/kubala-sosna-expression-speaker-cables?gclid=CO31l9b4ntQCFecV0wodkMwFsg)
Comment: one interpretation is that instead of the speakers needing time to "break in", the customer needs time to get used to the sound of their new system. I'd say about 10-20 hours will do the trick. So the "break in" story really just serves to get customers to suspend judgment. Then again, this is more of an explanation of WHY the myth is beneficial for speaker manufacturers than a proof that it is in fact a myth. :)
Comment: @alephzero The ears getting used to the sound of the speaker is something I have considered - and am treating as a bonus. However, I am interested in something more substantial than a hunch or common sense, as you can no doubt appreciate.
Comment: I answered this question instead of voting to close as opinion-based only after lengthy consideration and research. The first web sites I found all confirmed that there is almost always heated argument over whether break-in is real or not. If such an argument begins here I will feel compelled to vote to close as opinion based, as arguments over things that can't be clearly answered with documentation are definitely not part of what Stack Exchange is about. @leftaroundabout I did actually find a manufacturer site that weakly suggested you may benefit from break-in of their speakers.
Comment: @leftaroundabout Added example recommendations of break-in from manufacturer and review. I changed the wording of this section to remove the, perhaps unwarranted, quantifier.
Comment: @ToddWilcox The fact that the matter is contentious is exactly *why* I posted this question. Your own, very good, answer shows that it is answerable based on objective research and this is exactly the kind of service that - to my mind - Stack Exchange should offer its users. Problems with potential unsourced and argumentative answers are problems *with answers*, as opposed to the question, and what downvotes are for.
Comment: The problem is there is documentation (for example, the quotes you have added) on both sides of the argument. It's unlikely that my answer will somehow put the controversy to rest. Despite my answer showing measurements that seem to show there is no benefit to "breaking in", I myself am convinced I can hear differences between certain things that scientific measurements would seem to show are identical. It is a question ripe for argument.
Comment: @ToddWilcox The subjective perception of differences is readily explainable by what alephzero mentioned: your ears getting used to the sound. The mechanisms involved in how our brains make... ahem... sense of sense perceptions could shed light on why this happens, but I fear the matter is both inadequately researched ATM and outside the scope of the question. The question as stands is clear-cut: is there an identified, objective mechanism at work or not. Your answer suggests: no. Beyond that, we should remember that the placebo effect is a thing.
Comment: Never heard of this! Would it apply to *all* speakers, or is it aimed specifically at studio monitors?  The suggestion is to put the *speakers* through a number of hours of work, any mention of the user's *ears*?
Comment: @ToddWilcox "I myself am convinced I can hear differences between certain things that scientific measurements would seem to show are identical" Of course. You don't hear *anything* with your ears. You hear with your brain. Unless you are listening inside a functional MRI brain scanner, no scientific instrument is measuring what *you* are hearing - and of course whatever you hear is unique to you personally.
Comment: @Tim I would imagine it applies to all speakers. It is of special importance wrt studio monitors, because there accuracy and consistency are paramount. I'd say the *user's* adjustment period goes without saying.
Answer: The only measurements of speaker parameters made before and after alleged break-in periods I could find online support the notion that break-in is almost entirely a myth. The essence is that any physical changes that a speaker undergoes when it is first made to move are almost instantaneous and almost always occur doing factory testing, so any "break-in" done at home after buying a speaker is meaningless.
One thing that does happen is the speaker and enclosure behavior change slightly and temporarily as they heat up, and once cool again the original behavior is restored. A permanent change caused by heat would be considered damage and while it's theoretically possible heat damage could sound better to some ears at first, if continually heated to the same point the speaker will fail.
Here's a link to the best article I found:
http://www.audioholics.com/loudspeaker-design/speaker-break-in-fact-or-fiction
And quotes (emphasis mine):

Required break in time for the common spider-diaphragm-surround is typically on the order of 10s of seconds and is a one-off proposition, not requiring repetition. Once broken in, the driver should measure/perform as do its siblings, within usual unit-to-unit parameter tolerances.
Quite often, spider break in occurs when the driver is tested, before and/or after placement in the cabinet for which it's intended. Driver testing by signal stimulus at some point (or points) in the manufacturing process - if done at levels sufficient to break in the spider - generally makes further break in unnecessary. Hence, a finished system will not - in so far as its drivers are concerned - require further break in by a consumer once taken home from the dealer.
Taken together, it's clear the volume of air confined within the sealed cabinet of the enclosed box loudspeaker system moderates any measurable and/or audible changes that might arise as a consequence of driver compliance changes.
When the test series was run to completion, the resulting amplitude response graphs indicated that an end user would likely encounter larger system-to-system amplitude response differences (~1.04 dB Spl) owing to normal driver variances than would be encountered breaking in raw drivers.
Cease stimulus and the driver's compliance will return - in most cases within seconds or minutes depending upon surround design, material composition, ambient temperature and so on - to its pre-stimulus value; the compliance changes are temporary. So too are the changes that occur in all the other driver parameters that are effected by compliance, hence the changes in fs , vas, etc.
Four years after the system had been installed in the theater, I had the opportunity to go back and take some measurements. I availed myself of the opportunity and found that the amplitude response plots made that day matched to within a fraction of a dB those made when the system was first installed. Four year's worth of "breaking in" hadn't affected the system to any significant degree.
Comment: Just make sure you do break in  your Monster cables before turning up the volume.  Those electrons need to build their ideal pathways along the metal strands.    [yes, this is a joke, you humor-impaired dopes!]
Comment: I never understood monster cables: monsters don't exist, why would I need cables for them?
Comment: @CarlWitthoft - I thought the way to break in Monster cables was to tow a car a certain distance with them...
Comment: @CarlWitthoft Thanks for calling me a dope. It adds a lot to my answer.
Comment: I didn't call **you** a dope -- unless you actually bought Monster cables!
Comment: @CarlWitthoft Seems like you're calling people who didn't realize it was a joke at first "humor impaired dopes."
Comment: +1 From the article you quote it would appear that there is something that might need breaking in, but is likely to have already been broken in during manufacturer testing (or not, as the anecdote section illustrates). I would therefore hesitate to call break-in a myth, but rather say it's probably unnecessary post purchase. Either way, if no better answer shows up today, I will accept this one.
Answer: You have no choice about whether to 'break in' any piece of equipment, other than not using it at all!  The only question is whether you listen to them while it's happening (or, apparently, according to the consensus, not happening).
I'd like to see a double-blind experiment where identical speakers were compared, one set being powered only for the short test sessions, the other comprehensively 'burnt in'.   I suspect the results would be the same as for similar tests between different (but all adequate) cables.
@Todd Wilcox's  quoted test https://www.audioholics.com/loudspeaker-design/speaker-break-in-fact-or-fiction is impressive for the quantity of impressive-looking mathematical formulas, designed, of course, to boost the writer's credibility as an audio guru.  The paucity of research on this topic only reinforces my feeling that it's 'Well, maybe, a bit, but what'ya going to do about it anyway? Any burn-in differences are, I suspect, going to be orders of magnitude less that those caused by moving your ear position by a few inches.
Answer: Here is some rationalization (without empiric support): speaker cones are basically paper, glue and coating.  In that respect they are similar to accordion bellows.  Accordion bellows need a bit of "breaking in" both when new as well as when unplayed for days: when opening and closing them, they will make rustling noises at first.
Now obviously there are significant differences: accordion bellows do not work like springs, the creases are quite sharper, behavior does not need to be linear, the glue used is quite different and so on.
And when we are talking about monitors with non-trivial quality, they have had to go through testing (and deliver good results) before being shipped, and you cannot really afford materials that will require newly breaking in after every larger pause.
At any rate: if the speakers still smell when they get delivered, glue has likely still evaporated during shipping and the results might loosen up a bit under load still.
As I said: purely speculation on my part, but I'd imagine something like that being the rationale for such advice, whether or not it's actually snake oil.
Comment: "Speaker cones are basically paper, glue and coating" - Yes, back in the 1960s, but not any more - except for those who want to use 1960s technology to create its own characteristic sound. But the OP was asking about studio monitors, not reproductions of 50 year old guitar tube amps and cabinets. Modern speaker cones are more likely to be made from Kevlar, carbon fiber, rigid plastics, or even aluminium or titanium than paper and glue. And horn-loaded piezoelectric drivers don't even have "cones" at all.
Comment: @ScottWallace it's not just "loosening up,"  there's the general aging of the wood and the varnish on/in the wood.   As you probably know, this is an area of great controversy over in bowed-instrument-land, where there is no argument that nearly all instruments play much better after a few years.   ("few" being anything from two to 200)
Comment: I think @Carl Witthoft may need to treat 'there is no argument that nearly all instruments play much better after a few years' as a misprint and change it to 'there is NOW argument that nearly all instruments play much better after a few years'.
Comment: Had to downvote, I'm afraid. Such unsupported speculation doesn't really contribute anything,
Comment: Yep.  You can break in a guitar or a violin by playing on it for a couple of months, or (as many luthiers do nowadays) by attaching a driver to the bridge and vibrating it at various frequencies for a  day or a week.  This makes a difference because there are all kinds of places on an instrument that get loosened up with use.  But especially a modern speaker cone and its suspension is not going to change (unless it's defective) substantially by any playing-in due to the nature of its design and materials.
Comment: "A few years" may be too short. I remember some complaints about a new pipe organ being "a bit of a screamer" which got a fairly short answer from the organ builder, "Well, come back and listen to it again in 100 years time, after the building has got used to the way it vibrates the stone work" (Parts of the building were already about 700 years old!)
Comment: @LaurencePayne nope
Comment: @CarlWitthoft- by "loosening up", I meant all those things and many others too numerous to list.  On a violin, those would also include the compression and weaking of the glue of the purfling, the increasingly closer fit of the soundpost as its wood and that of the belly and back where it sits as it gradually slips into a position of less pressure, and many more.  But a comment only has a certain amount of room and I only have a certain amount of time.
Comment: @Scott Wallace (aka Fermat Wallace) Is there a Music SE discussion of this topic, that an instrument "opens up" or sounds better after playing? I am aware of the controversy, but have not seen convincing argument one way or the other. At present I'm in the camp that does not believe an instrument changes after moderate playing (who knows about 200 years) - rather the player changes to accommodate the efficiencies and characteristics of the instrument.
Comment: @EricO- sorry, I don't know if there's a Music SE discussion of this.  Probably the effect is small over short periods of time, and depends on how the instrument is built as well.  It might well be that the player adjusting to an instrument is a more important factor.
Answer: Yes. It cannot hurt. I have been burning in all my audio video gear for years. The first thing that happens is they become more dynamic. They have higher highs and lower lows. Then, at some point later, our brains become accustomed to the sound. That is where people disagree. Not whether it is an act of substance, but how we here them changes. If it is in fact the latter, then burn in always has benefited any new system. To me, it's very obvious and in my face, if you will. It's real. I would not waste precious time otherwise. A louder than normal volume helps to speed up the process.
Comment: It seems possible, even likely, that what's actually changing during your burn in experiences is your perception of the sound quality. We know that ears adjust their response to continuing sound over time, and louder sounds cause greater changes.
Comment: @ToddWilcox the fact that you need to learn the sound of new speakers is well known and accepted among the audio engineers – but it has nothing to do with "burning in".
Answer: I've found with higher end audio gear and studio monitors , with speaker break in you get more enhanced bass and mids,  I sanity checked this with producer friends, it can take as much as 24 hours but can happen quicker .
Comment: How did you measure the difference in response before and after?


Mass change Microsoft DNS & IIS server settings

Question: I need to change about 100 DNS records and IIS configurations on a Windows 2003 web server.  The GUI doesn't accommodate it and the MS command line tools seem incomplete (for example: dnscmd cannot edit a record, only create).  Is there a third party tool out there I can use?
Basically I just need to change one IP address to another.
Answer: I think something like this would help; you can edit the DNS file in your favorite text editor.
Comment: I ended up using dnsdump http://www.reskit.net/DNS/dnsdump.cm_ to dump the DNS config then used PSPad to do a multi file find and replace, then imported the changed config with dnsdump.
Comment: For the IIS config I created a backup configuration in IIS Manager, edited the backupname.MD0 file and then restored the backup.  Worked like a charm.
Answer: It's pretty easy to update dns records from the powershell command line, (as I was looking up a wmi query I found someone else that already wrote the code I was writing so here's the link)
try this code: PowerShell: Script to make batch DNS changes

From the site:
<code>$CNAMES = import-csv "Path to CSV file"
$Query = "Select * from MicrosoftDNS_CNAMEType"
Foreach($CNAME in $CNAMES)
{
$CNAME
$Record = Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName dnsserver | Where-Object{$_.Ownername -match $CNAME.Aliases}
$Record.RecordData = "FQDN of new IIS server"
$Record.put()
}
</code>
The script can be modified to update any kind of DNS record, so it's not locked into just updated CNAME's


Podio API - updating contact reference

Question: I have an an Podio app that handles customer accounts where each customer has a manager (podio contact). All of this data resides in another system, and we are in the progress off writing software to synch the two. The software is written in java and using the podio api
I'm currently able to read and set all types of fields, except for the manager field (contact).
This is what is received from the API when a customer is loaded:

But how do you go about updating the manager reference to something else?
I've tried something like:
List<Map<String, Object>> list = new ArrayList<>();
HashMap<String, Object> values = new HashMap<>();
list.add(values);

HashMap<String, Object> value = new HashMap<>();
values.put("value", value);

value.put("mail", "firstname.lastname@example.com");
//also tried user_id and profile_id

and then using the
ItemAPI.updateItemFieldValues(int itemId, int fieldId,
        List<Map<String, Object>> values, boolean silent, boolean hook)

to update the field. Where am I going wrong?
Answer: Setup:
Podio app with 'Contact' field, configured to 'Workspace members / share when new address added' (like this screnshot)

Working example in Ruby
  item_id = <some_item_id>
  field_id = <contact_field_numeric_id>
  field_external_id = <contact_field_external_id>

  # set to empty value by field_id
  empty_value = []
  Podio::ItemField.update(item_id, field_id, single_value)

  # set to single value by field_id
  single_value = [{'value' => {'type' => 'user', 'id' => <Podio user id>}}]
  Podio::ItemField.update(item_id, field_id, single_value)

  # set to multiple values by external field id
  multi_values = [{'value' => {'type' => 'user', 'id' => <Podio user id>}},
                  {'value' => {'type' => 'user', 'id' => <another Podio user id>}}]
  Podio::ItemField.update(item_id, field_external_id, multi_values)

Will set this contact field to new value single_value or to list of new values multiple_value. Also, I'd strongly recommend to think again about your data architecture. It might be much more scalable to work with Podio Contact app type and use Reference field instead of using Contact field.
Java example:
HashMap<String, Object> pair = new HashMap<>();
HashMap<String, Object> value = new HashMap<>();
List<Map<String, Object>> list = new ArrayList<>();

// set to empty value
list = new ArrayList<>();
ItemAPI.updateItemFieldValues(<itemId>, <fieldId>, list, <silent>, <hook>)

// set to real value
value = new HashMap<>();
list = new ArrayList<>();
pair.put("id", <user_id>);
pair.put("type", "user");
value.put("value", pair);
list.add(value);
ItemAPI.updateItemFieldValues(<itemId>, <fieldId>, list, <silent>, <hook>)

Comment: I've implemented your java example, and it works with type: user, and id set.
The setup isn't necessary in our case as all managers are workspace members.

As a bonus info. Can you add how to set manager=null?
Comment: using an an empty pair map doesn't work (in java at least): APIException [status=Bad Request, error=invalid_value, description=Invalid value {} (object): must be integer or must be integer or missing required properties: ['type', 'id'], parameters=null]. And adding type and a null id neither.

Podio API - updating contact reference


How to set mainActivity unshown in release and shown in debug version automatically

Question: I want to set MainActivity unshown in release and shown in debug version automatically. I knew how to do in manifest file manually, but I want to do it automatically when compile and export debug or release version.
Is there anyway to do that?
Thx!
Answer: You need to have two different manifest files for debug and release, the way to achieve this is to put them under src/release/ and src/debug/ directories
Comment: any other way to solve it? Like use code to config it dynamically?
Comment: AFAIK scope of your requirement is above your code, but If you are not strict on your request, you may create a bridge activity set it as default and based on your state (`BuildConfig.DEBUG`) you can finish it and start your desired activity


Solution to an ODE $f'(t) = S(0) + \mu f(t)$

Question: I came across this problem In a finance module of mine and I don't quite understand the solution.
The actual equation is as follows:
$E[S(t)] = S(0) + \mu \int^{t}_{0} E[S(u)]du$
Where $S(t)$ is an asset price at time $t$ And $E$ is the expectation.
The solution to the question is given as:
$E[S(t)] = S(0)e^{ut}$
and is stated that this is obtained from solving an ODE.
I am probably missing something really obvious here, but if someone could fill in the steps then that would be great!
Answer: You differentiate both sides with respect to $t$ leading you to
$$\frac d{dt} E[S(t)] = \mu E[S(t)].$$
This is a simple ODE which is known to have the solution
$$E[S(t)] = E[S(0)] \exp(\mu t),$$
where $E[S(0)] = S(0)$, since you already know the price at the beginning.
Answer: The initial value problem
$$
x'(t)=f(t,x(t)), \;x(0)=x_0
$$
is equivalent to the integral equation
$$
x(t)=x_0+\int_0^t f(s,x(s))\,ds.
$$
This is the basis for the existence theorems for ODE and the Picard iteration.
In your case you go backwards from the integral equation to the ODE. You could also use the usual integrating factor to find
$$
\frac{d}{dt}\left(e^{-μt}\int_0^t\Bbb E[S(u)]du\right)=e^{-μt}\Bbb E[S(0)]
$$
and so on without assuming the differentiability of $\Bbb E[S(t)]$.


Argparse in iPython notebook: unrecognized arguments: -f

Question: I am trying to pass a .py file to ipython notebook environment.
I have never had to deal directly with argparse before. How do I rewrite the main() function?
I tried to delete the line of def main(): and keep the rest of the code.
But args = parser.parse_args()" returned an error:

ipykernel_launcher.py: error: unrecognized arguments: -f.

And when I run . %tb:
showing this
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='data/tinyshakespeare',
                   help='data directory containing input.txt')
parser.add_argument('--input_encoding', type=str, default=None,
                   help='character encoding of input.txt, from https://docs.python.org/3/library/codecs.html#standard-encodings')
parser.add_argument('--log_dir', type=str, default='logs',
                   help='directory containing tensorboard logs')
parser.add_argument('--save_dir', type=str, default='save',
                   help='directory to store checkpointed models')
parser.add_argument('--rnn_size', type=int, default=256,
                   help='size of RNN hidden state')
parser.add_argument('--num_layers', type=int, default=2,
                   help='number of layers in the RNN')
parser.add_argument('--model', type=str, default='lstm',
                   help='rnn, gru, or lstm')
parser.add_argument('--batch_size', type=int, default=50,
                   help='minibatch size')
parser.add_argument('--seq_length', type=int, default=25,
                   help='RNN sequence length')
parser.add_argument('--num_epochs', type=int, default=50,
                   help='number of epochs')
parser.add_argument('--save_every', type=int, default=1000,
                   help='save frequency')
parser.add_argument('--grad_clip', type=float, default=5.,
                   help='clip gradients at this value')
parser.add_argument('--learning_rate', type=float, default=0.002,
                   help='learning rate')
parser.add_argument('--decay_rate', type=float, default=0.97,
                   help='decay rate for rmsprop')
parser.add_argument('--gpu_mem', type=float, default=0.666,
                   help='%% of gpu memory to be allocated to this process. Default is 66.6%%')
parser.add_argument('--init_from', type=str, default=None,
                   help="""continue training from saved model at this path. Path must contain files saved by previous training process:
                        'config.pkl'        : configuration;
                        'words_vocab.pkl'   : vocabulary definitions;
                        'checkpoint'        : paths to model file(s) (created by tf).
                                              Note: this file contains absolute paths, be careful when moving files around;
                        'model.ckpt-*'      : file(s) with model definition (created by tf)
                    """)
args = parser.parse_args()
train(args)

Comment: I use `ipython` a lot, but not the notebooks.  But if I recall other SO correctly you can't pass script specific commandline arguments to a notebook.  You can just use the arguments that `ipython` uses to start the server.  What commandline are you using (that includes the `-f` flag)?  https://stackoverflow.com/questions/43057529/how-to-pass-command-line-arguments-in-ipython-jupyter-notebook
Comment: What was the command line that gave this error?
Answer: You can try args = parser.parse_args(args=[]).
Answer: As @nbro suggested, the following command should work:
args = parser.parse_args(args=[])

In addition, if you have required arguments in your parser, set them inside the list:
args = parser.parse_args(args=['--req_1', '10', '--req_2', '10'])

Where you previously used:
import argparse
parser = argparse.ArgumentParser(description="Dummy parser")
parser.add_argument("--req_1", type=int, required=True, help="required int 1")
parser.add_argument("--req_2", type=int, required=True, help="required int 2")

You can also see from the notebook all params:
print("see all args:", args)
print("use one arg:", args.req_1)

You can find more information in the docs: Parsing arguments
Comment: Can I pass the required argument values from the other notebook?
Answer: It's better to use @nbro 's answer for Jupyter execution.
args = parser.parse_args(args=[])

If you want to manage parameters as class format, you can try this.
class Args:
  data = './data/penn'
  model = 'LSTM'
  emsize = 200
  nhid = 200

args=Args()

Comment: Solution of @nbro is easier and doesn't require modifying existing parser
Answer: An example is:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo')
args = parser.parse_args(['aa']) # actually you don't have to write (args=['aa'])
print(args.echo)

the output should be
>>> aa


Steps in CLT proof unclear

Question: In john rice Mathematical Statistics and Data Analysis we find a proof about the central limit theorem.
Let $X_1, X_2,\ldots$ be a sequence of independent random variables having variance $\sigma^2$ and the commmon distribution function $F$ and moment generating function $M$ defined in a neighborhood of zero. Let
$$S_n = \sum_{i = 1}^n X_i$$
Then:
$$\lim_{n \longrightarrow \infty}P \left( \frac{S_n}{\sigma \sqrt n} \le x\right) = \Phi(x)$$
Proof:
Let $Z_n = \frac{S_n}{\sigma \sqrt{n}}$
Since $S_n$ is a sum of independent random variables:
$$M_{S_n}(t) = [M(t)]^n$$
$$M_{Z_n}(t) = \left[M\left(\frac t {\sigma \sqrt n}\right)\right]^n$$
$M(s)$ has a Taylor series expansion about zero.
$$M(s) = M(0) + s M'(0) + \frac{1}{2}s^2 M''(0) + \varepsilon_s$$
where $\frac{\varepsilon_s}{s^2} \longrightarrow 0$ as $s \longrightarrow 0$.
Why is this? And why is it useful? I thought that if the denominator of a fraction converges to zero you would essentially have an expression that have a zero value in the denominator which would produce an undefined value.
Since $E(X) = 0$, $M'(0) = 0$ and $M''(0) = \sigma^2$.
As $n \longrightarrow \infty, t/(\sigma \sqrt{n}) \longrightarrow 0$
The statement $n \longrightarrow \infty, t/(\sigma
\sqrt{n}) \longrightarrow 0$ made, but why is it useful?
$$M\left(\frac{t}{\sigma \sqrt{n}}\right) = 1 + \frac{1}{2}\sigma^2 \left(\frac{t}{\sigma \sqrt{n}}\right)^2 + \varepsilon_n$$
I assume the above follows from the fact that $s = \frac{t}{\sigma \sqrt{n}}$ So you replace this into the taylor expansion, but why is $\varepsilon_{s}$ replaced with $\varepsilon_n$?
Comment: What do you mean by the latter $s$ terms?
Comment: "if the denominator of a fraction converges to zero you would essentially have an expression that have a zero value in the denominator which would produce an undefined value." $${}$$ THAT IS FALSE. All derivatives are limits as the numerator and denominator approach $0.$ If that made them undefined, then all derivatives would be undefined. If the denominator approaches $0$ while the numerator approaches something else, then the limit is undefined, but if they BOTH approach $0,$ then in many cases the limit exists.
Comment: consider $2^{-n}/2^{-n}$ denominator is going to zero but always equal to 1 for any integer n
Comment: (Partial hint, hence comment) - For $\epsilon_s / s^2 \rightarrow 0$ as $s \rightarrow 0$, the reason this is the case will be more apparent if you expand the Taylor series of $M(s)$ for a few more terms and compare the latter $s$ terms in relation to $1/s^2$.
Answer:
if the denominator of a fraction converges to zero you would essentially have an expression that have a zero value in the denominator which would produce an undefined value."

THAT IS FALSE. All derivatives are limits as the numerator and denominator approach $0.$ If that made them undefined, then all derivatives would be undefined. If the denominator approaches $0$ while the numerator approaches something else, then the limit is undefined, but if they BOTH approach $0,$ then in many cases the limit exists.
Note that if the numerator is $s^3$ and the denomoinator is $s^2,$ then certainly the fraction approaches $0$ as $s^2\to0.$
Comment: Ok that clears up part of my confusion. Why is the fact that $\frac{\epsilon_{s}}{s^2} \longrightarrow 0$ as $s \longrightarrow 0$ even useful in the proof?
Comment: @DanielDeWet : Recall from calculus that $$ \lim_{n\to\infty} \left( 1 + \frac a n \right)^n = e^a,$$ so in particular, $$ \lim_{n\to\infty} \left( 1+\frac{t^2}{2n} \right)^n = e^{t^2/2}.$$ But what you have is $$ \lim_{n\to\infty} \left( 1+\frac{t^2}{2n} + \cdots \right)^n.$$ The idea is to show that the terms appearing where those dots are do not alter the bottom line. $\qquad$
Comment: What do you mean the terms appearing where those dots are do not alter the bottom line? What is this bottom line you are talking about?
Comment: @DanielDeWet : By "the bottom line" I meant the expression to the right of the "equals" sign, i.e. $e^{t^2/2}. \qquad$
Comment: Sorry for all of the questions but I'm not sure what you mean by "altering" the expression $e^{\frac{t^{2}}{2}}$
Comment: @DanielDeWet : Calculus tells us that $\displaystyle\lim_{n\to\infty}\left( 1 + \frac{t^2}{2n}\right)^n = e^{t^2/2}.$ But what about $\displaystyle \lim_{n\to\infty} \left( 1 + \frac{t^2}{2n} + \cdots \right)^n,$ where the dots represent some additional terms after those first two? The question is whether the limit will still be $e^{t^2/2}.$ And that depends on what those additional terms are. It is claimed that if the sum of those additional terms divided by $s^2$ approaches $0$ as $s$ approaches $0,$ then the limit will still be $e^{t^2/2}. \qquad$

Steps in CLT proof unclear


Why do we sometimes define likelihood as $p(\textbf{T}|\textbf{X},w)$ and sometimes as $p(\textbf{X}, \textbf{T}|w)$?

Question: Let's suppose we have a dataset $\mathcal{D}=(\textbf{X}, \textbf{T})$ where $\textbf{X}$ are the samples and $\textbf{T}$ are the targets. We want to find $w$ such that the likelihood is maximized. When doing this sort of exercises in my Machine Learning course, we sometime define likelihood as $p(\textbf{T}|\textbf{X},w)$ whereas sometimes we define it as $p(\textbf{X},\textbf{T}|w)$. Why is this a legitimate thing to do? Shouldn't the likelihood be just the latter, since our dataset is composed by both $\textbf{X}$ and $\textbf{T}$? Is there a mathematical reason why we can do this, or is it just a matter of defining it in the easiest way depending on the context?
Answer: The first one is conditional joint, and can be written as $p(\mathbf{X},\mathbf{T}|w)=p(\mathbf{T}|\mathbf{X},w)P(\mathbf{X}|w)$. $w$ relates data to targets, so it's generally assumed that $p(\mathbf{X}|w)=p(\mathbf{X})$, which means the second term is nothing but a constant if we aim to maximize the expression with respect to $w$. So, both are valid and give the same $w_{ML}$ estimate.