Simplified notation for two-note tremolo

Question: Does first and second bar mean the same thing? If no, is there a simplified notation for the first one?
Comment: You should specify the instrument(s) in question.  In this case it may not matter, but for some markings it does
Comment: Actually the first **is** the most simplified notation already (and as such may not be known to inexperienced nor not formally trained players), full notation would have beams with each 32th note listed.
Answer: These two bars don't denote the same thing. The first asks the player to alternate the two notes. The second asks the player to repeat the two-note chords.
Comment: Beat me to it! Nice to see some answer from you again!
Answer: There are two different types of tremolo indicated in your example.
The first bar, where the tremolo lines are placed between notes, requires the rapid reiterations (here, in 32'nd notes) of the alternating notes indicated.  The first tremolo requires that we alternate between middle C and its octave (higher) in 32'nd notes for half a measure.  The second tremolo requires that we alternate similarly between E's.
The second bar, where the tremolo lines are written through the stems of the notes, require that we play the notes rapidly in unison.  So, with the first tremolo in the 2nd measure, we play the middle C and its octave in unison, in 32nd notes for half a measure.  And similarly for the second tremolo on E.


Using part of a composite primary key in a composite foreign key in NHibernate

Question: We have a fairly big DB (~200 tables) which almost entirely uses composite primary keys and composite foreign keys, using a single "base table" from which every other table inherits part of its primary key:

Parent has single column primary key ParentId
Child has composite primary key (ParentId, ChildId) and foreign key ParentId
Nephew has composite primary key (ParentId, NephewId), foreign key ParentId and foreign key (ParentId, ChildId)

and so on. Up until now we managed this whole shebang with an ORM framework of our own, but we're considering using NHibernate, which I've been assigned to learn (i've downloaded v2.1.2).
The mappings:
Child
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Assembly" namespace="Namespace">
<class name="Child" table="Child">
    <composite-id name="IdChild" class="ChildId">
        <key-many-to-one name="Parent" column="ParentId" class="ParentId"></key-many-to-one>
        <key-property name="Id" column="ChildId" type="Int32"></key-property>
    </composite-id>

    <set name="Nephews" table="Nephew">
        <key>
            <column name="ParentId"></column>
            <column name="ChildId"></column>
        </key>
        <one-to-many class="Nephew"/>
    </set>
</class>
</hibernate-mapping>

Nephew
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Assembly" namespace="Namespace">
    <class name="Nephew" table="Nephew">
        <composite-id name="IdNephew" class="NephewId">
            <key-many-to-one name="Parent" column="ParentId" class="Parent"></key-many-to-one>
            <key-property name="Id" column="NephewId" type="Int32"></key-property>
        </composite-id>
        <many-to-one name="Child" class="Child">
            <column name="ParentId"></column>
            <column name="ChildId"></column>
        </many-to-one>

    </class>

I can post the classes too if you want, I'll omit them now for brevity (as I'll omit the mapping for Parent, since it doesn't have problems). Every property is virtual, every mapping file is an embedded resource, every composite Id has its own class which overrides Equals and GetHashCode.
The problem is I can't save an instance of Nephew, initialized through a simple new Nephew() and passed on to _session.Save(), because I get a System.IndexOutOfRangeException: Invalid index n for this SqlParameterCollection with Count=n..
The only column which is duplicated in the mapping is the ParentId. Removing the many-to-one mapping in the Nephew, the set mapping in the Child and all related properties everything works fine.
I found several posts reporting this exception, and the most appropriate in my case seems to be this one, which gives me the gut feeling that my current schema is infeasible with NHibernate. Please tell me I'm wrong :-)
NOTES:

I'm not using Fluent right now, even though it may be an option, but I preferred learning the basics first;
Yes, we realize composite primary keys are a big pain in the ass. This DB has passed through several hands through the years, probably not so skilled ones, but before refactoring it we will count to 10 000
Answer: Unfortunately, you won't be able to map that relationship in its current form, as you have inferred.
However, there's a workaround. Instead of mapping Nephew.Child as a many-to-one, map ChildId as a regular property, and use a query when you need to retrieve the Child.
There's one more chance for a hack. If and only if Nephew.Child is not null and not mutable, you could map the key referencing the Child instead of the parent:
<class name="Nephew" table="Nephew">
  <composite-id name="IdNephew" class="NephewId">
    <key-many-to-one name="Child">
      <column="ParentId">
      <column="ChildId">
    </key-many-to-one>
    <key-property name="Id" column="NephewId"/>
  </composite-id>
</class>

Comment: Thank you. Your first suggestion partly works, but I lose the ability to cascade save the nephews by only calling _session.Save(child). I have to manually create a Child.Add(Nephew) method that adds the nephew to the Nephews collection and sets the simple property ChildId in the Nephew, even with  inverse="true" and cascade="all" in the  tag. It still is more than nothing
Answer: I found a better solution:
<many-to-one name="Child" class="Child">
    <formula>ParentId</formula>
    <column name="ChildId"></column>
</many-to-one>

I had already tried that and it gave me an error, but then I noticed this patch, so I downloaded the 3.0.0 alpha2 and it all worked correctly! Thanks to this solution I can map the Nephew.Child property as it was meant to be.
I still need the Child.Add(Nephew) method, though (but I realized that is recommended even in the documentation)


Using TLS on Google Talk XMPP TCP connection using PHP

Question: I am trying to connect to the Google Talk XMPP server using PHP. I am successful establishing a connection and logging in using X-OAUTH2. Then Google requires I establish a TLS connection. However when trying to upgrade the connection to TLS I get an exception: stream_socket_enable_crypto(): Peer certificate CN='gmail.com' did not match expected CN='talk.google.com'.
Here are my steps:
$stream = stream_socket_client('tcp://talk.google.com:5222', $error_num, $error_str);
// ... I login,
//server tells me to use TLS,
//I tell it I am going to,
//it tells me to proceed ...
stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

And I get this error:
stream_socket_enable_crypto(): Peer certificate CN='gmail.com' did not match expected CN='talk.google.com'

Of course, if I try to connect to the xmpp server via tcp://gmail.com or tcp://www.gmail.com, it won't work.
I have also tried establishing the TLS before logging in (Which, I would assume is the more secure way of doing it), but I get the same problem. Here is the whole handshake up to the error:
Me:     <stream:stream to="gmail.com" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">

Google: <stream:stream from="gmail.com" id="7373AF2152849B51" version="1.0" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">
            <stream:features>
                <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls">
                    <required/>
                </starttls>
                <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
                    <mechanism>X-OAUTH2</mechanism>
                    <mechanism>X-GOOGLE-TOKEN</mechanism>
                </mechanisms>
            </stream:features>

Me:     <auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="X-OAUTH2" auth:service="oauth2" xmlns:auth="http://www.google.com/talk/protocol/auth">Encrypted user and pass</auth>

Google: <success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>

Me:     <stream:stream to="gmail.com" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">

Google: <stream:stream from="gmail.com" id="B3A6AD05178A5BF2" version="1.0" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">
            <stream:features>
                <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls">
                    <required/>
                </starttls>
                <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
                <session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>
            </stream:features>

Me:     <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>

Google: <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>

Answer: I haven't figured out how to fix the problem, but I could avoid it altogether by connection via tls from the get-go and using port 5223 instead:
stream_socket_client('tls://talk.google.com:5223', $error_num, $error_str);


Archery for 67 years old beginner

Question: My father is 67 years old and wants to start archery as a hobby.
I don't have the knowledge to select a proper bow & arrow (set) for him.

What should I pay attention to?
What should a beginner archery equipment include?
Does this sport require some gloves or similar items?

Side note:
My father had a surgery and got 3 stents for his heart attack. Would archery have a negative effect on his health?
Answer: Forgive me if I don't know the archery-terminology, its been years since I've released an arrow. My primary advice is to go shoot at a local archery range if you're a beginner, and you'll probably get competent advice there as well. When I started to shoot, I didn't buy any equipment - I could get a beginner's set of everything I needed at the archery range at which I trained. Once I started going to competitions (who says your dad won't? : ) I bought my own equipment and also maintained it, but that was after 2 years of using standard rented equipment. Plus - I found the crowd at archery ranges to be quite easy going, a very pleasant surrounding to spend time.
Health: First off - the health issue. I practiced competitive archery for 3 years, and don't recall ever getting an elevated heartbeat. So circulatory problems shouldn't be a worry. Depending on the volume of arrows you shoot, or if your bow is too strong for you, you can have cramps and muscle-aches in the back/shoulder area. But if you take it easy at the beginning, and slowly work yourself up to higher volumes and a heavier bow, you should be fine.
Equipment:This is an overview, best to consult someone at the shop or better yet at an archery range, about buying equipment. The expensive stuff(bow, arrows), you'll probably be able to rent at the range for a membership fee, and is what I'd start with, until you feel you like archery enough to buy your own bow/arrows.

Bow: there are 3 types of common bows: long-bow(stick with a string), recurve(end of sticks curve in shooting direction), compound(wheels & pimpy technology). The long-bow is generally shot for aesthetic reasons, say if you are interested in medieval times, or have a back-to-nature thingy and want to practice archery in it's "pure" form. Compounds have an initially hard draw, then the draw becomes a joke - helps to keep stable when aiming. Recurves have a fairly evenly difficult draw, and are the olympic standard for archery (I think).
Arrow: too many types to explain, depends on the bow, the target, and how much you want to spend. Best to ask at the local archery store about each individually available arrow type. Apart from that, you want to differentiate between 3 parts of the arrow - the head, the shaft and the feathering, which can be put together in various combinations.
Protection: when you release that string, you don't want some piece of body getting caught in its way. A MUST is a fore-arm protection, for the arm holding the bow. It's basically a leather strap which you tie around your arm. Some people, for example if you like to wear windy clothes or have a big chest(belly ;), also get breast-protection to keep the chest on the side of your bow-holding arm all packed in tight, so the string doesn't chip off a nipple. Then most archers also use a finger-thingy, which you put on the fingers you pull the string with, to protect your skin from too much wear.
Aim: unless you're shooting long-bow, you'll probably use some sort of sights. Maybe for the first couple times holding a bow you'd shoot without.
Stabilizers: are counter-weights on rods which get attached to your bow, so that the force of releasing the arrow doesn't shake your bow too much - which can be a pain after shooting a couple dozen of arrows. But this shouldn't be a problem with lighter bows.

Good luck to your dad. In the end, good shooting is about securely repeating form. Equipment comes second.
Comment: Thank you very much for your extensive answer:) There isn't any local range in the country I live so I have to research and trust on kind people like you for the correct things to do. My father didn't want to have the protections but I'll pursue him to get those too. I think I'll get him an composite bow for the beginning :) THANK YOU VERY MUCH!
Comment: Vielen vielen Dank mein Herr :)
Comment: Sure a compound will do. Get practice arrows which don't have fancy points. If he doesn't have anyone to teach him the correct form. Tell him that he should try to stand straight (he should NOT push his neck out infront, and his shoulders shouldn't be hunched up - he needs to relax in his full-draw position in order to aim properly). He should breathe calmly. The string should then slightly touch his lips, and when he lets go, he should just relax his fingers. If he turns his hand away or does some movement with his body, his aim will suffer and get an unnatural direction. Aim is everything!:)
Comment: As for the shoulders - he should try to make his shoulder-blades "touch" behind his back.
Comment: I'll tell him that :) Also a couple of youtube videos should suffice I think:) VIELEN DANK!
Comment: No Points? ;P Anything you feel is missing from this answer?
Answer: I just want to add something about this question "Would archery have a negative effect on his health?"
As far as I concern (I'm not a doctor or specialist), if you can reduce your stress level, then it's good actually for blood circulation and also leads to a healthy heart. I found this research paper, and the finding is, "playing archery sports has a positive effect on coping with stress"
Furthermore, another study also shows that "The wrong drawing technique will create muscle fatigue due to increased muscle activity".
So you just need to make sure that, a proper method needs to be implemented or maybe the archery club has the qualified coach to teach the first step. If not it will also cause injury according to that research paper.
Somehow, I think the archery will promote good health if the technique being performed the right way. And I think this finding also good to read -https://www.researchgate.net/publication/318086934_PHYSICAL_PERFORMANCE_MEASURES_IN_COMPETITIVE_SENIOR_ARCHERS
All in all, based on scientific research and in fact, your father is good to go for this kind of sports. You just need to expand the knowledge and get to know the archery terminology. It will be useful if you really want to buy the archery stuff and also easy to understand while having a conversation with the archers at the local archery club.

Archery for 67 years old beginner


How to simulate R data for a random effects model set-up?

Question: Suppose we have $m$ schools chosen randomly from among thousands in a large country. Suppose also that $n$ students of the same age are chosen at each school. Let $Y_{ij}$ be the score of the $j$th student at the $i$th school.
One model we can come up with is:
$$
Y_{ij} = \mu + U_i + W_{ij}
$$
where the $\mu$ variable is the average score for the entire population. From this model, $U_i$ is a random effect with $W_{ij}$ being the error term. Suppose that I want $U_i$ to be normally distributed. That is, each school has a different normal distribution parameter: $U_i$.
I am wondering how a scenario like this can be simulated in R, for say $m = 5$ schools, $n = 100$ students?
Answer: Simulate random effect model.
m <- 5 #number of schools
mu <- 12.56 # global score average
sdU <- 5.67 # standard deviation for the random effect
sdW <- 3.25 # standard deviation for the noise

# values for the random effect
U <- rnorm(m, mean=0, sd = sdU)

# Number of observations in each school
n <- 100

N <- m*n

data <- data.frame(school = rep(1:m, each=n))
data$U <- U[data$school] # random factor value for each school
data$val <- rnorm(m*n, mu + data$U, sdW)

library(lme4)
library(lmerTest)

# Estimate parameters set earlier
m1 <- lmer(val ~ 1 + (1|school), data = data)
summary(m1)

# If you look at the summary and the Random Effects section, the estimates for
# schools (sdU) and for the noise (sdW) should be close to those defined above.
sU <- sdU^2 # Variance (only for the reference)
sW <- sdW^2 # Variance (only for the reference)
```

Comment: Are the lines `sU <- sda^2; sW <- sdf^2` supposed to be included? `sda` and `sdf` aren't defined, and `sU` and `sW` are never used.
Comment: I've downvoted this answer because this code doesn't work (for the reasons already stated) and is effectively misleading. The answerer may consider editing the answer to include actionable code.
Comment: Thanks for pointing that out! I have corrected the code. It should be working now.


Crash when deleting CStringArray*

Question: I'm noob in C++ world and I'm facing a weird behaviour. I use Visual Studio 2010.
The context: I decided to use wxWidget for GUI.
For this, I had to change in my project properties the following settings:
C/C++ > Code Generation > Runtime library > /MTd  (previously it was /MDd)
General > Use of MFC > Use MFC in a shared DLL (previously it was Use MFC in a static library)
Since these changes, all my delete[] on CStringArray* crash my app.
I try to change delete[] by delete but it causes a huge memory leak.
I don't understand why theses changes in project settings generate this difference of behaviour.
EDIT:
The output message is:

HEAP[xxx.exe]: Invalid address specified to RtlValidateHeap( 002B0000,
  002BDE54 ) Windows has triggered a breakpoint in xxx.exe.
This may be due to a corruption of the heap, which indicates a bug in
  xxx.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while xxx.exe has focus.

I have read that:

The CRT libraries use weak external linkage for the new, delete, and
  DllMain functions. The MFC libraries also contain new, delete, and
  DllMain functions. These functions require the MFC libraries to be
  linked before the CRT library is linked.

So I tried to add in Properties> Configuration Properties> Linker > Input > Ignore Specific Default libraries: nafxcwd.lib;libcmtd.lib;
no changes.
In the call stack, I see that it's CStringArray::vector deleting destructor that is invoked.
Comment: @Groco: if you create `CStringArray` that way, you allocate a single object. Destroying it with `delete[]` is incorrect.
Comment: `CStringArray* m_ArrayResult = new CStringArray();` I already tried to change `delete[]` by `delete` but it leads me to huge memory leaks... For the AFXDLL, how can I check if it's correctly included?
Comment: Did you execute a "new" on the CStringArray to create it on the heap?
Comment: Yes, I do. In "/MDd mode", all work flawlessly, no memory leaks, no crash...
Comment: Where does the code crash? And, are you including [AFXDLL](http://msdn.microsoft.com/en-us/library/6f20edzb(v=vs.100).aspx) in your build settings?
Comment: can you show us the code how you created `CStringArray*` with your new operator. I suspect it was created as a single object, that needs to be destroyed using `delete`, not `delete[]` as you are doing
Comment: I understand that, but `delete` doesn't work (memory leaks). In `/MDd` mode, I used `delete[]` and it works nice. Before using `delete[]`, I tried `delete` and it caused leaks.
Comment: do you really need to allocate CStringArray on the heap? normally you just have it as an auto member since it is a collection.
Comment: Yes, I need it, it's the returned value of a method I called several times. In fact, I don't want to change my code as it works in /MDd.
Comment: Check your project settings for AFXDLL.
Comment: What do I have to check?
Comment: You mention wxWidgets: Have you made sure you're putting `CString` instances into the CStringArray and not doing something funny to get `wxString` instances?
Comment: Sure, I mentionned wxWidget to explain why am I changing code generation settings.
Answer: So, I give up. I have left to much time on this problem.
I think that there is an underlying issue that spread when I'm deleting a pointer.
I'm gonna try Qt...
Comment: You did not say where you new'ed the pointer and where you deleted it. That matters.
If you new'ed the pointer in an EXE and deleted it in a DLL, with /MT option yo uare dealing with different heaps

Crash when deleting CStringArray*


Meta tags aren't saved with all content types

Question: I use the module Meta Tags for adding meta data to my nodes. And it works like a charm. It's super easy to add meta tages like title, keywords, description,... even our IT-noob marketing team can do so. It's awesome.
However, not all content types seems to be able to save those meta data. I've got 12 content types and 3 of them don't display the meta data. Although I add them like on the other nodes...
Here is the source code of a node without any meta:

And here with meta:

So correct me if I'm wrong, but I don't see any meta data in the first example.
Strange part, all the data is present in the database (table metatag), so all nodes does save the meta data, but for some reason, some content types aren't displaying the meta data.
What could be the cause of this "bug". Could it be something like hiding certain content in the template files since they all have a separate .tpl.php file? Or what other causes are you thinking of?
Answer: There is an issue with the module.
Try the following code in node.tpl.php.
render($content['metatags']);

Alternatively, try with the following code in page.tpl.php.
print render($page['content']['metatags']);

Comment: Ok, great! This helped me a lot! Thanks a million!!


Criar Array de Objetos em java e acessar os objetos diretamente

Question: Então preciso fazer o seguinte tenho uma classe com alguns atributos e metodos, preciso gerar uma array de objetos dessa classe, porem eu queria poder acessa-los diretamente, atualmente o que consegui fazer é joga-los em um arraylist e usar o get(posição) pra atribui-los em uma variavel temporaria para poder acessar seus metodos e atributos.
Classe a qual quero criar um array de objetos
public class BlocoView {
    private MemoriaTextField enderecoMemoria;
    private MemoriaTextField palavras;
    public BlocoView(boolean selected){
        if(selected){
            this.enderecoMemoria = new MemoriaTextField("0", true);
            this.palavras = new MemoriaTextField("???", true);
        }else{
            this.enderecoMemoria = new MemoriaTextField("0", false);
            this.palavras = new MemoriaTextField("???", false);
        }
    }
    public MemoriaTextField getEndereco(){
        return this.enderecoMemoria;
    }
}

Classe que contem o arraylist de objetos da classe acima
public class MemoriaView extends JPanel {
    private ArrayList listadeBlocos;
    public MemoriaView(){
        super();
        this.listadeBlocos = new ArrayList();
        this.listadeBlocos.add(new BlocoView(false));
        this.setLayout(new MigLayout());
        //Aqui que tenho que acessar os atributos ou metodos diretamente
        this.add(this.listadeBlocos.get(0));
    }

}

Ao tentar fazer algo do tipo
this.add(this.listadeBlocos.get(0).getEndereco);

o java nao consegue encontrar o metodo get endereco
Comment: Você não precisa colocar em um objeto temporário. Basta saber a posição e fazer assim. arrayList.get(i).getPropriedade().
Comment: @alleen94 Creio que o problema do OP é que ele não definiu um tipo para a lista, usando Generics, por isso ele só vê um Object ao dar o get.
Comment: o que você quer dizer com `queria poder acessa-los diretamente`?
Comment: @alleen94 se você é capaz de atribuir a uma variável do tipo da classe com certeza você pode acessar diretamente tb, conforme o adelmo00 falou. Você deve estar cometendo algum outro erro no caminho, se não conseguir resolver poste o código que está com dificuldade.
Comment: @Math acessar do modo que o adelmo00 mostrou
Comment: @adelmo00 ja tentei assim e não funciona, não consigo acessar nem os atributos e nem os metodos
Comment: @utluiz Exatamente cara defini agora o ArrayList como ArrayList funcionou certinho obrigado a todos
Comment: @alleen94 Vou acrescentar uma resposta, para não ficar apenas como comentário.
Comment: beleza @utluiz ja seleciono ela como aceita
Answer: Para fazer isso você deve definir o tipo genérico do ArrayList, assim:
public class MemoriaView extends JPanel {
    private ArrayList<BlocoView> listadeBlocos;
    public MemoriaView(){
        super();
        this.listadeBlocos = new ArrayList<BlocoView>();
        this.listadeBlocos.add(new BlocoView(false));
        this.setLayout(new MigLayout());
        //Aqui que tenho que acessar os atributos ou metodos diretamente
        this.add(this.listadeBlocos.get(0));
    }

}

Sem isso, o tipo da lista fica como Object e, mesmo a instância sendo tipo que você passou, não terá um acesso aos métodos diretamente.
Outra alternativa é fazer um cast, assim:
BlocoView bloco = (BlocoView) this.listadeBlocos.get(0);
this.add(bloco.getEndereco());


How do I declare multiple maintainers in my Dockerfile?

Question: How can I best indicate that there are multiple authors/maintainers of a docker image built using a Dockerfile? If I include multiple separate MAINTAINER commands, only the last one seems to take effect.
MAINTAINER Me Myself "firstname.lastname@example.com"
MAINTAINER My Colleague "firstname.lastname@example.com"

Only mycolleague shows up in the output of docker inspect.
Should I use a comma delimited list in a single MAINTAINER line? Is wanting to list two maintainers a boondoggle and I should just armwrestle my colleague to see whose email we put in the file?
Comment: I'm looking for a solution as well. Maybe it's just okay to have multiple maintainers in one line?
Comment: Probably, yeah. If `MAINTAINER` is an arbitrary string (or series of whitespace delimited tokens) then I would imagine it fine to put multiple people on one line. I'm just not sure whether there's a common convention for it.
Answer: You can only specify one MAINTAINER instruction in a Dockerfile.
Furthermore, MAINTAINER will be deprecated in the upcoming 1.13.0 release, see deprecations and this pull request.
The recommended solution is to use LABEL  instead, e.g.
LABEL authors="first author,second author"

Labels have a key=value syntax. This means you cannot assign the same label more than once and you cannot assign multiple values to a given label. But you can combine multiple values into one with a syntax of your choice as illustrated in the example..
Comment: [The current recommendation](https://docs.docker.com/engine/reference/builder/#maintainer-deprecated) is to use `"org.opencontainers.image.authors"` as the **key**, since this a [more widely recognized metadata key](https://github.com/opencontainers/image-spec/blob/main/annotations.md). It is still freeform string **value**.
Comment: Good question, @amacleod. It seems that exactly `org.opencontainers.image.authors` should be used as the key, since it is specified in the OCI specs, see the referred [OCI image-spec annotations](https://github.com/opencontainers/image-spec/blob/main/annotations.md):
"The prefix `org.opencontainers` is reserved for keys defined in Open Container Initiative (OCI) specifications and MUST NOT be used by other specifications and extensions"
Comment: Do you know whether `org.opencontainers.image.authors` should always be the key, or should the first few parts be my own organization's reversed domain, like `com.example.image.authors`?


Assumption in Prototype Based Classification

Question: A very simple model:

Given N labeled training examples from two classes (say red and green), we use the distance from means approach to learning a classifier - that classifies new points as either red or green. The idea is to predict the class that has a closer mean.

Mathematically, it can be shown that this model learns a hyperplane decision boundary.
One of my university's course's lecture content remarks that -
"This simple approach, if using Euclidean distances, can only learn linear decision boundaries.
A reason: The basic approach implicitly assumes that classes are roughly spherical and equi-sized."
What is the reason and intuition behind the classes being roughly spherical and equi-sized? Could someone please explain? Thanks a lot!
Comment: The claim, as you write it, is: "The distance from means approach can only learn linear boundaries *because* it assumes sphericity and equal sizes." This claim is false. Yes, it can only learn linear boundaries, and spherical equally-sized groups are better. But these are two independent claims. So: are you interested in the two separate claims? (If so, I would recommend you ask two separate questions. One question per post is a better fit for us here.)
Comment: No, I'm not interested in two separate claims - I'm only interested in knowing why spherically "equally sized" groups are better. Why is that? @StephanKolassa
Answer: Spherical groups are better because distance-to-means relies only on group means to classify new data, and group means (i.e., centers) are good summaries of groups only for spherical groups. For instance, suppose your two groups are concentric annuli (as in this answer). Since they are concentric, their means are identical. Of course, in a real world situation, the means will differ slightly, but which group a new data point will be assigned to will be very variable.
Alternatively, suppose your two groups are ellipsoids. Then points far out on the major axis will have a much higher impact on the group means (and therefore on the classifications for new data points) than points far out on the minor axis.
Equal sizes are good because the impact of each training data point will be disparate if group sizes are unequal. If one of your groups is very small, then a change in a single data point of that group can move the group's mean a lot, and therefore change the classification boundary a lot. Higher variance means higher error.
I very much recommend the thread on How to understand the drawbacks of K-means, which I took the link above from. Many of the problematic examples there straightforwardly suggest cases where distance-to-means also has problems.
Comment: You will typically not *change* the training data. But your training data will usually be a sample from an underlying population. And then the variance comes from whether you include one observation in your sample rather than another. You might be lucky and use a training sample that gives you a good model. Or you might be unlucky and happen to use a sample that gives you a bad model. This dependence on luck is the variance in your model, and therefore on your classifications of new data. Variance translates directly into higher error.
Comment: And that is the impact I was discussing. And the error is why we are interested in it.
Comment: *If one of your groups is very small, then a **change in a single data point** of that group can move the group's mean a lot.* What is meant by change in a data point? Why would I change the training data? Please clarify!
Comment: Also, what is meant by the disparate impact of data points, if group sizes differ largely?
*Impact on what?* and *Why is it something we consider?*
Comment: Thanks a lot - makes sense now!


Passar variaveis na URL do getjson XDK Intel

Question: Comecei a estudar javascipt agora e preciso passar duas variáveis para um método de soma com getJSON e nao sei como fazer. Criei meu app com o XDK Intel, o server criei com delphi xe2 utilizando datasnap.
Tentei destas duas formas e nao consegui.
//alert('acessou a rotina');
$.get(urlSoma).then(function(data){

    alert(data);
    //$("#iptResult").val();
    //$("#iptResult").val(data.result);

}).fail(function(jqXHR,status,error){
    alert(error);
});

$.ajax({
        url: urlSoma,
        type: 'GET',
        dataType: 'json',
        data: {x: pX},
        success: function(json){
            alerta('fungo');
        },
        error: function(json){
            alert('erro');
        }
    });
});

Alguem pode me auxiliar?
Answer: Olá,
Passe o parâmetros com /
Exemplo
$.get('suaUrl/paramentro1/paramentro2', suaFuncaoRetorno);
function suaFuncaoRetorno(itens){
  console.log(itens);
}

Answer: Olá,
Esqueça o $.get. Só  $.AJAX já resolve seu problema.
Veja como é a chamada a sua rotina feita em delphi, mas eu creio que não seja diferente das outras formas.
Se fosse em php urlSoma='somanumeros.php', em delphi eu não sei como fica.
p1 e p2 são os numeros que vc deseja somar.
json é o retorno. Depende da sua função no server-side.
$.ajax({
        url: urlSoma,
        type: 'GET',
        dataType: 'json',
        data: {p1: numero1,
               p2: numero2},
        success: function(json){
            alerta('fungo');
        },
        error: function(json){
            alert('erro');
        }
    });
})

;


Annoying ssh workflow

Question: I've been using ssh for svn for a while now, but suddenly this strange thing happen
First, running svn up would just do, wonderfully.
Later, running svn up prompted me for a password, the suggested solution was to do sudo ssh-add ~/.ssh/* and then executing the update. Not very painful, but not so fun either.
Now, even that won't work. It says:
Could not open a connection to your authentication agent.
So the actual way of making this work is:
exec ssh-agent bash
sudo ssh-add ~/.ssh/*
svn up
Is there a way I can avoid doing all that stuff ?
Thanks a lot
Answer: Just put this line into your .profile:
eval `ssh-agent -s`

And it'll be taken care of automatically whenever you open a shell.
You could put the ssh-add command in there too, but I recommend doing that manually so that you can keep your private key passphrase-encrypted.
Comment: mm this doesn't work, still asks for the passphrase (which is empty) and after pressing enter it asks for a password :(
Comment: Just to verify you followed my instructions correctly: are you seeing an "Agent PID 12345" message when you start the shell, and does running 'env' show SSH_AUTH_SOCK and SSH_AGENT_PID set?  If you aren't, try moving the ssh-agent line from .profile to .bashrc: maybe your terminal isn't a login shell.
Comment: I put that on my .profile and I'm seeing the Agent PID ### stuff. I have both variables you mention defined.
Comment: Then check the output of 'ssh-add -l' and make sure the relevant key is loaded into the agent.  If it is, and this approach doesn't work while the commands you listed in your question do, then I have no idea what to tell you.
Comment: Why, by the way, are you running the ssh-add command under sudo?  Is there some reason that those keys aren't readable by the user you're running svn under?
Comment: @dfranke ssh-add -l says: "the agent has no identities"
Comment: Which of the alternatives did you choose w.r.t. "You could put the ssh-add command in there too, but I recommend doing that manually so that you can keep your private key passphrase-encrypted"?  And what was the output when that command ran?
Comment: Oh, it's working now. I thought that I didn't have to do the `ssh-add` thing again. Sorry for the misunderstanding and thanks a lot for the solution
Answer: You can also run svn through apache.  That way you will only need to do the ssh-agent/ssh-add prior to starting apache.
You can then access svn through https.

Annoying ssh workflow


Get polar coordinates from origin

Question: In a polar coordinates system I have two point $P_1$ and $P_2$. For $P_1$ I know it coordinates from the origin ($O$) which are $(d_1,\alpha_1)$.
For $P_2$ I also know it's coordinates, $(d_2,\alpha_2)$, but it's from $P_1$. I want the coordinate of $P_2$ from the origin, $(D,A)$.

I've found some post about translation in polar coordinates.
The first one gives those equations:
$$d_2^2 = d_1^2 + D^2 + 2d_1D \cos(A-\alpha_1)~~~~~~~~~~~~~~~~(1)$$
and
$$\sin(\alpha_2) = \frac{D}{d_2} \sin(A-\alpha_1)~~~~~~~~~~~~~~~~(2)$$
The second one gives those equations (I guessed some parts because he gave it with value instead of variables names):
$$(1)$$
and
$$ \tan(\alpha_2) = \frac{D \sin(A-\alpha_1)}{D \cos(A-\alpha_1)-d_1}~~~~~~~~~~~~~~~~(3)$$

My problem is, from all those equations, I don't know how to get $D$ and $A$.
EDIT:
I have to do it several times, so I'd like a solution with a small computational cost (lower than use the cartesian coordinates)
Answer: Consider the following right triangle $\triangle{P_1 Q P_2}$

The sides of the triangle are known $$ \begin{aligned} x & = d_2 \cos \alpha_2 \\ y & = d_2 \sin \alpha_2 \end{aligned} $$
Now you can find the properties of the larger triangle $\triangle{O Q P_2}$
$$\begin{aligned}
 D &= \sqrt{ (d_1+x)^2 + y^2 } \\
 A &= \alpha_1 + \tan^{-1} \left( \frac{y}{x+d_1} \right)
\end{aligned} $$
Comment: The solution for $D$ is essentially a proof of the Law of Cosines.
Comment: I like your solution. I just let it open for somes days to see if someone else has an other solution. Thanks
Comment: I have a personal axiom, that find the _right_ triangle in any problem and the solution becomes trivial.
Answer: In the linked questions, the distances and directions from the origin of two points are known and we want the distance and direction between them.
That is, in terms of your figure,
$d_1, \alpha_1, D,$ and $A$ are known while $d_2$ and $\alpha_2$ are unknown.
Your problem is set differently because you already know the distance and direction between the two points that are not the origin. What you are missing is the distance and direction from the origin to one of those points.
But by understanding a little bit about why the other solutions work, you can reapply them to your different problem.
The Law of Cosines relates the length of one side of a triangle (on one side of the equation) to the angle opposite that side and to the lengths of the other two sides (on the other side of the equation).
The Law of Sines relates the ratio of a side and the angle opposite it to the ratio of another side and the angle opposite it. This is a multipurpose formula, because if you know two ratios are equal, $p/q = u/v,$ and you know any three of the quantities in the ratios, you can easily solve for the fourth quantity.
The Law of Cosines in general can be written
$$ c^2 = a^2 + b^2 - 2ab \cos \theta, $$
where $a,$ $b,$ and $c$ are lengths of sides of a triangle and $\theta$ is the interior angle opposite $c.$
Since $D$ is your unknown side, you want to put $D$ for $c.$
Therefore you put $d_1$ and $d_2$ for $a$ and $b.$
Now the trickiest part of the application is that the Law of Cosines deals with the interior angle opposite the unknown side, but you have the exterior angle $\alpha_2.$
So just be aware that if $\theta$ is the interior angle, then
$\theta = \pi - \alpha_2$ and $\cos\theta =  - \cos\alpha_2.$
So when you make all these substitutions into the Law of Cosines you get
$$ D^2 = d_1^2 + d_2^2 + 2 d_1 d_2 \cos \alpha_2. $$
Since $D$ is positive (assuming you want the usual polar coordinates, with positive radius), you can take the square root to solve for it without using a $\pm$ sign:
$$ D = \sqrt{d_1^2 + d_2^2 + 2 d_1 d_2 \cos \alpha_2}. $$
This works in every case, even if $\alpha_2$ obtuse or if the direction of the angle is counterclockwise instead of clockwise (including the case where you measure $\alpha_2$ in such a way that it is greater than $180$ degrees).
The Law of Sines says
$$ \frac{\sin P}{p} = \frac{\sin Q}{q} $$
where $P$ and $Q$ are angles of a triangle and $p$ and $q$ are the lengths of the sides opposite $P$ and $Q$ respectively.
Note that the sine of an exterior angle is equal to the sine of the interior angle, so you can use interior or exterior angles interchangeably in this formula.
Therefore you can write
$$ \frac{\sin (A - \alpha_1)}{d_2} = \frac{\sin \alpha_2}{D}. $$
Multiply both sides by $d_2,$ take the inverse sine of both sides, and add $\alpha_1$, and the result is
$$ A = \alpha_1 + \arcsin\left(\frac{d_2\sin \alpha_2}{D}\right). $$
Now you have only one thing to watch out for, which is that this solution for $A$ assumed that the angle $A - \alpha_1$ was acute.
That is a drawback to the first solution you found.
You can use Law of Cosines on $A - \alpha_1$ to disambiguate whether it is acute or obtuse, but now you have additional calculations to perform.
The second solution is better but can be improved further for use in a program by using the $\mathrm{atan2}$ function.
The idea is that you construct a right triangle and solve for the angle;
in your case you can take $d_1 + d_2 \cos\alpha_2$ as one side of the triangle and $d_2\sin\alpha_2$ as the other side.
Then
$$ A = \alpha_1 + \mathrm{atan2}(d_2\sin\alpha_2, d_1 + d_2 \cos\alpha_2). $$
This works even if $\alpha_2$ is obtuse or greater than $180$ degrees,
as long as you measure all the angles $\alpha_1,$ $\alpha_2,$ and $A$ in the same direction, for example clockwise as in your figure.
None of these formulas particularly cares which quadrant of the plane any of the points are in or which points are "above" which other points.
Comment: I'm not a mathetician, I'm just a computer engineer trying to do some math stuff, that why I was not able to do the transformation. :s Thanks a lot for your explenations :) And about the sign of $D$. my figure is an example. If $P_2$ is below $P_1$ or $O$, how can I know it ($D<0$ or $A<\pi$, or something else)?
Comment: In that light the second solution you found has a better idea. I have added this to the answer, but I use $\mathrm{atan2}$ rather than $\arctan$ because $\arctan$ does not give you the correct angle when the correct angle would be obtuse.
Comment: I can have positive and negative angles. But positive angles are always clockwise, and negative always conter-clockwise. Is it what you mean? As a next step of computation I use $P_2$ as the center of transformation for the rest of the scene. And after a while, all the scene is upside-down, because equations from linked questions don't care about the sign. Please, could you give a little more info about the way you got your last equation, like this, as an exercice, I could try to find the good equation
Comment: So in your system an angle of $-\theta$ is in the opposite direction from the angle $\theta.$ That is what I would consider "all angles measured in the same direction", so you should have no problem there. I have not had time to do a full writeup of the last equation yet; I think you would probably want to see at least three separate cases for positive angles and also consider negative angles.
Comment: Anyway, I found it ($\alpha_2 = \mathrm{atan2}(D\sin(A-\alpha_1), D\cos(A-\alpha_1)-d_1)-\alpha_1$, if anyone need it). Thanks again for your post ! ;)
Answer: You could transform $(d_1, \alpha_1)$ and $(d_2, \alpha_2)$ into cartesian coordinates, add them to get the cartesian coordinates of $P_2$ and then transform them back into polar coordinates.
Comment: I have to do several times, so I'd like a way with a small computational cost. I forgot to mention it in my post. But thanks

Get polar coordinates from origin


How to knockoutjs nested template

Question: I'm trying to figure out why this nested template doesn't display anything. I have 2 classes Foo/Bar, the ViewModel has an observable array of Foo,  and Foo have a collection of Bar
At the moment all I see is the Foo item
ie

someitem

instead of

someitem

subitem

List item

    var Foo = function () {

    var self = this;
    self.Name = ko.observable('someitem');

    self.bars = ko.observableArray([new Bar()]);

    self.HasChildren = ko.observable(false);

    self.addBar = function () {
        self.bars.push(new Bar());
    };
    self.removeBar = function (param) {
        self.bars.remove(param);
    };
    self.bars.push(new Bar());

    }
    var Bar = function () {

    var self = this;
    self.Name = ko.observable('subitem');

    }

    var ViewModel = function () {

    var self = this;
    self.foos = ko.observableArray([new Foo()]);
    self.addFoo = function () {
        self.foos.push(new Foo());
      };
      self.removeFoo = function (param) {
        self.foos.remove(param);
       };

    }

    $.ajax({
    url: '@Url.Action("AddFoos")',
    type: 'GET',
    async: false,
    contentType: 'application/json',
     success: function (result) {

        ko.applyBindings(new ViewModel(result));

      }
    });

Thanks in advance!
Answer: Knockout has an issue binding text in li's for some reason. I have run into this issue before. It ends up overwriting everything else that should go on the node, which in your case is an inner ul. You can fix this with a span or any other text element like this:

Here is your code in a working fiddle.
A small note, your ajax call is going to fail, since your ViewModel doesn't have a paramater to take the result.
Also, calling applyBindings in a function like that is bad, since if it gets called twice you will cause errors. If you call it once, updates made to the viewmodel later will automatically get sent to the UI. That's sort of Knockout's thing =)
Update:
Upon further consideration, this is probably not specific to li nodes. It is probably that the text binding works by overwriting the contents of any node it is bound to, so that any contents other than the text will also be overwritten. It is probably intentional.
Comment: from Knockout source : `text` binding uses `ko.util.setTextContent()` which has this comment `We need there to be exactly one child: a text node. If there are no children, more than one, or if it's not a text node, we'll clear everything and create a single text node.`

How to knockoutjs nested template


Select ambiguous view that is not displayed

Question: In my espresso test, I want to select a view by id. The view is below the fold, so I need to scrollTo() it. This view shares its id with another view which is hidden.
This gives ambiguous view error:
onView(withId(textViewId)).perform(scrollTo(), myAction);

So does:
onView(allOf(ViewMatchers.isEnabled(), withId(textViewId)))
    .perform(scrollTo(), myAction);

This gives no matching view exception:
onView(allOf(ViewMatchers.isDisplayed(), withId(textViewId)))
    .perform(scrollTo(), myAction);

How can I uniquely select the view I want?
Answer: I solved this by identifying a unique ancestor view.
onView(allOf(isDescendantOfA(withId(R.id.someParent)), withId(textViewId)))
    .perform(scrollTo(), myAction);


Generate relationship data

Question: I have a set of xml files representing rules manager rules. There are several elements that map to tables or table-attribute pairs.
I would like to discover all the elements that affect intersecting sets of tables or table-attributes.
I can work in java or possibly python, or command line Windows/Mac. Can someone suggests a tool or approach? Thanks so much!
Comment: You can use Jackson to deserialize XML to java class and write business logic around it here is the example: https://www.baeldung.com/jackson-xml-serialization-and-deserialization
Comment: This is good - however I"ll repost another question as this has made it a bit clearer to me that using a language especially java is a bit more than I want to do right now since I just want to try various samples and the command line is looking like a better fit (starlet or Powershell). Sorry to seem idiotic but I can't see a checkmark to accept this answer even though I'm the author.
Answer: Experiment with xmlStarlet
Try Saxon for cross file xpath queries
Both can work from the command line

Generate relationship data


File upload with ajax

Question: Is there any example how to set up form element with type file to upload it via AJAX. I want to be same as field image in node type article.
thx
Answer: Maybe this will be helpful (in a custom module):
function testmodule_forma($form, & $form_state) {
    $form['im-container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['image_file'] = array(
        '#type' => 'file',
    );

    $form['upload'] = array(
        '#type' => 'submit',
        '#value' => 'upload',
        '#submit' => array('upload_image'),
        '#ajax' => array(
            'callback' => 'upload_image',
            'wrapper' => 'im-area',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );
    return $form;
}

function upload_image($form, $form_state) {

    $file = file_save_upload('image_file', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", FILE_EXISTS_REPLACE);
    if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
        $form['im-container'] = array(
            '#title' => t('Preview:'),
            '#prefix' => '
',
            '#markup' => ' filename.
            '" height="250" width="250" />',
            '#suffix' => '
',
        );
    } else {
        drupal_set_message('No file uploaded.');
    }

    return $form['im-container'];
}

Comment: thx @Chapabu, this is great
Answer: If you are using D7, Why you are writting messy code to achieve this task?
In D7 form API we have type = managed_file which uploads file using ajax.
Try this example:
$form['image'] = array(
            '#type' => 'managed_file',
            '#title' => t('Upload Image'),
            '#default_value' => '',
            '#required' => TRUE,
            '#description' => t("Upload Image description"),
        );

Comment: Will it work for multiple file upload?
Comment: Not in any easy way, it seems

File upload with ajax


Representação little endian do menor para o maior em uma CPU Intel?

Question: Sobre endianess do meu PC Intel, ocorre o seguinte:
int i = 0X23456789;
unsigned char* a = (char*)&i;

for(int i = 0;i < 4;++i)
{
   printf("%.2X\n",a[i]);
}

Output:
89
67
45
23

Porém:
int i = 0X23456789;
unsigned char* a = (char*)&i;
printf("%.2X\n%.2X\n%.2X\n%.2X",*a,*a++,*a++,*a++);

Output:
23
45
67
89

Qual a razão do printf se comportar de diferentes maneiras nas duas situações acima?
Comment: A dúvida é boa, mas para entender seu raciocínio e elaborar em cima, como concluiu que a questão é realmente de endianness? Já considerou outras possibilidades?
Comment: Robson sim, levantei o questionamento como uma forma de adiantar o assunto, e fazer uma provocação a pensar (não só para você, mas para quem fosse responder já que eu não estava com tempo de elaborar mais), isso foi antes de ter a resposta do colega @Inkeliz que vai direto ao problema de fato. Sobre endianness, a melhor coisa que faz de fato é ler direto da memória individualmente se um dia precisar determinar (mas isso só como experiência, normalmente os próprios compiladores já tem algum built-in ou define para te informar isso, se um dia precisar de um código condicional multiplataforma).
Comment: O comportamento dos dois códigos do autor não tem relação com endianness (a palavra está lá só por uma conclusão inicial do autor que já foi "desmistificada"). Seja qual for a plataforma, o loop e o printf avulso (feitos na mesma ordem sequencial) darão o mesmo output. Obviamente que o output vai ser diferente comparando duas plataformas distintas, mas isso não foi a causa do fenômeno observado, até porque o autor disse qual era o target no título, e rodou os dois testes na plataforma especificada.
Comment: Os dois são iguais, o problema é a ordem dos parametros. O ultimo `&a++` será executado antes do terceiro, antes do segundo e então o primeiro `*a`.  Quebre isso em vários `printf`, como `    printf("%.2X\n",*a++);    printf("%.2X\n",*a++);    printf("%.2X\n",*a++);    printf("%.2X\n",*a);` e vai ver que o resultado é igual ao do `for`.
Comment: @Bacco estou começando a estudar endianess, só queria saber na prática como identificar a ordem em que os bytes são lidos e escritos em minha máquina.
Comment: @Bacco endianess sempre vai fazer diferença porque os bytes serão apresentados em outra ordem, ainda que se use por exemplo o mesmo gcc e as mesmas opções, mudando de arquitetura.
Comment: O loop vai receber os valores em outra ordem, para o mesmo código, @Inkeliz não considerou isso ao escrever, indo "direto ao problema de fato"
Comment: Acho que a pergunta misturou dois assuntos: *endianess* e ordem em que os argumentos são avaliados. Se a questão era sobre o *endianess*, deveria ter como [mcve] só o primeiro código dando resultados diferentes em máquinas diferentes, por exemplo. Se a questão era a ordem, poderia trocar para algo como o sugerido abaixo (`int i = 0; printf("%d, %d", i, i++);`). Da forma que está, um acaba sendo ruído pro outro, tanto que cada resposta escolheu focar em um deles. Minha sugestão seria separar em duas perguntas, assim o site fica mais organizado...
Comment: ... Lembrando que o objetivo do site é ser uma base de conhecimento sobre programação, com perguntas **objetivas e focadas** em um único assunto. Misturar 2 assuntos distintos vai contra esse objetivo
Answer: O problema não tem relação com o endianness, e sim com a ordem das operações na função.
Para visualizar melhor, troque para:
int i = 0X23456789;
unsigned char* a = (char*)&i;
printf("%.2X\n",*a++);
printf("%.2X\n",*a++);
printf("%.2X\n",*a++);
printf("%.2X\n",*a);

Isso resultará em:
89
67
45
23

Exatamente a mesma ordem do for.

Então por que o seu printf dá outro resultado? Porque a ordem as operações importam e compilador também parece poder alterar. Segundo a resposta do SO (em inglês), a ordem não é determinística, e cada compilador pode dar seus pulos.
printf("%.2X\n%.2X\n%.2X\n%.2X",*a,*a++,*a++,*a++);

O que você acha é que feito primeiro? O que você quer é fazer: *a e depois *a++. Mas será que essa é a ordem que o compilador vai fazer? Recomendo que veja no https://godbolt.org/z/4P1aPKqKx. Pode passar o mouse por cima para ver melhor cada coisa e pode usar vários compiladores diferentes.
Alguns compiladores, como CLang e ICX, dão alguns warnings:
<source>:6:38: warning: unsequenced modification and access to 'a' [-Wunsequenced]
printf("%.2X\n%.2X\n%.2X\n%.2X",*a,*a++,*a++,*a++);
                                 ~   ^

Se você compilar usando ICX (Intel Compiler), a ordem muda:
89
89
67
45

Já o compilador ICC, a ordem é diferente:
23
89
67
45

Compilando com Zig CC, a ordem também é igual ao do ICX:
89
89
67
45

Com o GCC, é a ordem que mencionou:
23
45
67
89

Mas, para simplicar, considere o seguinte código:
int main() {
    int i = 0;
    printf("%d, %d", i, i++);
    return 0;
}

O que você acha que é o resultado? 0, 1 ou 1, 0 ou 0, 0? Então, isso depende do compilador, não do endianness.
Comment: @arfneto mas a ordem dos dois casos (com o `for` ou com o `++`) serão iguais.
Comment: Esse é ponto. Talvez eu pudesse deixar isso mais claro a resposta. O que quis dizer com "não tem relação com endiness" é o comportamento diferente entre o `for` e `++`, que é a pergunta principal: "Qual a razão do printf se comportar de diferentes maneiras nas duas situações acima?". O endianness terá relação com o CPU, isso é claro, mas os dois métodos terão o mesmo resultado entre si.
Comment: Obrigado pela resposta. Me ajudou a perceber que preciso entender melhor endianess.
Comment: **Depende também de endianess...** O mesmo compilador numa plataforma BigEndian vai te dar um resultado diferente porque os bytes virão em outra ordem. Pense nisso
Comment: sim. o conteúdo é que será diferente.
Comment: O memso compilador, duas plataformas. Os bytes serão apresentados em outra ordem
Answer: printf("%.2X\n%.2X\n%.2X\n%.2X",*a,*a++,*a++,*a++);

Essa chamada a printf() tem um comportamento indefinido --- UB. Não há garantia sobre a ordem da avaliação dos incrementos ++ e dos ponteiros resultantes. Veja o código gerado usando a opção de seu compilador. -S no caso do gcc, /Fa no MSVC.
Evite esse tipo de construção a todo custo.
No fundo qualquer operação dentro da lista de argumentos de uma função é um risco porque você pode remover  a chamada e esquecer de repor a operação. Ou copiar a chamada e fazer mais vezes a mesma coisa...
Cada *a++ vai ter o resultado esperado: o valor apontado por a. E depois o ponteiro a avança sizeof(*a).  Só que hora de chamar printf() a ordem em que isso é avaliado não é definida pela norma e pode acontecer qualquer coisa porque tem 3 na mesma lista de argumentos. Vai avaliar da direita para a esquerda? Ou da esquerda para a direita? E se o valor de *a for calculado antes e usado 3x para otimizar, e o ponteiro incrementado 3X de modo independente? printf() não vai ver esses resultados e vai mostrar 3x o mesmo valor. Mas na linha seguinte estará tudo certo.
E um mesmo compilador rodando em uma arquitetura Big Endian vai pegar os valores na memória em uma ordem e em outra em uma arquitetura Little Endian levando a resultados diferentes. Isso --- endianess --- é bem definido, mas somado ao descrito acima leva a mais confusão.
Endianess e um EXEMPLO em C
Um modo comum de testar se a máquina em que o programa está rodando usa Big-Endian ou Little-Endian é considerar um int valendo 1 e ver se o primeiro byte vale 1. O clássico
int little_endian()
{
    int um = 1;
    // redefine &um como char* para ver se
    // o primeiro byte vale 1
    return *((char*)(&um)) == 1;
}

O programa abaixo mostra os valores para um int de 32 bits com um único byte 1 e os outros 0. Usa uma union para mostrar os valores como estão na memória e serve para ilustrar isso. E chama a tal função do exemplo acima.
saída do exemplo

    ==> Valor do int (32bits): 1

        Bytes 0/1/2/3: 0x01 0x00  0x00 0x00

    ==> Valor do int (32bits): 256

        Bytes 0/1/2/3: 0x00 0x01  0x00 0x00

    ==> Valor do int (32bits): 65536

        Bytes 0/1/2/3: 0x00 0x00  0x01 0x00

    ==> Valor do int (32bits): 16777216

        Bytes 0/1/2/3: 0x00 0x00  0x00 0x01

        Little Endian? SIM

o código do exemplo
#include <stdint.h>
#include <stdio.h>

int little_endian();

int main(void)
{
    union
    {
        uint32_t d_word;
        uint8_t  byte[4];
    }   teste;

    int val[4] = {1, 256, 65536, 16777216};

    for (int n=0; n < sizeof(val) / sizeof(val[0]); n += 1)
    {
        teste.d_word = val[n];
        printf("\n\n\
    ==> Valor do int (32bits): %d\n\n\
        Bytes 0/1/2/3: 0x%02X 0x%02X  0x%02X 0x%02X\n",
        teste.d_word, teste.byte[0], teste.byte[1],
        teste.byte[2], teste.byte[3]);
    }

    const char* sn[2] = {"NAO","SIM"};
    printf("\n\n\tLittle Endian? %s\n", sn[little_endian()]);

    return 0;
}

int little_endian()
{
    int um = 1;
    // redefine &um como char para ver se o primeiro byte
    // vale 1
    return *((char*)(&um)) == 1;
}

// https://pt.stackoverflow.com/questions/555733/representa
//%c3%a7%c3%a3o-litle-endian-do-menor-para-o-maior-em-uma-
//  cpu-intel

Comment: Esse é o início de minha responsta, @Robson _"Essa chamada a printf() tem um comportamento indefinido --- UB. Não há garantia sobre a ordem da avaliação dos incrementos e dos ponteiros"_  O exemplo que te mostrei indica como você poderia ter feito em seu programa para verificar isso.
Comment: E imagino que tenha entendido que se rodar numa máquina Big Endian com o mesmo compilador o resultado vai ser diferente então sua afirmação e a da resposta que citou não procedem: tem também a ver com litttle/big endian a saída. O programa deveria servir para você entender essa questão de ordem do byte mais significativo e se eu não consegui preciso mudar algo lá. Notou os 4 int com 1 byte 1 e os outros 0 ?
Comment: Então minha resposta, que explica a razão do problema e tem um programa em C com a saída acompanhando não é útil? **Preciso melhorar, está claro**
Comment: Dois votos como inútil hoje. Pena que não se deram oa trabalho de explicar como eu poderia tornar a resposta melhor. Nada como o anonimato
Comment: Obrigado por sua resposta. Sim, o printf que escrevi tem como resultado um comportamento indefinido, e eu devo evitar tal prática de programação. Essa foi sua contribuição e te agreço por isso;não farei mais tal coisa. Porém, além do que tu escreveu Inkeliz demonstrou que o output do meu código não tem nada a ver com endianess, mas como cada compilador determina a ordem de operação do printf que escrevi. Como percebi que não entendo de endianess, não comentarei sobre o programa em C que disponibilizou. Mas, aqui fica meu muito obrigado a todas respostas.
Comment: Realmente fiquei com essa compreensão. Se é o compilador que determina a forma de se ler os bytes com printf, então é um problemão!!! Realmente, a sua resposta além de demonstrar que é uma má prática a forma como eu tratei a ordem de avaliação dos incrementos, ainda me trouxe um código que possibilita o que quero - que é descobrir o endianess da minha máquina. Esclarecendo o endianess da minha máquina consigo entender porque lendo sob matriz tenho uma ordem, e lendo sob ponteiros tenho outra ordem.
Comment: oh... o que o compilador é livre para determinar é a ordem de avaliação de coisas como os  operadores ++ dentro da lista de argumentos do printf(). O endianess é determinado pela arquitetura e determina a ordem dos bytes dentro de uma word na memória, se começa a carga pelo primeiro ou pelo segundo byte e por isso escrevi o programa para mostrar o byte `0x01` _"navegando"_ na DWORD.
Answer: Em uma arquitetura x86 (intel, amd...), o número 0X23456789 é armazenado assim: 89 67 34 23.
x86 é uma arquitetura chamada "little-endian": https://pt.wikipedia.org/wiki/Extremidade_(ordena%C3%A7%C3%A3o)
Ao usar uma notação de matriz, você lê os bytes na ordem da memória.
Você também pode ler este array como uma string:
        union u_u {
            int i;
            unsigned char c[4];
        } u;
        u.i = 0X23456789;
        // Stored in memory on a x86 architecture like that : 89 67 34 23

        for(int i = 0;i < 4;++i) {
            printf("%.2X\n",u.c[i]);
        }

Quando você usa uma notação de ponteiro, você a lê como o processador, na ordem inversa: https://pt.wikipedia.org/wiki/Extremidade_(ordena%C3%A7%C3%A3o)#Transfer%C3%AAncia_de_dados_entre_processador_e_mem%C3%B3ria
Comment: Nesse sentido, qual seria mais eficiente(ou não tem importância no que compreende otimização)?Lendo em notação de matriz há alguma perda em comparação a ler como o processador lê( iteração de ponteiros)?
Comment: Na minha opinião, acho que a notação de iteração de ponteiro é mais rápida, mas isso não deve ser muito. Eu prefiro a notação de índice. É mais legível. O uso de uma notação em vez de outra pode ser escolhido dependendo do que você deseja fazer com ela posteriormente.
Comment: obrigado pela opinião.


Diminuir valor de campo span com preg_replace

Question: Estou tentando alterar todos os valores dos campos que contém span class.
Exemplo o site está assim:

   1/2
   1.50
   -200
   1.50

   <input class="betCode" type="hidden" value="0]SK@82285689@314222649@NB*1~2*0*-1*0*0]CPN:0" />
   <input class="originalBetCode" type="hidden" value="0]SK@82285689@314222649@NB*1~2*0*-1*0*0]CPN:0" />

Qual a forma mais fácil pra mim recuperar os valores 1.50, 200, 1.50 e diminuir 20% do valor original utilizando da função preg_replace?
Comment: Queres fazer isso com PHP ou JS? se não sabes então pf explica melhor o que queres fazer... que funcionalidade.
Comment: *1/2* entra? *200* entra como negativo?
Comment: Com PHP, usando a função preg_replace.
Comment: Usar regex para analisar HTML [**é ceder ao apelo do chtulhu**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)
Answer: Como já mencionado na resposta do Tivie, expressões regulares não são recomendáveis para analisar uma estrutura como o HTML, além do mais ela não é uma linguagem regular, não utilize regex quando há melhores ferramentas que possam fazer esse trabalho.
Leia mais sobre isso nesse artigo (em inglês): Expressões Regulares: Agora você tem dois problemas
Vou seguir o mesmo caminho que o Tivie e usar DOMDocument e DOMXPath para analisar o HTML, mas pode ser usado outro parser, como o Simple HTML DOM Parser por exemplo.
$url = "paginahtml.html";         // Link da página
$outputFile = "novapagina.html";  // Arquivo onde será salvo as modificações

$html = file_get_contents($url); // Pega o conteúdo da página

$DOM =  new DOMDocument();
$DOM->loadHTML($html);

$xpath = new DomXpath($DOM);

$prices = $xpath->query('//*[contains(concat(" ", normalize-space(@class), " "), "priceText ")]');
$percent = 20.0 / 100.0; // 20%

foreach($prices as $price){
    $value = $price->nodeValue;
    $floatValue = floatval($value);
    $finalValue = $floatValue - ($percent * $floatValue);
    $price->nodeValue = $finalValue; // Salva o valor final com desconto de 20%
}

file_put_contents($outputFile, $DOM->saveHTML()); // Salva as modificações
echo "Done!";

DEMO
O exemplo acima utiliza a função file_get_contents para obter o conteúdo da página e salva as modificações em um novo arquivo com file_put_contents.
O código funcionou como o esperado passando o link da página fornecida nesse comentário. A expressão utilizada na query vai retornar os resultados desejados se o node atual apresentar parte do nome do atributo class, nesse caso priceText, com a função normalize-space do Xpath substituímos espaços excedentes por um único espaço e assim validando a expressão.
Para exibir as modificações na tela pode-se usar o echo.
echo $DOM->saveHTML();

Answer: Analisar HTML com regex é uma má opção e pode levar à loucura. Existem muitas maneiras de regex falhar ao ler HTML (por exemplo, TAGS em maiusculas ou minusculas, espaços entre as classes, linhas extra entre os elementos html, etc...)
Regex significar "Regular Expression", expressão regular, e HTML não é uma linguagem regular. Invariavelmente vai quebrar algures...

Dito isto...
A melhor forma será usar um "parser" verdadeiro.  Felizmente, existem várias opções em PHP.
Aconselho a usar o DOMDocument e o DOMXPath que vêm incluidos no PHP por defeito. Eis um exemplo:
HTML
$html = '

           1.2
           1.50
           200
           1.50

           <input class="betCode" type="hidden" value="0]SK@82285689@314222649@NB*1~2*0*-1*0*0]CPN:0" />
           <input class="originalBetCode" type="hidden" value="0]SK@82285689@314222649@NB*1~2*0*-1*0*0]CPN:0" />

';

codigo PHP
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);

//Lista de spans filhos de div"isOffered"->a
//So lista as divs que contenham a class 'pricetext'
$nodeList = $xpath->query("*/div[@id='isOffered']/a/span[contains(concat(' ', @class, ' '), ' priceText ')]");

foreach ($nodeList as $node) {
    if ($node instanceof \DOMElement) {
        // Le o valor do span e transforma num inteiro
        $value = (float) $node->nodeValue;

        // Altera o valor do span
        $node->nodeValue = $value * 0.8;
        var_dump($node->nodeValue);
    }
}

//salva as alterações feitas ao documenthtml
//e guarda na variavel newHtml
$newHtml = $doc->saveHtml();

Para impedir que o DOMDOcument engasgue em documentos HTML com erros, pode adicionar esta linha no inicio do seu codigo:
libxml_use_internal_errors(true) AND libxml_clear_errors();

Comment: Obrigado amigo! deu certinho.
Comment: Amigo, me dá outra força! seu código funciona, mas de onde estou retirando as informações, tem muitas div, tags e outras coisas, aí seu código não consegue capturar os valores e só me retorna "warnings", e outra: como faço pra levar esses valores modificados para o HTML? lembre-se que estou usando file_get_contents para pegas os dados de um site remoto e exibir no meu site da mesma forma, só que com os valores diminuidos.
desculpe minha ignorância, estou no começo do curso PHP e não sei muito ainda rs. por favor me dê mais essa ajuda!
Comment: Veja a ultima linha do meu post
Comment: Quanto ao capturar os valores, tem a ver com o XPATH, provavelmente tem de ser alterado para corresponder ao caminho de onde está a retirar a informação.

Aconselho a ler isto: http://www.dicas-l.com.br/arquivo/tutorial_xpath.php#.VO5WVfmsWxU

Pode ajuda-lo a compreender como funciona o XPATH, vai ver que é bastante simples. Depois é só substituir `"*/div[@id='isOffered']/a/span[contains(concat(' ', @class, ' '), ' priceText ')]"` pelo xpath correcto
Comment: Obrigado amigo! vou estudar o XPATH.
Comment: Quanto aos erros do  DOMDOcument, quando apliquei seu código no início, nenhum erro foi exibido, mas também não me mostrou os valores, ficou tudo branco.
Se quiser ver como está o html que estou a buscar pode ir no link:
[link](http://admin.sportfacil.com/proxy/especial/valor.html)
Answer: Também recomendo o uso do dom parser mas só pela diversão ta ai uma versão beta usando regex
<?php

$html = <<<XXX

   1/2
   1.50
   -200
   1.50

   <input class="betCode" type="hidden" value="0]SK@82285689@314222649@NB*1~2*0*-1*0*0]CPN:0" />
   <input class="originalBetCode" type="hidden" value="0]SK@82285689@314222649@NB*1~2*0*-1*0*0]CPN:0" />

XXX;

$re = "/(span.*pricetext.*>)([\d\/.-]+)/im";

$ret = preg_replace_callback($re, function($matches){
    $matches[2] = ((float)$matches[2]) * .8;
    return $matches[1] . $matches[2];
}, $html);

echo $ret;

https://ideone.com/4kEPf9
Comment: Cara o seu funcionou também!
Obrigado pela ajuda :)
Answer: E já agora uma resposta clandestina e pornográfica (Perl :)
com expressões regulares:
perl -pe 's/\K(.+?)(?=<)/$1*0.8/e' span.xml

Com parser de xml:
#!/usr/bin/perl
use XML::DT;
my $filename = shift or die("Erro: usage $0 file.html\n");

print dt($filename,
            span => sub{$c *= 0.8 if $v{class} =~ /^pricetext/i; toxml },
            -html => 1,
        );

# $c - contents after child processing
# %v - hash of attributes


What are these formulas that are suppose to be Gram-Schmidt

Question: The formulas are in this picture.

My question is what are these formulas used for. I tried using them but they don't work. I'm familiar with Gram-Schmidt but these don't look like GRAM. I got these formulas from 3D Game Programming with DirectX 11.
The book says:
In §1.3.1, we looked at a way to orthogonalize a set of vectors using the process. For 3D, there is another strategy to orthogonalize a
set of vectors {Gram-Schmidtv0, v1, v2} that are almost orthonormal, but perhaps became un-orthonormal due to accumulated
numerical precision errors, using the cross product. Refer to Figure 1.15 for the geometry of this process:
Comment: Please use LaTeX to show the formulae.
Answer: I'm assuming the third equation is $\textbf{W}_1 = \textbf{W}_0 \times \textbf{W}_2$.
Those three equations are just another way to obtain an orthonormal basis of vector for $\mathbb{R}^3$. For higher dimensions, one will have to generalize the cross product, which is much more of a hassle than the Gram-Schmidt process.
The first equation normalizes one of our vectors $\textbf{v}_0$, and sets it equal to $\textbf{W}_0$. The second equation produces a vector orthogonal to $\textbf{v}_1$ and $\textbf{W}_0$, and normalizes it also, setting it equal to $\textbf{W}_2$.
Now you have two orthonormal vectors in $\mathbb{R}^3$. A way to get a third is to take the cross product of the two.


A complex anti/symmetric nilpotent matrix is null?

Question: i know how to prove that

a real symmetric nilpotent matrix is null
a real antisymmetric nilpotent matrix is null

But, is a  complex symetric nilpotent matrix is null (Q1) ?
I think that a complex antisymetric nilpotent matrix is null. Because if $A$ is complex antisymetric nilpotent matrix, $A$ is diagonalizable, so $A=PDP^{-1}$ with $D$ the diagonal of eigenvalues. But $A$ is nilptotent. For an integer $p$, $A^p=0$ $\Rightarrow D^p=0 \Rightarrow D=0 \Rightarrow A=0$.
Can we prove that a complex antisymetric nilpotent matrix is null without using the argument above (Q2) ?
Answer: First, a complex antisymmetric matrix is NOT diagonalizable.
Second, a complex antisymmetric nilpotent matrix is not always null.
The following matrix is a counterexample for both:
$$
A =
\begin{pmatrix}
0 & 1 & 0\\
-1 & 0 & i\\
0 & -i & 0
\end{pmatrix}
$$
$A$ is an antisymmetric matrix, but its characteristic polynomial is $-x^3$ so it is nilpotent and it isn't diagonalizable.
$$
B =
\begin{pmatrix}
0 & 1 & 0\\
1 & 0 & i\\
0 & i & 0
\end{pmatrix}
$$
Moreover, $B$ is symmetric nilpotent, but not null, with the same reasoning above.
Comment: OK ! Nice example.
Answer: I suppose you mean by symmetric: $A=A^H$, where $A^H$ is taking transpose + complex conjugate.
Assume $A= A^H$ nilpotent, $A\ne 0$. Then there is $n\ge 1$ such that $A^{2n}=0$ but $A^n\ne0$.
$A^{2n}=0$ implies
$$
0=x^H(A^{2n} x) = (A^nx)^H(A^nx)=\|A^nx\|_2^2
$$
for all $x$, hence $A^n=0$. Contradiction, hence $A=0$.
In case $A=-A^H$, you get an additional factor $(-1)^n$ in the above equation, which does not influence the conclusion.
Comment: A is symmetric if $A^{T} = A$. ($T$ for only transpose)
Answer: I want to sum up fact on anti/symmetric nilpotent real/complex matrix
1) (A is a real symmetric nilpotent matrix)  $\Rightarrow A =0 $
Proof : $A$ is diagonalizable.  $(A = PDP^{-1}) \Rightarrow (0=A^p = PD^pD^{-1})$ fon an integer $p$. So $D^p = 0 \Rightarrow D=0 \Rightarrow A=0$.
2) (A is a real antisymmetric nilpotent matrix)  $\Rightarrow A =0 $
Proof 1 : $A^2$ is symmetric and nilpotent thus $A^2=0$ (thanks to the previous result). So ${\rm tr}(A^2)=0$ (trace). But $A^2=-(A^T)A$ so $0={\rm tr}(A^2) = -\|A\|^2$ and $A=0$.
(We use the scalar product $(M \mid N) = {\rm tr((M^T)N)}$)
Proof 2 : $A$ is a real antisymmetric matrix so $A$ is diagonalizable in ${\Bbb C}$ (i'm right here ?)
We can write the same proof as before for the real symmetric nilpotent matrix.
Proof 3 : let f the endomorphisme of ${\Bbb R}^n$ with matrix $A$. $A$ is nilpotent so $F={\rm Ker}(A)$ is not null.  $f(F) \subset F$ and we have the same thing for $F^{\perp}$ (for the usual euclidean scalar product on ${\Bbb R}^n$).
Suppose that $A$ is not null. So $F^{\perp} \neq \{0\}$.
We choose a base according ${\Bbb R}^n = F \oplus F^{\perp}$. In this base, the matrix of $f$ is the block diagonal matrix :
$$\begin{pmatrix}
0 & 0 \\
0 & B
\end{pmatrix}$$
$B$ is inversible for ${\rm Ker}(f) \cap F^{\perp}$ is null.
$A$ is nilpotent so $B$ is nilpotent. But $B$ can't be inversible AND nilpotent. So $A=0$.
3) A complex antisymmetric nilpotent is not necessarily null (cf example given by Exodd)
4) A complex symmetric nilpotent is not necessarily null (cf example given by Exodd)
Questions : what are the complex anti / symmetric nilpotent matrix ? Is there any known characterization of these matrix ?
Comment: @daw is your matrix antisymmetric ?


Regressing a differenced variable on a lagged variable. How can I fix the error in R?

Question: I have a time series (std) of 324 observations with no missing values, starting from January 1987 and ending in December 2013.
I want to regress via OLS the one in the question.
In R, the code:
 lm(dstd ~ lstd)

Where 'dstd' is the differenced variable, via:
 dstd<-diff(std,differences=1)

And lstd is the lagged variable via:
 lstd<-lag(std, k=1)

Does not work, as it gives the following error:
 Error in model.frame.default(formula = dstd ~ lstd, drop.unused.levels = TRUE) :
 variable lengths differ (found for 'lstd')

Which is, of course, natural as the length of 'dstd' is 323 while the length of 'lstd' is 324.
Searching for the error, na.omit has been suggested as the answer for other models. However, no combinations of 'na.omit' or 'na.exclude' would work. This video (at the relevant time) says ' you need to change these', referring to these variables.
I have tried excluding while forming another object, as well as subsetting in the regression model, yet none of these seem to work.
What code would I need to fix this?
Here is a Minimal Reproducible Example:
An object 'stdshort' is created with the same characteristics of the parent object, via this code:
 > stdshort<-dput(window(std, 1987, 1989, 12))
 structure(c(4.5, 4.7, 4.2, 4.4, 3.9, 3.9, 3.7, 3.7, 3.4, 3.6,
 3.5, 3.1, 3.5, 3.3, 3.7, 3.7, 3.7, 3.8, 3.6, 3.5, 3.5, 3.3, 3.5,
 3.5, 3.4), .Tsp = c(1987, 1989, 12), class = "ts")

The following code replicates the steps previously mentioned: differencing, lagging and linear regression.
First, a differenced object is created. The object dtstdshort's structure looks like this:
 > dstdshort<-diff(stdshort,differences=1)
 > dput(dstdshort)
  structure(c(0.2, -0.5, 0.2, -0.5, 0, -0.2, 0, -0.3, 0.2, -0.1,
 -0.4, 0.4, -0.2, 0.4, 0, 0, 0.0999999999999996, -0.2, -0.1, 0,
 -0.2, 0.2, 0, -0.1), .Tsp = c(1987.08333333333, 1989, 12), class = "ts")

A following object, lstdshort, for 1 period lagging is constructed. This is the structure:
 > lstdshort<-lag(stdshort,k=1)
 > dput(lstdshort)
 structure(c(4.5, 4.7, 4.2, 4.4, 3.9, 3.9, 3.7, 3.7, 3.4, 3.6,
 3.5, 3.1, 3.5, 3.3, 3.7, 3.7, 3.7, 3.8, 3.6, 3.5, 3.5, 3.3, 3.5,
 3.5, 3.4), .Tsp = c(1986.91666666667, 1988.91666666667, 12), class = "ts")

The regression of those two objects as explained before, gives the following error (with code):
 > lm(dstdshort ~ lstdshort)
 Error in model.frame.default(formula = dstdshort ~ lstdshort, drop.unused.levels = TRUE) :
   variable lengths differ (found for 'lstdshort')

Comment: This question appears to be off-topic because it is about programming without a reproducible example.
Comment: Would uploading the data make it better?
Comment: I voted to leave this question open because although it is phrased in terms of "code" it reflects a very basic problem that I believe will have a universal (code-independent) answer.
Comment: I'd suggest the smallest reasonable example with the same issue.
Comment: Added relevant Minimal Reproducible Example as requested.
Comment: A minimal reproducible example is one where I can paste the code in and get the same data and results as you. That is, it would go "`dstdshort <- structure(c(4.5, 4.7, 4.2, ...`". But I managed.
Comment: I am sorry, this is the first time I wrote one, and I followed the instructions to the best of my understanding according to [this question](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example).
Answer: The function ts.intersect sets up the variables for you.
stdshortcomb <-  ts.intersect(dstdshort,lstdshort)
lm(dstdshort~lstdshort, stdshortcomb)

Call:
lm(formula = dstdshort ~ lstdshort, data = stdshortcomb)

Coefficients:
(Intercept)    lstdshort
     0.6798      -0.1995


Solve in $\mathbb{R^{3}}$ : $\begin{cases}(1+4x^{2})y=4z^{2}\\(1+4y^{2})z=4x^{2}\\(1+4z^{2})x=4y^{2}\end{cases}$

Question: Solve the system in $\mathbb{R^{3}}$ :

$$\begin{cases}(1+4x^{2})y=4z^{2}\\(1+4y^{2})z=4x^{2}\\(1+4z^{2})x=4y^{2}\end{cases}$$

My try :
By imaging I see $(\frac{1}{2},\frac{1}{2},\frac{1}{2})$ is a solution!
From a first equation :
$$x=\frac{1}{2}\sqrt{\frac{4z^{2}}{y}-1}$$
So by second equation :
$$y=\frac{1}{2}\sqrt{\frac{\frac{4z^2}{y}-1}{z}-1}$$
But after applied I get difficult equation for $z$ ?
Answer: We see that all are nonnegative.
If one of them is $0$ then all are $x=y=z=0$. Now suppose all are $>0$.
Now $1+4x^2\geq 4x$ so $$4z^2=y(1+4x^2)\geq 4xy\implies z^2\geq xy$$
In the same manner we get $y^2\geq xz$ and $x^2\geq yz$ so, if say $x^2>yz$ we get $$x^2y^2z^2>xyxzzy$$
a contradiction. So $x^2=yz$ and similary for other, so we have equality sign every where and thus $$1+4x^2 = 4x\implies x={1\over 2} = y=z$$
Comment: I don't see it (I mean +1)
Comment: So you are not going to give me that +1 after all?
Comment: Thanks! .......+1!
Answer: Hint
What if $x=0?$
For nontrivial cases $x,y,z>0$
$$(1+4x^2)(1+4y^2)(1+4z^2)=?$$
$$(1-2x)^2\ge0\implies1+4x^2\ge4x$$
Check when the equality can occur
Comment: can you complete your solution ? I don't get you
Comment: @Ellen, Similarly for $y,z$ So, we get $$(1+4x^2)(1+4y^2)(1+4z^2)\ge64xyz$$ the equality occurs when each of $$(1-2x)^2$$ are zero
Answer: Taking the resultant of equations 1 and 2 with respect to $z$, we find
$$ 64\,{x}^{2}{y}^{5}+32\,{x}^{2}{y}^{3}+16\,{y}^{5}-64\,{x}^{4}+4\,{x}^{
2}y+8\,{y}^{3}+y
=0 $$
Taking the resultant of equations 1 and 3 with respect to $z$, we find
$$ 4 x^3 y + x y - 4 y^2 + x = 0$$
Taking the resultant of these two with respect to $y$, we find
$x = 0$ or $x = 1/2$ or
$$ 65536\,{x}^{18}+65536\,{x}^{17}+147456\,{x}^{16}+131072\,{x}^{15}+
156672\,{x}^{14}+205824\,{x}^{13}+221440\,{x}^{12}+251904\,{x}^{11}+
234624\,{x}^{10}+203392\,{x}^{9}+179232\,{x}^{8}+159104\,{x}^{7}+
131524\,{x}^{6}+39460\,{x}^{5}+10681\,{x}^{4}+2800\,{x}^{3}+680\,{x}^{
2}+128\,x+16
 = 0$$
This last polynomial has no real roots. The real solutions are $(0,0,0)$ corresponding to $x=0$ and $(1/2,1/2,1/2)$ corresponding to $x=1/2$.
Comment: not esay very difficult you solution


PowerShell to open gzip stream

Question: Web searches for $s=New-Object IO.MemoryStream(,[Convert]::FromBase64String()) show numerous Pastebin's for similar events, but I cannot figure out how to decode it myself.  The original base64 I decode with
param(
[Parameter(Mandatory=$True)]
[string]$b64
)
[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("$b64"))

which gives me this:
$s=New-Object IO.MemoryStream(,[Convert]::FromBase64String("Encrypted-String"))
IEX (New-Object IO.StreamReader(New-Object IO.Compression.GzipStream($s,[IO.Compression.CompressionMode]::Decompress))).ReadToEnd();

I have been unable to figure out how to use PowerShell to decompress the "Encrypted-String" so I can analyze what's happening.
I've seen similar posts but nothing answers my question of how to decode it myself.  Any help is greatly appreciated.
Comment: What are you trying to achive?
Comment: Are you trying to ask how to decompress a gzip comressed string with PowerShell? gzip is only mentioned in the title, while you are saying base64 in the question's body.
Answer: I apologize for the formatting, I am still learning the nuances of posting questions/anwers on here.  I also apologize if my question wasn't clear, but after much luck with today's research (been trying to figure this out for the past year).
I found a link (https://blog.kenaro.com/2010/10/19/how-to-embedd-compressed-scripts-in-other-powershell-scripts/) which gave me enough information to build this script.  Thank you Ingo Karstein for your blog and all who viewed and asked for clarification.
The gzip stream is part of the results that needed further analysis which I was unable to figure out.
I create a folder in my Temp with the name of the machine that I obtained the suspicious batch file from that calls the encoded powershell command; remove all but the base64 code and rename it to a .txt file.  I then run the code below with the computername and the file name to see what the attacker was doing.  The answer that works for me:
(
[Parameter(Mandatory=$True)]
[string]$HostIP,
[Parameter(Mandatory=$True)]
[string]$file
)

New-Item C:\Temp\$HostIP\Results -ItemType Directory

$b64 = Get-Content C:\Temp\$HostIP\$file.txt -Raw
Write-Host
$results = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("$b64"))
$results | Out-File C:\Temp\$HostIP\Results\unicode_$file.txt

$ec64 = Get-Content C:\Temp\$HostIP\Results\unicode_$file.txt
$eb64 = $ec64|%{$_.split('"')[1]}

$data = [System.Convert]::FromBase64String("$eb64")
$ms = New-Object IO.MemoryStream
$ms.Write($data, 0, $data.Length)
$ms.Seek(0,0) | Out-Null

$cs = New-Object IO.Compression.GZipStream($ms, [IO.Compression.CompressionMode]::Decompress)
$sr = New-Object IO.StreamReader($cs)
$t = $sr.readtoend()
$t | Out-File C:\Temp\$HostIP\Results\decompressed_$file.txt

$dcb64 = Get-Content C:\Temp\$HostIP\Results\decompressed_$file.txt
$dc64 = $dcb64|%{$_.split('"')[1]}

$utf = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("$dc64"))
$utf | Out-File C:\Temp\$HostIP\Results\utf8_$file.txt

$asc = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("$dc64"))
$asc | Out-File C:\Temp\$HostIP\Results\ascii_$file.txt

$utf8 = "C:\Temp\$HostIP\Results\utf8_$file.txt"
$ascii = "C:\Temp\$HostIP\Results\ascii_$file.txt"

(Get-Content "$utf8") -replace "`0", "" | Set-Content "C:\Temp\$HostIP\Results\utf8_no-null_$file.txt"
(Get-Content "$ascii") -replace "`0", "" | Set-Content "C:\Temp\$HostIP\Results\ascii_no-null_$file.txt"

'

PowerShell to open gzip stream


Distribution of dependent variable in linear regression with fixed effect (panel data)

Question: I have a question regarding the hypothesis of the distribution of the dependent variable in a linear regression model.
I have a model to assess the earning losses of displaced workers. I have observations of treated (displaced) and control (non displaced) workers. When a worker is displaced and only finds a job years after, I assign 0 to its earnings on every unemployment year.I have five cohorts of displaced workers (2002 to 2006), and I assess the impact of displacement on annual earnings from t-2 to t+5 (t being the year of displacement, it varies depending on which cohort the worker belongs). Control workers can become treated afterwards and every worker can be used several times as control (imagine you are a control worker in 2003 and 2004 because you have only been displaced in 2005).
I did a matching between displaced and non displaced worker based on displacement year and several other variables (age, sexe etc) based on the probability of being displaced (propensity score) and obtain a weakly balanced panel data. Then, I use a linear fixed effect regression (xtreg) to assess the effect of treatment on the annual earnings of workers.
The problem is: since I put 0 for earnings for all observations where the worker is unemployed, the distribution of my dependent variable is not continuous (there are a mass of observations where the earnings are equal to 0, and the rest of the distribution is continuous). Nevertheless, there are several paper in the same case using a linear regression anyway.
What do you think ? I would be very glad if someone could help me with that.
Thank you very much !!!!
Eugenie
Answer: It sounds like you're looking at a hurdle model of some sort. Workers earn $0 unless they break some hurdle of characteristics (job hunting, soft skills, etc.).  After that point they are employed and have earnings greater than 0.
Using a hurdle model will better allow you to estimate the effects of how many people have jobs, and the wages of those jobs when they occur.
Note unemployment might be highly endogenous, those who are low quality workers are probably more likely to be fired, so your estimate of the effect of unemployment on future low wages/unemployment will likely be overestimated.
Many papers use linear regression (Do you mean IV techniques? They're linear but not OLS.) so they can estimate the effect at the mean and don't estimate the intensive and extensive margins.
Suggestion: You might want to ask in the economics forum. Their techniques are going to be better suited for this task than typical ML approaches.
Comment: Thank you very much. To avoid endogeneity, I only include displaced workers following firm closure :such separations are unrelated to the performance and career aspirations of workers and have been considered exogenous from a worker's perspective. I also use matching to enhance the plausibility of this exogeneity assumption. Other papers use diff-in-diff regression with individual FE to assess the effect of displacement on workers. Estimating the effect at mean is not a problem, I only want to know if the method is wrong when the dependent variable is distributed with mass effects on zero.
Comment: You should also look at Tobit for similar cases, though I think you specifically need a hurdle model: https://en.wikipedia.org/wiki/Censored_regression_model