Percentile Calculation

Question: I have a series of data. let's say these are scores of various schools  (51.3%, 51.3%, 62.5%, 64%, 68%, 71.3%, 84.5%, 86%, 88.7%, 90%, 91.3%). For this, All I need to calculate percentile for each school.
What is easiest way to find?
Comment: Note that there are multiple ways of computing percentiles. For a large number of data these give approximately the same result, but you have a small number of data. See http://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm . If this is an exercise for school, you should consult your textbook or course notes for a formula so that you use the desired method.
Answer: Let's look at the definition of a percentile first:
"A percentile is a value on a scale of $100$ that indicates the percent of a distribution that is equal to or below it." – Merriam-Webster
According to this definition, the $1$st percentile includes everything that is within $1$ percent or less, the $2$nd percentile includes everything that is $2$ percent or less, and so on.
All you have to do is to round up the numbers to the nearest whole number. This is because something like $51.3$% is not in the $51$st percentile or less, but in the $52$nd percentile.
Answer: Write the rank of each school. After that apply formula
<code> Percentile = ((position of school)/total no. Of school participating - 1))*100
</code>
I did -1 because in total the school(of which the percentile is calculated) is never included.
Now you will think why percentile is not 100 for first ranked school. Fyi percentile never comes 100. For very big no. Of participants it may approaches to 99.999...... but never 100.
Hope you got it from here.
Comment: Bhai Yaar upvote karde.

Percentile Calculation


Singles net at ATP

Question: Why they don't use a singles net at the ATP Finals. Also on other big tournaments they often use the doubles net.
Is there a rule, when a turnament is supposed to have a singles net or is it a decision if every tournament?
Comment: They play doubles as well on them, why would it be better to have to take out the posts and nets and redo them between singles and doubles
Comment: A "Singles net" can also be a doubles net with sticks placed in the right spots on the sides. That's how it's done at nearly every professional tournament in the world, including the ATP finals.
Comment: @aqwert: true, but I remember in Gstaad (ATP250) the changed the net for doubles and singles until 10 years ago. And e.g. https://www.youtube.com/watch?v=D-AQC8Bbvhs in Wimbledon, they have singles net on the center court, when singles are played. So my question is, if is there a rule when a turnament should change the nets.
Comment: @chloese . I don't think there is a rule apart from the rule where the net needs to be a certain height on the ends (and therefore use a stick) and a certain height at the middle. If the tournament wants to go through the trouble then they can.
Answer: There is no rule for which net to use. It is because doubles are played on the same tournament (venue) at the same time. It is easier to just place sticks under the net for singles rather than changing the whole net.

Singles net at ATP


Are there specific injury concerns I should watch out for with piano tremolo exercises?

Question: Based on Cortot exercies like these...

...I've been practicing patterns like this for seventh chords...

...and left hand...

The spacing of the fingers with these major seventh chords feels different than other seventh chord types like minor sevenths, etc. The fingers get crowded at the minor seconds, but then stretch to reach the major thirds. The finger spacing feels more even for the other chord types.
When I reach with finger 4 to get to a black key I notice that my left hand has a more difficult time than my right, but my two hands are the same size.
When if finish playing like this my palms feel a little warm and sort of 'itchy.' I'm not sure exactly how to describe it. It does not hurt or ache or spasm, etc. I definitely feel like my hands need a rest by the end. I don't push through any discomfort.
It feels similar to the fatigue of playing scales in octaves or full octave chords, but it's more centered in my palms.
Let's just say I've had worse feeling from using the computer mouse wheel, and I have enough sense to stop before I've really irritated by hand.
Of course I don't want to do any damaging repetitive motions. But I can't really tell if this is just a phase of coordinating and training my hand.
Just looking for some guidance.

does my pattern show some misunderstanding of the Cortot exercises?
are there some time limits I should keep in mind?
should I avoid certain things when doing such tremolo patterns?

EDIT for a bounty.
The one answer I received from @MalcolmKogut is appreciated but is more of a general overview of anatomy than a response about these particular exercises. I'm looking for help with how to approach these exercises safely. Or, if the recommendation is to avoid them entirely, some explanation of why such exercises were recommended by Cortot - whose teaching I understand is still used today - but avoided by some teachers.
Also, I removed the word 'strengthen' from my question. I can tell now that word is a big piano instruction buzz word. This issue isn't about strength, but extension (meaning spreading my fingers apart - which apparently uses the interossei muscles) and finger independence, which I understand is mostly an issue or coordinating the nervous system. To be clear: I do not think these exercises are about working out finger muscles. I can hold my fingers fully spread apart without discomfort or fatigue. I can do motions like this for an extended time - 20 minutes for example - so the point is already understood these exercises are not about strength. I want to know how to approach such exercises safely.
I found some videos like this one...

...from what I have seen in this particular video I gather that I don't need to play them fast and the ability to rock your hand in subtle circular motion while the keys are depressed sort of tests or demonstrates a firm touch without undesirable tension and stiffness. He calls it 'loose' around 5:47 in the video.
Answer: I have been looking at that question for a few days unsure if I could actually bring anything useful. I will try.
First, some comments about what you shared:

Though I have never followed these particular exercises, the Cortot exercises make sense to me. I do not know about strength but they certainly teach about independence and help (to a lesser extend) with stretching.  It's common to start children on much simpler versions of these exercises where some keys need to remain depressed while others are being played.  During these exercises, it is key to remain completely relaxed and there is no need for racing either, very much like what the video shows. There is nothing wrong with them if you approach them that way. If you don't, yes, they can harm you.
The video also makes perfect sense: slow and relaxed. Note also why he doesn't move down the fifth finger on his left hand. Even if you do that one slowly, there is an uncomfortable stretch even if you are completely relaxed (unless you have even more reach than him).  That isn't the case in any of the Cortot exercises you showed where the stretches are much more subtle and completely safe.
Regarding your own exercise. First I think you meant to show the same notes and fingering but different notes depressed (1 and 3) if you want it to be the very same as the right hand. When I activate the very same fingers on both hands, I do not feel the difference you describe. The only difference possibly between your chords and Cortot's is that the fingering for your chord is really counter intuitive. For example, you would want to put a 5th instead of 4th for the notes you have. I do get you are after a stretch but Cortot's chords present the advantage of representing more natural positions that would occur more commonly. And I do think there is value, if you are into exercises, in making them as realistic as can be.  But these somewhat unnatural positions you have feel completely safe to me nevertheless.

To sum it up and answer your questions directly now.

does my pattern show some misunderstanding of the Cortot exercises?

No. Your pattern is just not as natural so conceivably not as useful.

are there some time limits I should keep in mind?

No time limit. Listen to your inner tensions. If any of these happen: you cannot move your hand and arm gently as shown in the video, you feel tensions, in your wrist, up your arm or even into your shoulder or neck, your neighbor wants to smash your head or the piano or both, just stop.

should I avoid certain things when doing such tremolo patterns?

Avoid rushing it. Avoid any form of tension (stretching != stressing).

I'm looking for help with how to approach these exercises safely. Or,
  if the recommendation is to avoid them entirely, some explanation of
  why such exercises were recommended by Cortot.

I think I answered everything as objectively as I could. So I will conclude subjectively: exercises are great; practicing on actual music is greater.  Exercises are fine in context. Pick a score at your level, whatever it is, and within that score listen to your performance. Identify the areas that need improvement: evenness of the touch, fluidity, softness, rhythm, precision, etc. and come up with exercises--with the help of a teacher if need be--that will hone on your weakness. Because the ultimate test for all these exercises is whether they work, and your improvements on the actual piece you play will be the best judge of that.
Answer: I am not a slave to notation so if something feels "wrong" I either try to figure out what movement is missing or what movement is getting in the way of my execution or, I work around it.   I also beleive in working on technique through the use of real music rather than exercises.  For instance, I know I will probably not hurt myself jumping off the roof of my house but, I'm not going to try it (although I did it all the time as a youth).
Tremolos and trills on their own come from the pronator and supinator muscles around your elbow.  Those two muscles are strong and don't fatigue very easily.   The reason is because you can not use both at the same time.  When you pronate your supinator rests.  When you supinate your pronator rests.  It is impossible to use both at the same time. If you could, like a game of tug of war they would tear at each other, strain and cramp.  Likewise, you can only flex or extend your fingers, you can't do both at the same time - HOWEVER, if you isolate a finger, you can indeed engage your flexors and extensors simultaneously.  The bad thing about that is your flexors and extensors will pull on one another creating tension.  If you are lucky enough to not strain anything you may be creating micro tears to the tendons.  That sort of damage is cumulative because tendons don't have a direct blood supply and can't heal as fast as tearing muscle which is flooded with cell healing blood. The first sign of this is waking up in the morning feeling a little stiff.  That is a sign that your tendons are inflamed and adhering to the tendon sheath. Once you get your synovial fluid flowing you can force the tendons to glide again.  That should serve as a warning, not the need to "warm up."
All those exercise examples you provided require you to use both flexors and extensors at the same time.  Oh, they also most likely require you to use your abductors too.  That means you have three muscles pulling on one another simultaneously.  Something will strain but you may not feel it now.  As I said, it is cumulative.
Another downside to static loading your hand in place to play these exercises, you can't use gravity to play the notes and must use brute force. Unable to use equal and opposite muscles they never get to rest.  Every motion must have an equal and opposite motion otherwise it will strain.
Here is an example; if you walk your legs effortlessly move right, left, right, left.  If you tie your inner leg to another person as in a three legged race, you now have a third vector force pulling on you and you can immediately feel the strain.  We do this with our hands all the time but most of our teachers tell us to practice more or prescribe exercises to build strength and endurance.  The thing is, we don't need strength and endurance, only to obey the laws of physics.  Don't ever challenge the laws of physics because it will always win, eventually.  Just ask the builders of the Tower of Pisa.
Your hands have to serve you for about 80 years and injuries never fully heal. Instead, we power through them because we are taught "no pain no gain."  What a lie that is.  The body often replaces damaged tissue with scar tissue and rarely do cartilage, tendons and ligaments heal 100%.  Muscle indeed does get stronger with damage but the pianist doesn't need more muscle. The body will provide what it needs. That is why your anti gravity muscles are stronger than your go with gravity muscles (hamstrings, quads / bicep, triceps). You don't need muscle to stand on the floor.  Gravity does all the work, you only need ancillary balancing muscles. The same is true at the piano.  We've all seen 5 year old prodigies, surely they don't have more muscle than a grown adult.  What is different is they are going with the laws of physics and not trying to brow beat technique into the wrong muscles.
Just my take.  I may never be the best pianist but I will still be playing when I am 80.
Comment: Is the main concern that two fingers are held down while the other two perform the tremolo? Regarding real music versus drill, this stuff is just a means to an end for me: finger independence and 'finding' any chord on the keyboard. I'm open to using other methods.
Comment: I've re-read this answer several times over the past week and watched some online lessons - like this one https://youtu.be/uFjz_O9TUSA?t=402 - I can't really tell if you mean 'don't play these at all' or 'play them properly.' It seems like if played only with the flexors/extensors it could be harmful. But if played with pronator/supinator and some wrist motion that is better. I understand the ergonomics of gravity drops and muscle balance. I just don't understand how you recommend applying that to these kinds of passages.


Prove that there are no integers with order $4$ in modulo $12$

Question: Prove that there are no integers with order $4$  in  modulo $12$

This is given as an obvious fact without any proof in my textbook. However I am not able to see why there cannot be any integer whose order is $4$ in $\mod 12$. Any help ? thanks !
Comment: If "order" means additively, then $3$ has order $4$.  If "order" means multiplicatively, then look at $\mathbb{Z}_{12}^\times$.
Comment: That doesn't help. I am looking for an explanation and not references. Order of $a$ in $\mod n$ is the smallest positive integer $k$ such that $a^k \equiv 1 \pmod n$
Comment: @rational, no. What you wrote is the *multiplicative* order of $\;a\;$ in the group of units modulo $\;12\;$ , i.e. in  $\;\Bbb Z_{12}^*\;$. As Vadim explained to you, without further saying your question implies the additive order, meaning: the order in the group $\;\Bbb Z_{12}\;$.
Answer: Explicitly $\mathbb{Z}_{12}^\times=\{\pm 1, \pm 5\}$, and each of these has order at most 2, e.g. $(-5)^2=25\equiv 1\pmod{12}$.
Comment: nice ! i liked this proof
Comment: I don't get this proof :( I am not familiar with groups :/
Answer: Using Carmichael function,
$$\lambda(12)=\text{lcm}(\lambda(4),\lambda(3))=\text{lcm}(2,2)=2$$
In fact,  $$\lambda(24)=2$$
Comment: The number $12$ is a very small number. Note that $1$ has order $1$. The numbers $2,3,4$ are not relatively prime to $12$, so no power of them is congruent to $1$. Note that $5^2\equiv 1$, so $5$ has order $2$. Continue. Only $2$ more candidates to examine.
Comment: I'm sorry may I ask how does that prove there is no $a$ such that $a^4\equiv 1 \mod 12$ ? (4 is minimum possible exponent)
Comment: @rational, Have you followed the link ?
Comment: still going through it, is this right $1^1 \equiv  1 \mod 12$
Comment: sorry for being slow; im hearing Carmichael function for the first time. it seems my textbook skipped this topic
Comment: @rational, $$1^1\equiv1\pmod n,(-1)^2\equiv1$$ for all integer $n$
Comment: Is it possible to prove this by using congruences and $\phi$ function ? Carmichael function is throwing me off at the moment as it is new to me sorry
Comment: @rational, Using $\phi, \phi(4)=\phi(3)=2\implies a^2\equiv1\pmod3,a^2\equiv1\pmod4\implies $ lcm$(4,3)|(a^2-1)$
Comment: okay and $\phi(12) = 4$ , how do these relate to the proof in question exactly ?
Comment: @rational, It implies max(ord$_{12}a)=2$
Comment: OMG yes! $7^2\equiv  11^2 \equiv 1 \mod 12$ We only had to check for $a \lt 12$ as we are doing $\mod 12$ and all other numbers can be written as $12k+r$ by division algorithm xD I am such a noob thanks a lot awesome people !!!!


IlegalArgumentException ao reabrir jInternalFrame várias vezes

Question: Estou com uma aplicação que está validando quando a janela JInternalFrame está aberta ou fechada, mas se a janela for aberta e fechada algumas vezes seguidas, o console apresenta um erro e não abre novamente o JInternalFrame.

Janela com JDesktopPane:
package janelas;

public class desktop extends javax.swing.JFrame {
    private frameInterno register;

    public desktop() {
        initComponents();
    }

    private void initComponents() {

        painelDesktop = new javax.swing.JDesktopPane();
        btnAbrirFrame = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout painelDesktopLayout = new javax.swing.GroupLayout(painelDesktop);
        painelDesktop.setLayout(painelDesktopLayout);
        painelDesktopLayout.setHorizontalGroup(
            painelDesktopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        painelDesktopLayout.setVerticalGroup(
            painelDesktopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 260, Short.MAX_VALUE)
        );

        btnAbrirFrame.setText("Abrir Frame");
        btnAbrirFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirFrameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(painelDesktop)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(301, Short.MAX_VALUE)
                .addComponent(btnAbrirFrame)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(painelDesktop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAbrirFrame)
                .addGap(0, 11, Short.MAX_VALUE))
        );

        pack();
    }

    private void btnAbrirFrameActionPerformed(java.awt.event.ActionEvent evt) {
        if (register == null) {
            register = new frameInterno();
        }

        if (!register.isVisible()) {
            painelDesktop.add(register);
            register.setVisible(true);
        }
        register.toFront();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new desktop().setVisible(true);
            }
        });
    }

    private javax.swing.JButton btnAbrirFrame;
    private javax.swing.JDesktopPane painelDesktop;

}

Janela JInternalFrame:
package janelas;

public class frameInterno extends javax.swing.JInternalFrame {

    public frameInterno() {
        initComponents();
    }

    private void initComponents() {

        btnSair = new javax.swing.JButton();

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(300, Short.MAX_VALUE)
                .addComponent(btnSair)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(200, Short.MAX_VALUE)
                .addComponent(btnSair)
                .addContainerGap())
        );

        pack();
    }

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {
        this.dispose();
    }

    private javax.swing.JButton btnSair;
}

Erro (exception):

Exception in thread "AWT-EventQueue-0"
java.lang.IllegalArgumentException: illegal component position  at
java.awt.Container.addImpl(Container.java:1100)     at
javax.swing.JLayeredPane.addImpl(JLayeredPane.java:231)     at
javax.swing.JDesktopPane.addImpl(JDesktopPane.java:484)     at
java.awt.Container.add(Container.java:417)  at
janelas.desktop.btnAbrirFrameActionPerformed(desktop.java:63)   at
janelas.desktop.access$000(desktop.java:3)  at
janelas.desktop$1.actionPerformed(desktop.java:31)  at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)    at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)    at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)     at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)  at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)  at
java.awt.Component.processMouseEvent(Component.java:6533)   at
javax.swing.JComponent.processMouseEvent(JComponent.java:3324)  at
java.awt.Component.processEvent(Component.java:6298)    at
java.awt.Container.processEvent(Container.java:2236)    at
java.awt.Component.dispatchEventImpl(Component.java:4889)   at
java.awt.Container.dispatchEventImpl(Container.java:2294)   at
java.awt.Component.dispatchEvent(Component.java:4711)   at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)  at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)   at
java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)   at
java.awt.Container.dispatchEventImpl(Container.java:2280)   at
java.awt.Window.dispatchEventImpl(Window.java:2746)     at
java.awt.Component.dispatchEvent(Component.java:4711)   at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)  at
java.awt.EventQueue.access$500(EventQueue.java:97)  at
java.awt.EventQueue$3.run(EventQueue.java:709)  at
java.awt.EventQueue$3.run(EventQueue.java:703)  at
java.security.AccessController.doPrivileged(Native Method)  at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)     at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)     at
java.awt.EventQueue$4.run(EventQueue.java:731)  at
java.awt.EventQueue$4.run(EventQueue.java:729)  at
java.security.AccessController.doPrivileged(Native Method)  at
java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)     at
java.awt.EventQueue.dispatchEvent(EventQueue.java:728)  at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)   at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)  at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)   at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)   at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)    at
java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Comment: +1 pelo vídeo explicativo. Consegue copiar e colar o erro (exception) na sua pergunta também? Não dá para ver bem o motivo do erro
Answer: Em resumo, o erro ocorre porque está sendo adicionado um componente que o JDesktopPane já possui adicionado. Mas no caso do seu código, está havendo um dispose() no frame interno, e este método do frame interno faz com que ele se torne "invisível, não selecionável e fechado"1, o que deveria removê-lo do JDesktopPane.
Não consegui debugar o código por completo, mas posso deduzir que isso ocorre devido ao frame interno não deixar de existir, pois como já explicado, o dispose não destrói a instância.

Errata sobre a explicação do erro

O que causa o erro realmente é o fato do dispose() não destruir a referencia do frame interno, só o torna não-exibível, e o gerenciador de componentes do JDesktopPane, apesar de removê-lo uma primeira vez, não repete esta ação na segunda, o que gera a exceção pois o componente já está incluso, e você tenta inclui-lo novamente.

Para evitar esse tipo de problema e conforme já explicado o funcionamento do dispose() para com frames internos, é melhor alterar a visibilidade ao invés de dar dispose, pois a instancia vai ficar disponível de qualquer jeito, então, apenas altere o método de fechamento do frame interno para:
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {
    this.setVisible(false);
}

E com essa alteração, não é necessário adicionar mais de uma vez o componente no desktoppane, então, mova a adição para dentro do if:
private void btnAbrirFrameActionPerformed(java.awt.event.ActionEvent evt) {
    if (register == null) {
        register = new frameInterno();
        painelDesktop.add(register);
    }

    if (!register.isVisible()) {
        register.setVisible(true);
    }
    register.toFront();
}

Com isso, o erro nao ocorre mais:

1 - fonte: documentação da classe


Type not prefixed in runtime generated WSDL with CXF

Question: I have a Java-first web service, integrated with Spring. The service interface is simple:
@WebService
public interface ContactService {

    public void addContact(@WebParam(name="contact") Contact contact);
    public List<Contact> listContact();
    public void removeContact(@WebParam(name="id") Integer id);
}

The implementation:
@WebService(endpointInterface = "com.foobar.contact.service.ContactService")
@Service
public class ContactServiceImpl implements ContactService {
    // methods
}

The model:
@XmlAccessorType( XmlAccessType.FIELD )
public class Contact {
    private Integer id;
    private String firstname;
    private String lastname;
    private String email;
    private String telephone;
}

If I use the Maven plugin cxf-java2ws-plugin, the WSDL generated is correct. But without specifying the WSDL, the one CXF generates at runtime does not work.
For example, in the one generated by cxf-java2ws-plugin, the return type is properly prefixed with tns:
<xs:complexType name="listContactResponse">
<xs:sequence>
  <xs:element maxOccurs="unbounded" minOccurs="0" name="return" type="tns:contact"/>
</xs:sequence>

In the one generated at runtime, contact is not prefixed, so it cannot be resolved:
<xsd:complexType name="listContactResponse">
<xsd:sequence>
  <xsd:element maxOccurs="unbounded" minOccurs="0" name="return" type="contact"/>
</xsd:sequence>

Both WSDLs do contain the proper complex type contact.
How do I tell CXF/JAX-WS that contact is the type it defined in the WSDL?
Answer: look at the xsd, wich generates automatically with wsdl:
schemaLocation="http://<server>:<port>/<app>/<webservice>?xsd=1


SyntaxError: Unexpected token import - Jest

Question: Hi I am trying setup web components skeleton project with hyperhtml and jest and getting following error while running test cases
import {Component, bind, define, hyper, wire} from 'hyperhtml/esm';
    ^^^^^^
SyntaxError: Unexpected token import

Tried all existing suggestion in stackoverflow for the issue, but no-luck.
Below are my configurations
.babelrc.json
{
"env": {
    "production": {
        "presets": [
            [
                "env", {
                    "targets": {
                        "browsers": ["last 2 Chrome versions", "last 2 Firefox versions", "last 2 Edge versions", "last 2 Safari versions", "ie 11"]
                    },
                    "modules": false,
                    "useBuiltIns": true
                }
            ]
        ],
        "plugins": [
            "transform-object-rest-spread",
            [
                "babel-plugin-transform-builtin-classes", {
                    "globals": ["HTMLElement"]
                }
            ]
        ]
    },
    "test": {
        "presets": [
            ["env", {
                "targets" : { "node" : "current" },
                "modules": "commonjs",
                "debug": false,
                "useBuiltIns": "usage"
            }],
            "stage-0",
            "jest"
        ],
        "plugins": [
            "transform-object-rest-spread",
            "transform-es2015-modules-commonjs",
            [ "babel-plugin-transform-builtin-classes", { "globals": ["HTMLElement"] } ]
        ]
    }
}

}
jest.config.js
module.exports = {
    verbose: true,
    collectCoverageFrom: [
        './src/**/*.{js,jsx}',
        '!**/_tests/**',
        '!**/node_modules/**'
    ],
    testMatch: ['**/_tests/**/*.js'],
    testPathIgnorePatterns: [
        '<rootDir>/node_modules/',
        '<rootDir>/dist/',
        '<rootDir>/demo/',
        '<rootDir>/docs/'
    ],
    testURL: 'http://localhost/',
    moduleNameMapper: {
        '\\.(css)$': '<rootDir>/test-mocks/styles.js'
    },
    moduleDirectories: ["node_modules", "./src"],
    transform: {
        '^.+\\.(js?)$': 'babel-jest'
    }
};

package.json
"scripts": {
...
"test": "NODE_ENV=test jest --no-cache --config jest.config.js",
 ....
 }
"dependencies": {
    "hyperhtml": "2.10.1",
    "hyperhtml-element": "3.1.0",
    "babel-loader": "7.1.4",
    "babel-jest": "22.4.3"
  },
  "devDependencies": {
    "babel-core": "6.26.3",
    "babel-eslint": "8.2.3",
    "babel-preset-react": "^6.24.1",
    "babel-plugin-transform-builtin-classes": "0.6.1",
    "babel-plugin-transform-dynamic-import": "2.0.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "babel-plugin-transform-object-rest-spread": "6.26.0",
    "babel-polyfill": "6.26.0",
    "babel-preset-env": "1.7.0",
    "babel-preset-jest": "^23.2.0",
    "babel-preset-stage-0": "6.24.1",
    "basichtml": "0.16.0",
    "cssnano": "4.1.4",
    "eslint": "4.19.1",
    "eslint-config-airbnb": "17.1.0",
    "eslint-plugin-import": "2.14.0",
    "eslint-plugin-jsx-a11y": "6.1.2",
    "eslint-plugin-react": "7.11.1",
    "jest": "22.4.3",
    "jest-environment-node": "22.4.3",
    "jsdoc": "3.5.5",
    "live-server": "1.2.0",
    "minami": "1.2.3",
    "postcss": "7.0.5",
    "postcss-cssnext": "3.1.0",
    "postcss-custom-media": "7.0.6",
    "postcss-discard-comments": "4.0.1",
    "postcss-easy-import": "3.0.0",
    "postcss-loader": "3.0.0",
    "postcss-mixins": "6.2.0",
    "postcss-nesting": "7.0.0",
    "postcss-reporter": "6.0.0",
    "postcss-selector-not": "4.0.0",
    "prettier-eslint": "8.8.1",
    "sizzle": "2.3.3",
    "stylelint": "9.6.0",
    "stylelint-config-standard": "18.2.0",
    "text-loader": "0.0.1",
    "webpack": "4.8.3",
    "webpack-cli": "3.1.1",
    "webpack-dev-server": "3.1.4",
    "webpack-merge": "4.1.2"
  }

You can find the code in the following repo.
https://github.com/balajiram/webcomponent-elements-app
Comment: edit code block with four spaces. Highlight the code and click the {} button
Answer: If I read "modules": "commonjs" correctly under test preset configuration, it means you should at least try the following instead:
const {Component, bind, define, hyper, wire} = require('hyperhtml/cjs');

You are also using Babel 6 instead of 7, where 7 is better specially for classes and native/built-in extends such as Custom Elements.
If you don't need Shadow DOM (problematic, slow, heavy), I suggest you to use the most deployed polyfill for custom elements, which is document-register-element, the production choice in these years for AFrame, Google AMP, and others.
Last, but not least, this question seems more like a configuration one, so that both web-component and hyperhtml labels here look a bit abused/redundant, since these have literally nothing to do with how you configure your testing environment.
I hope, regardless, to have clarified what is the issue, and what you could improve in general in your project.


Attempting to understand functions in Python

Question: This is an example of a coupled PDE that was solved using finite differences. Can someone tell me how arrh_expr was calculated if the range of temperature in its equation was never defined? I am trying to recreate this solution using a different method, but to do that I need to fully understand this first
import numpy as np

nz = 50
dz = 1 / nz
nt = 50
t = np.linspace(0, 4, nt)

p = np.array([0.01, 0.5, 1.0])

#Initialize concentration and temperature arrays
C = np.zeros(nz)
T = np.zeros(nz)

#Set initial condition for concentration
C[0] = 1.0

#Initialize arrays to store results
c_results = np.zeros((nt, nz))
T_results = np.zeros((nt, nz))

#Define the Arrhenius rate constant function
def k(temperature):
    arrh_expr = 4.68 * np.exp(-806 / ((600 - 273) * temperature + 273))
    return arrh_expr

#Calculate time derivative at specific spatial points
def rhsC(c0, c1, c2, T1, dz, p):
    return (p[0] * (c2 - 2 * c1 + c0) / dz**2 -
            p[1] * (c2 - c0) / (2 * dz) -
            p[2] * k(T1) * c1**2)

def rhsT(T0, T1, T2, c1, dz, p):
    return (0.01 * (T2 - 2 * T1 + T0) / dz**2 -
            0.5 * (T2 - T0) / (2 * dz) +
            2.45 * k(T1) * c1**2)

#Time-stepping loop
for it in range(nt):
    c_results[it, :] = C
    T_results[it, :] = T

    for iz in range(1, nz - 1):
        # Calculate concentration and temperature derivatives
        dc_dt = rhsC(C[iz - 1], C[iz], C[iz + 1], T[iz], dz, p)
        dT_dt = rhsT(T[iz - 1], T[iz], T[iz + 1], C[iz], dz, p)

        # Update concentration and temperature using forward Euler
        C[iz] += dz * dc_dt
        T[iz] += dz * dT_dt

Comment: `T1` is being passed as the `temperature` argument in expressions like `k(T1)`. Calling `k(blah)` passes in the value of `blah` as the value of `temperature` for example. This is how functions work in pure math and any other programming language ever. I recommend maybe starting at some basic tutorials if you've gone this far without that being clear.
Comment: Don't you see `k(T1)` in `rhsC()` and `rhsT()`?
Comment: It looks like `temperature` is just a scalar value being passed in to `k` as an argument. Following the call chain, I see `T1` being used as `temperature` where `k` is called in `rshC`, and that value (`T1`) is passed in from `T[iz]` in the inner `for` loop at the bottom
Answer: A function is a block of code meant to be reused, but to be able to reuse them in more than on case, we allow variables to be passed to them in the form of parameters. Consider the case where you want to create a function that perform the summation of two values, you can define it as
def sum():
    return 4+5

now this function is pretty useless in any case other than summing 4 and 5, so instead it makes since to allow it to sum any two variables, to do this we define a function that takes parameters e.g.
def sum(x, y):
    return x+y

this new function can now be called in the rest of our code by passing any two values as x and y and it will sum them up e.g.
sum(4, 5)
# returns 9

same thing applies here to you code, the function k(temperature) takes a value for temperature and based on it, it calculates the return value


Function in verilog

Question: I used the code below as a function in ModelSim, and it raised the error of 'Global declarations are illegal in Verilog 2001 syntax'. could anyone help me with this?
function [24:0] shiftright(input [24:0] in);
integer i;
begin
if (in)
for (i=0; i<25; i=i+1) begin
    if (i == 24) shiftright[i]<= 0;
    else shiftright[i] <= in[i+1];
end
end
endfunction

Answer: You have written your function outside of a module declaration. All declarations must be inside a module in Verilog. SystemVerilog does allow variables, functions and a number of other things outside of a module.
Also, you cannot use a non-blocking assignment to the return value of a function.

Function in verilog


Server 2012 Cluster - Second Node Can't Ping Items

Question: I've got a server 2012 SQL Cluster and all of the processes failover and run properly. The only odd behavior is that when I fail over to the secondary node, there are certain items on one NIC that can't seem to be pinged by the secondary node. When the primary node is up, I can ping the virtual IP for that NIC just fine, so that NIC has connectivity. The other NICs can ping their respective devices just fine, but this one seems to be behaving oddly. I have seen this with two setups of the same configuration as well.
The network side is just a layer 2 switch, but no Vlans have been applied, so it's basically one big vlan for all of the NICs.
So the problem is that there's an application that runs that talks to devices on that problematic network. Since there's no ping available, there's no traffic, so none of those devices are able to come up on the secondary node. Fail back to the primary and all problems are solved.
Any ideas?
Comment: Ping isn't a cluster or SQL Server validation tool. What's the actual network problem you're having?
Comment: Incorrect. As I stated, this is a SQL Cluster, so items fail over between the hosts (such as the virtual IP for the public/private cluster NICs). So devices should be able to ping back and forth from/to both hosts.
Answer: I have faced the same issue, however the issue got solved when I stopped anti-virus installed in the server from services level.if you have any anti-virus please stop the anti-virus and check whether the issue gets resolved.


Matrices that are simultaneously Hermitian and unitary

Question: My quantum mechanics professor was discussing the properties of Pauli matrices, their being both Hermitian and unitary. Then he made a remark that it is not possible to find three $n \times n$ matrices, where $n > 2$, that are simultaneously Hermitian and unitary. Can someone please explain or give a hint as to why this has to be true?
Comment: It doesn't seem right to me, but maybe your prof had some additional property in mind (or mentioned some additional property which escaped your attention). Anyway, you might find https://math.stackexchange.com/questions/57148/matrices-which-are-both-unitary-and-hermitian enlightening.
Comment: Why three matrices? I strongly suspect he was talking about three such matrices satisfying the su(2) algebra, spin matrix irreps, in which case he'd be right, as per the irreducible representation structure of spin.
Comment: Integral multiples of the identity are not unitary (unless the integer multiplier is $\pm1$).
Comment: I edited the question. Thanks for pointing out.
Comment: What does "simultaneously" mean in your context?
Comment: Any thoughts on the comments and the answer, Kashish?
Comment: He said that the statement was incorrect and that he meant that spins higher than 1/2 have spin observable matrices hermitian but not unitary.
Answer: Three of the four Dirac matrices
$$
\gamma^1=\left(\begin{matrix}0&0&0&1\\0&0&1&0\\0&-1&0&0\\-1&0&0&0\end{matrix}\right)\,,\quad \gamma^2=\left(\begin{matrix}0&0&0&-i\\0&0&i&0\\0&i&0&0\\-i&0&0&0\end{matrix}\right)\,,\quad \gamma^3=\left(\begin{matrix}0&0&1&0\\0&0&0&-1\\-1&0&0&0\\0&1&0&0\end{matrix}\right)
$$
are obviously anti-Hermitian and unitary. Therefore, their multiples with $\pm i$ are Hermitian and unitary.


Connected Graph Proofs

Question: Let $G$ be a connected graph with $n$ vertices and $m$ edges.
a) Prove that $G$ contains at least $m-n+1$ distinct cycles.
My attempt: Induction on $m$
Base Case: $m=n-1$: $G$ is a tree. $m-n+1=m-1-n+1=0$ which follows since a tree has 0 cycles
Inductive Hypothesis: Assume that a connected graph with $n$ vertices and $m-1$ edges has at least $m-1-n+1=m-n$ distinct edges.
Inductive Step: Suppose $G$ is connected with $n$ vertices and $m$ edges.  Let $e$ be in a cycle of $G$.  Then $G-e$ is connected with $m-1$ edges. By the inductive hypothesis, $G-e$ at least has $m-n$ distinct cycles. So $G$ has at least $m-n+1$ distinct cycles.
I'm not to sure about the inductive step (specifically if I can conclude with the last line)
b) Prove that if $G$ is bipartite, then $G$ contains at least $3(m-n+1)+1$ distinct spanning trees.
I'm not too sure if I have the right approach to this but I prove with induction on $m$ again, and I get stuck on the inductive step.  I'm pretty sure I will have to use part a) in some way, but I can't see how.  Any hints would be very helpful
Answer: I think you have the right idea but trying to do it inductively might be making the problem trickier to work with.
Try this: Let $G$ be a connected (simple) graph with $n$ vertices and $m$ edges. Since $G$ is connected, $m\geq n-1$, so let $m = n-1 +k$ for some $k\in \mathbb{Z}_{\geq 0}$. Recall that any connected graph contains a spanning tree $T_0$ as a subgraph, which necessarily has $n-1$ edges and 0 cycles. Let $\{e_1, e_2, \ldots e_k \}$ denote the set of edges not in $T_0$.
Now think about what happens when we add $e_1 = (v_1,v_2)$ into $T_0$. Since $T_0$ is a spanning tree there exists a path from $v_1$ to $v_2$ in $T_0$. Therefore adding $e_1$ to this path will produce a cycle. Let $T_1$ denote the subgraph consisting of $T_0$ with $e_1$.
Now think about adding in $e_2$. You'll see that by the same argument we will produce at least one new cycle, and the resulting graph $T_2$ will have at least 2 cycles. Continuing in this way we see that $G$ itself must contain at least $k$ cycles, but $k = m -(n-1) = m-n+1$ as desired.
For part (b), part (a) tells you that you have at least $(m-n+1)$ cycles. To form a spanning tree, you essentially just have to remove an edge from each of those cycles. Think about how many ways you can do that (remember a bipartite graph has no odd cycles) and you should get your answer.

Connected Graph Proofs


Help with choosing the correct effect size

Question: I conducted a two-way between groups ANOVA to test the impact of video gaming (gamer/non-gamer) and gender (male/female) on reaction time. I'm conducted my analysis using SPSS and received the following result:
https://i.stack.imgur.com/2oQyD.jpg
As you can see, there is no interaction and gender was not significant. However, being a gamer did have a significant impact on response times. I need some help with the effect size. I'm not sure if it's best to use Cohen's criteria (0.01 = small, 0.06 = medium and 0.138 = large) or a different effect size estimate.
0.234 seems ridiculously large in comparison to Cohen's criteria, does this seem right?
I really appreciate your time and help.
Thanks.
Comment: How did you compute .234 and for what purpose ? why Anova? state your purpose?
Answer: Cohen's criteria for labeling effect sizes is abstract and in relationship to the variance rather than into the variable being studied.
Imagine if you will that the difference between means was the same as what you have now, but your variability in measurement was half what it was. Would you consider the effect to be 'larger' in the common sense of the word?
In short, don't get hung up on the ritual of calling an effect size large medium or small. Instead, be sure to (additionally) report the mean differences and SD of those differences. Trust your audience to judge for themselves the 'bigness' of the effect you are presenting.
Also, partial eta isn't Cohen's d.
Comment: Thanks for the reply. Sorry if I wasn't clear. I know that partial eta squared and Cohen's d are separate effect size statistics, what I'd like to know is if I should simply use partial eta squared because that is the output I receive from SPSS, or if I should calculate a different one such as Cohen's d? Also, I'm referring to the SPSS Survival Manual by Julie Pallant which says that Cohen's criteria that I mentioned above can be used to interpret partial eta squared, and my result just seems rather high in comparison. Thanks again
Comment: The choice of an effect size metric is a mixture of tradition and prefered interpretation.  Do you think your results should be about the proportion of variance explained?  If so, use eta.  Do you think your results should be about the magnitude of the difference relative to the variance?  If so, use cohen's d.  For my part, given the choice between the two and the type of study you describe, I'd lean towards reporting cohen's d.


Loading up value from SharedPreferences

Question: In my Application class, I have the following:
public void loadPrefs(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean soundValue = sharedPrefs.getBoolean("SOUND", false);
}

public void savePrefs(String key, boolean value){

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sharedPrefs.edit();
    edit.putBoolean(key, value);
edit.commit();

}

All OK there as far as I can tell.
Now in my main class which extends SurfaceView, I have the following:
myApp mySettings = (myApp)getContext().getApplicationContext();

Then I can save values like so: (Again from my surfaceView activity)
myPlanSettings.savePrefs("SOUND", false);}

However, what I just cannot work out is how to read the value back so I can set a local variable like so:
Boolean thisValue = (the value from the shared preferences).

Thanks for any help
Answer: Try this
public Object loadPrefs(String key,String defaul){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
return  sharedPrefs.get(key,default);
}

Cast it with the type while using getting the value
Basic usage:
boolean b=(Boolean)loadPrefs("value","default value")

Comment: This is generic method you can use for all types of data types don't create each one for the specific type..Create generalised one
Comment: Thanks, I only have 2 Booleans to save so I used something similar to this but didn't use the cast.  Tested and all working :-)

Loading up value from SharedPreferences


Print out the data in batches as insertion order

Question: I have this code to printout all the registered passenger's details:
for(int counter = 0; counter < a; counter++) {
    System.out.println("==============================");
    System.out.println("Name: " + PassengerName[counter]);
    System.out.println("ID Number: " + PassengerIDNum[counter]);
    System.out.println("Mobile Number: " + PassengerMobNum[counter]);
    System.out.println("Temperature in °C: " + PassengerTemp[counter]);
}

This is the output:
==============================
Name: PassengerA
ID Number: 12345
Mobile Number: 23456
Temperature in °C: 36.5
==============================
Name: PassengerB
ID Number: 34567
Mobile Number: 45678
Temperature in °C: 35.4
==============================
Name: PassengerForTesla
ID Number: 5678
Mobile Number: 6789
Temperature in °C: 35.6
==============================

These inputs are grouped into batches.
PassengerA and PassengerB belong to the first batch of input and PassengerForTesla belongs to the second batch input.
As I use Array I can not print those by batches. What's the way to preserve batch information.
Comment: *FYI:* You may want to create a class `Passenger` with the attributes `name`, `idNum`, `mobNum` and so on. Then you won't need to mess around with arrays like that.
Comment: Don't use a for loop if you want to print one entry.
Comment: what do you mean by "first" and "second" input?
Comment: But i don't know how many passenger's information will be entered by the user at the beginning of my code.
Comment: I already have a class for Passenger, so i need to use the getter and setter methods?
Comment: This is a system for user to input the information. For example a family with four person, so this four person will be considered as the first input. When the next people come in, the information entered by the next people (not the family members), it will considered as the second input.
Comment: you need a way to distinguish those groups of people, like an attribute `groupId`. Otherwise, there is no criteria to do it.
Answer: I think it would be best if you create a passenger class like this:
class Passenger {
    private string name;
    private int idNumber;
    private string mobileNumber;
    private int temperature;
    private int inputNumber;

    public Passenger(string name, int idNumber, string mobileNumer, int temperature, int inputNumber) {
        this.name = name;
        ....
    }
    public int getInputNumber() { return inputNumber;}

    public void print(){
         System.println(name);
         System.println(idNumber);
         ....
    }
}

This should solve your problems. You can now have a List of Passengers and print out only the ones with a certain inputNumber. Also for convenience sake I'd put a print() method in the passenger class.
So your for() loop would look something like this:
for (Passenger p: myPassengerList) {
     if(p.getInputNumber() == THE_NUMBER_I_WANT_TO_BE_PRINTED) p.print();
}

The reason for using a list and passenger objects instead of multiple arrays is because storing data which belongs together in the same class is a lot easier to work with and in general it's just a better style of programming.
Hope this was helpful
Comment: For the for-loop, the Passenger p: myPassengerList is the array list?
Comment: Yes, the `for(Passenger p: myPassengerList)` is going through every Passenger in that list (it's called a "foreach" loop). So you have a `List myPassengerList` and with the foreach you go through every Passenger contained in that list.
Answer: You can construct main method logic accordingly, this could be the basic block
import java.util.ArrayList;
import java.util.List;

public class Main {
  static List<List<Passenger>> allPassengers = new ArrayList<List<Passenger>>();

  public static void main(String[] args) {
    Passenger PassengerA = new Passenger("PassengerA", 12345, "23456", 36.5F);
    Passenger PassengerB = new Passenger("PassengerB", 34567, "45678", 35.4F);
    Passenger PassengerForTesla = new Passenger("PassengerForTesla", 5678, "6789", 35.6F);

    List<Passenger> firstSet = new ArrayList<Passenger>();
    firstSet.add(PassengerA);
    firstSet.add(PassengerB);
    allPassengers.add(firstSet);

    List<Passenger> secondSet = new ArrayList<Passenger>();
    secondSet.add(PassengerForTesla);
    allPassengers.add(secondSet);

    for (int i = 0; i < allPassengers.size(); i++) {
      System.out.println("****print " + (i + 1) + " set passengers****");
      print(allPassengers.get(i));

    }

  }

  private static void print(List<Passenger> passengers) {
    for (Passenger passenger : passengers) {
      System.out.println(passenger + "\n");
    }

  }

}

and the Passenger class is
public class Passenger {
  /*
   * Name: PassengerA ID Number: 12345 Mobile Number: 23456 Temperature in °C: 36.5
   */
  String name;
  int id;
  String mobile;
  float temp;

  public Passenger(String name, int id, String mobile, float temp) {
    super();
    this.name = name;
    this.id = id;
    this.mobile = mobile;
    this.temp = temp;
  }

  @Override
  public String toString() {
    return "==============================" + "\nName: " + name + "\nID Number: " + id
        + "\nMobile Number: " + mobile + "\nTemperature in °C: " + temp;
  }

}

out will be
****print 1 set passengers****
==============================
Name: PassengerA
ID Number: 12345
Mobile Number: 23456
Temperature in °C: 36.5

==============================
Name: PassengerB
ID Number: 34567
Mobile Number: 45678
Temperature in °C: 35.4

****print 2 set passengers****
==============================
Name: PassengerForTesla
ID Number: 5678
Mobile Number: 6789
Temperature in °C: 35.6

Comment: based on how you want to print, whether to print last, and all input you may change the logic on main method accordingly
Comment: but the passenger information need to based on the user input
Comment: yes, you must have already know how to get the user input I guess. you need to convert those to passenger object that is explained here(see passenger object creation)
Comment: what is your question? is it about how you going to store input for easy processing, this is the answer. You have to have a Passenger class and an arraylist to store them.
Answer: I dislike posting 2 answers but I can't comment under @Java Newbie's answer (pls someone just give me an upvote or smth, I can only comment with 50+ reputation) so here you go:
Yes, storing an Array inside an Array is possible. It's called a 2D Array and looks like this: String[][] myArray = new String[someValue][someValue]
Although this is possible, I would very much advise against it. It is a lot better to use Lists. The following code might seem a little complex compared to using a 2D-Array but it is in my opinion the best and only proper way to write this code
List<Ride> rides = new ArrayList<Ride>();

public class Ride {
    private List<Passenger> passengers;
    private VehicleInformation vehicleInformation;
    //You need to add a constructor and getters and setters
}

This way you have a Ride which contains a List of passengers and one car (rule of thumb: if your data structure sounds like a sentence someone would say then it's probably good).
Now if you want to know who rode with vehicle XYZ then you can go through the rides List, select all rides with one vehicle and print the passenger informations. This is something you most likely will want to do in the future and it will be a lot harder to do with arrays.
With lists you can go
List<Passenger> passengersOfCarXYZ = new ArrayList<Passenger>();
for(Ride r: rides){
   if(r.getVehicle().getName().equals("XYZ")) passengersOfCarXYZ.add(r.getPassengers());
}

and have all the passengers of a car. It doesn't get much simpler than this.
Using arrays for this is possible but it's the definition of bad coding haha


How to select and insert In Microsoft Access database (accdb) in ASP.NET VB

Question: Hey Everyone I am new to asp.net and I would like to select data from a database and store the data in a DataTable in VB not C#, but I just cant seem to understand how to connect. Can anyone help me try to connect to an access database? I am so lost and have been for days. if not its ok.
Thank you for reading.
Brent
Public Function CheckUser(ByVal p_strUserNAME As String, ByVal p_Password As String) As Boolean
    Dim blnAdminUser As Boolean = False

    Dim SQLQuery As String = "SELECT Username, Password FROM HomelessUsers WHERE Username = " & p_strUserNAME & " AND Password = " & p_Password

    Dim MDBConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\HomelessCapstone\HomelessCapstone\HomelessCapstone\APP_Data\Homeless.accdb;Persist Security Info=True"
    Dim ds As New DataSet
    Dim cnn As OleDbConnection = New OleDbConnection(MDBConnectionString)

    cnn.Open()

    Dim cmd As New OleDbCommand(SQLQuery, cnn)
    Dim da As New OleDbDataAdapter(cmd)
    da.Fill(ds, "HomelessUsers")
    cnn.Close()

    'Dim DatatableTest As DataTable = ds.Tables("HomelessUsers")
    'Dim Row As DataRow = Nothing
    'Dim Item(2) As String

    'For Each Row In DatatableTest.Rows
    'item()
    ' Next

    Return blnAdminUser
End Function

Comment: Show us what have you done so far.
Comment: [Connection Strings.com](http://www.connectionstrings.com/)
Comment: ...and what error are you getting or what isnt working?
Comment: it says like its missing needed paramters?
Comment: "like"??? Is HomelessUsers a table of user names and passwords? You have a fairly useless query. You are asking for the very same things as in your WHERE clause...you shouldnt need to query for what you already know (just drop the WHERE and you'll get a list of all the users). Is the error coming from like the connection portion of from like the execution of the SQL query?  My Magic 8 ball says the SQL query - you need to add ticks to the string params: `WHERE Username = '" & p_strUserNAME & "' AND Password = '" & p_Password & "'"` but it is still like a silly query
Answer: Basically, there are two ways you can go about it.
One is to use ADO (access database objects) which has an intiutive wizard that will help you connect your access database to your program and set datasource for your controls,
Or you can use System.Data.OLEDb (I prefer this as it gives me more control over my system)
Dim accessconn As New  _
System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & pathofAccessFile)
    Try
        accessconn.Open()
        MsgBox("Access succesfully connected")
        accessconn.Close()
        Return 0
    Catch ex As Exception
        accessconn.Close()
        MsgBox("There is something wrong with the path provided.")
    Return 1

    End Try

You will need an understanding of using OLEDb classes though, so here is something to help you out.
http://msdn.microsoft.com/en-us/library/System.Data.OleDb(v=vs.110).aspx
Take note of OLEDbCommand(Execute SQL strings), OLEDbDataAdapter(Translate data from DB to Datagridview) and OLEDbDataReader(I use this for selecting data from the Database).
Perhaps to help you more with understanding your problem, here is an example of how I use DataReader Class:
  Public Sub AccesstoGridd(ByVal utos As String, ByVal pathh As String, ByVal gridd As DataGridView, ByVal ngalan As String)
    Dim accessconn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & pathh)
    Try

        Dim sqlutos As New System.Data.OleDb.OleDbCommand(utos, accessconn)
        Dim idcounter As Integer = 0

        accessconn.Open()
        Dim reader As System.Data.OleDb.OleDbDataReader
        reader = sqlutos.ExecuteReader
        While reader.Read
            idcounter = idcounter + 1
            gridd.Rows.Add(idcounter, reader(0), reader(1), reader(2), reader(3), reader(4), reader(5), ngalan)
        End While
        reader.Close()

        accessconn.Close()
    Catch ex As Exception
        accessconn.Close()
        MsgBox("There is something wrong with the Access file selected." & vbNewLine & ex.ToString, MsgBoxStyle.Exclamation, "MDB file unrecognized.")
    End Try

End Sub

Comment: ok is there any way you could give me an example what goes in dataadapter and Datareader?
Comment: With the code you provided, you just didn't call the functions of the class so that your dataAdapter will work. Also, you didn't create a OLEDBCommand variable as well.
Look at my edit


How to calculate burstiness?

Question: I would like to have some advice on the way to calculate burstiness. I am working with a set of text data, where every term is calculated with their frequency in newspaper for 2 weeks, e.g. "apple" during their iphone4s release will be day1 = 10, day2 = 300, day3 = 25, and so on till day14. So if popular term such as Obama which appear day1 = 100, day2=100, day3=105 ... since it is popular but some other terms which is bursty and spiky will be like "apple" example.
Is there any way that we can measure such burstiness, I am aware of standard deviation, and is there any other ways? The ultimate goal is to make burstiness(Obama) as small as possible and the burstiness(apple) as high as possible. Thanks.
Answer: Try Index of Dispersion, i.e. variance/mean ($D = \sigma^2 / \mu $). It is also known as Fano factor (for your case - with the time window $W=1\text{ day}$).
For Poisson distribution it is just $D=1$ (e.g. if people write post all the time, not related to each other).
For bursty events it is $D>1$ (e.g. there is hype about a product by Apple).
For 'self-avoiding' events $D<1$ (e.g. daily reports; if each day there is the same number of posts, it is just $D=0$).
Comment: Interesting idea.  It seems that "negative bursts" where the frequency suddenly goes *down* would also be detected this way.  It's not clear whether this is intended, but the multiple references to "popular" in the question suggest not: a burst is solely a sudden temporary *increase* in the frequencies.
Answer: A single-day burst will appear as an outlier in the variable's distribution.  There are some established ways to assess whether values are outliers--besides calculating by how many standard deviations they differ from the mean.  One is Dixon's Test (see the notes here).
Comment: Is Dixon test just used to detect a single outlier? Or you are suggesting to calculate number of outliers as burstiness (i.e. more outliers means more bursty?)
Comment: The original ratio test is designed to detect a single outlier.  If there are two outliers it suffers from the masking effect that many outlier detection tests suffer from.  To get around this Dixon modified his test statistic. Instead of [X(n-1)-X(1)]/[X(n)-X(1)] for two outliers he uses {X(n-2) -X(1)]/[X(n)-X(1)].  This eliminated the masking effect that the second outlier has in hiding the first.

How to calculate burstiness?


Strange behaviour with num_rows()

Question: EDIT
For heaven's sake, this is not a duplicate. Do not close it as such. I'm not inquiring about what the error means. I'm more interested in knowing why this is giving me an error in this case while it works fine when used at other places.
For a query such as:
$this->db->select('user_id');
$this->db->from("members");
$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)));
$query = $this->db->get();
if($query->num_rows() == 1)
{
   // some logic goes here
}

I'm getting the following error.

Call to a member function num_rows() on boolean

If I use $this->db->last_query(), I'm getting the following result:
SELECT `user_id`
FROM `members`
WHERE `username` = 'adg'
AND `password` = '3a1c21a559ed42d6ce17c0b8205b6bda2465c2a8'

The query is 100% correct and when run in MySql console, returns an empty set (0 rows) which is fine. But why then is it returning boolean when used in the code.
By the way, I'm using num_rows() on the $query object in various other places and that seem to be working fine.
CI version is 3.1.3
Update

var_dump($query) is printing out bool(false)
Comment: It _is_ about what does it mean - because it means that your query failed. If you pretend that you already knew that, then I would expect that you had been reading up on how to debug _why_ your query failed at this point as well.
Comment: try to use var_dump($query) for see a object
This function prints the variable's content on the page
Comment: Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php)
Comment: You have to get the underlying sql error - till then we can only guess. Btw, your question **is** a duplicate of what @CBroe has linked in, since it contains no MySQL error message and the debugging steps are described in the linked topic.
Comment: @ParagSoni that's not how it works, an _empty_ query result is not an _error_.
Comment: Use like `if($query && $query->num_rows() == 1)` to handle this situation
Comment: @CBroe I beg to differ. It's not about "what does it mean". It's about "why it works in one place but doesn't at the other"
Comment: @ParagSoni Yes, that will solve the issue but my question still remains. Why is this particular instance giving a problem but working fine with other cases?
Comment: num_rows() first perfrom the query then check how many rows
Comment: @CBroe Read the entire OP. The sql query generated is fine. It runs fine in MySql console too. There is no syntax error. This is sort of a bug.
Comment: And `_error_message` and `_error_number` have what to say ...? (Or `error`, depending on CI version.)
Comment: @asprin Because data which match to your query is does not exist, so instead of an object return value is boolean `false` and here you are calling a method of an object as`$query->num_rows()` but without an object it throws an error.
Comment: @asprin Just tip would not use sha1 for password use something like http://php.net/manual/en/function.password-hash.php and to verify it callback http://php.net/manual/en/function.password-verify.php
Comment: @ParagSoni nope, that's not correct.
Comment: please check your autoload.php file.

    $autoload['libraries'] = array('database');
Answer: It's not well documented but when a query fails a boolean might be returned instead of a CI_DB_result object. That is what is happening to you. My first guess as to why it happens in your example is that some piece of data is being improperly escaped - most likely in the where statement. Try this.
$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)), NULL, FALSE);
And see if that helps.
I have, on occasion, when queries are complicated, had to resort to the following check on my results like this.
if($query instanceof CI_DB_result && $query->num_rows() == 1) {...

just to make sure I'm not trying to "Call to a member function num_rows() on boolean"

Strange behaviour with num_rows()


How to adjusting camera to be directly behind the new direction of the model?

Question: I have problem in moving camera behind the car.The camera can not adjusting itself to be directly behind the new direction of the car.
My code:
<code>    Vector3 tmpV = new Vector3();
    Quaternion quatRotation = new Quaternion();
    //chassis is car
    chassis.transform.getTranslation(camera.position);
    tmpV.set(camera.position).sub(5, 0, 5).y = 0f;
    chassis.transform.getRotation(quatRotation);
    camera.rotate(quatRotation);
    camera.position.add(tmpV.nor().scl(-4f)).y = 4.f;
    chassis.transform.getTranslation(tmpV);
    camera.lookAt(tmpV);
    camera.up.set(Vector3.Y);
</code>
It is currently happening when moving right:

What i needs to happen when moving right:
Comment: https://github.com/xoppa/world/blob/master/src/com/xoppa/android/world/ChaseCamera.java see it in action over here: https://www.youtube.com/watch?v=alCLHywqtiI
Answer: By using of this class from this link
that Xoppa posted in the comment:
<code>    camera.desiredLocation.set(new Vector3(0, 5, 5));
    camera.transform=chassis.transform;
    camera.up.set(Vector3.Y);
</code>


Express with API - Can't access inner JSON Object

Question: Here's code from the Riot Developer API.
I want to log the id from the body object in the console.
app.get('/hallo', function(req, res) {
var data = {};
var summoner = "dyrus";
var apikey = "xxxxxxxx";
var URL = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-
name/Teemo?api_key=" + apikey;
var URL2 = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-
name/" + summoner +"?api_key=" + apikey;

request(URL, function (err, data) {
  console.log(data.body);
 })
})

Writing:
console.log(data.body)

Gives me back:
"{"id":34080052,"accountId":37712662,"name":"Teemo","profileIconId":0,"revisionDate":1495767212000,"summonerLevel":6}"

How can I access the id field in the object body?
Comment: Have you tried `JSON.parse(data.body).id` ?
Comment: Ty man, I feel not smart right now... it worked!
Comment: Glad if it helped, sometimes we get stuck on simple problems. I'll put it in an answer.
Answer: you can access it this way:
JSON.parse(data.body).id


creating empty 3 channeled image and add pixel values

Question: I am trying to create empty image, with 3 channels:
heatmap  = np.zeros_like((416,416,3))

Now i want it to act as pseudo heatmap, so i created a box
box = [0,0,25,25]

And now increase value of pixels in this box in the empty image by 1
while( box[0] < box[2]):
    y_axis = int(box[1])
    while(y_axis < box[3]):
            heatmap[box[0]][y_axis] += 1
            y_axis  = y_axis+1
    box[0] = box[0]+1

Using this i get colors but "full"colors, i would need transparent color so i can put this "pseudo heatmap" over image.
How can i acieve this?
Comment: three channels and "I want transparency" does not bode well for your wants. Normally you have 3 channels (BGR, RGB, HVS, etc) and a Transparency value == 4 channels. Transparent =255 is opaque, 0 is translucent, something in between is transparent
Comment: How do you convert this array to an image to overlay elsewhere? Does that overlay function provide transparency? Maybe you must add a 4th channel: alpha.
Comment: I have solved the transparency using cv2.addWeighted(heatmap , alpha, img, 1 - alpha, 0, output), however another question has occured, i will create another topic for the question not to OT. thanks.
Answer: To create a transparent image you need a 4 channel image, 4th channel is representing the alpha channel. To create a transparent image, you can ignore the RGB values and directly set the alpha channel to be 0.
So you can use this:
heatmap  = np.zeros_like((416,416,4),dtype=np.uint8)

Comment: I have solved the transparency using cv2.addWeighted(heatmap , alpha, img, 1 - alpha, 0, output), however another question has occured, i will create another topic for the question not to OT. thanks.


Como DateTime com null?

Question: Basicamente, eu preciso filtrar de uma tabela do banco de dados alguns itens cujo o valor do campo de deleted_at (um campo do tipo DateTime) seja igual a null, exemplo:
Print tirada do banco
Para isso eu usei o seguinte código:

var banks = await context.BanksInstaller
                .Where(x => x.InstallerId == installerId && x.DeletedAt == null)
                .ToListAsync();

Eu sei que isso não é o mais correto a se fazer, mas eu também já tentei de outras formas:
var banks = await context.BanksInstaller
                .Where(x => x.InstallerId == installerId && x.DeletedAt == DBNull.Value)
                .ToListAsync();

Porém nenhuma delas com sucesso
Comment: no c# o Datetime não pode ser null, então é por isso que você não encontra o resultado, talvez setando ele pra nullable (acrescentando o "?" a variavel) você consiga filtrar corretamente.
Answer: O DateTime pode ser recebido como Nullable, nesse caso basta adicionar um ? após o tipo, possibilitando nesse caso ser feita a verificação de != null ou utilizar o atributo HasValue conforme abaixo:
Assim como o @Lucas Miranda mencionou:
DateTime? suaData = null;

if (!suaData.HasValue)
{
    //operação
}

Ou assim já em seu código (se for .net5 ou 6)
var banks = await context.BanksInstaller
                .Where(x => x.InstallerId == installerId && x.DeletedAt.HasValue is false)
                .ToListAsync();

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Resposta bem cirúrgica e direto ao ponto.

Como DateTime com null?


"Home" not changing in Breadcrumbs when switching languages (Locale)

Question: I am using Locale to translate content and menus.
Despite that, even when viewing a page in Spanish, the "Home" link in the breadcrumbs does not change to "Inicio".
What can I do to fix that?
I have attempted to create a node called "Home", translate it to be called "Inicio" and then changed the url to the homepage in the Configuration > Site Information but have still not had any success.
Is there a possibility to fix this without an additional module and a ton of re-configuring?
Thank you.
Comment: Have you customized breadcrumbs in template.php? If yes, then check if "Home" is written in t() function.
Comment: What version of Drupal? What contrib modules (if any) were used to construct breadcrumbs?
Comment: Thank you for the response. @VishalPatil - I have not customized Breadcrumbs at all in the template.php file (The only function I have is for custom page--**.tpl.php")
Comment: Thank you for the response. @oksana-c - I am using Drupal 7 (7.43). I have not used any other modules with it. Simply whatever was generated by default. I assume it is taking Breadcrumbs from the Main Menu. I am not sure if it means anything that my template is a sub-theme based on Zurb Foundation 5.
Comment: Go to "Translate strings" interface, search for "Home" and translate all untranslated instances of that string `/admin/config/regional/translate/translate`. See if that fixes you issue w/ breadcrumbs
Comment: @oksana-c, you are a life saver! Thank you very much! when I searched for "Home", fixing the first result happend to fix the issue I was having:

Home
/es/admin/config/regional/language/configure

Thank you again!
Comment: Awesome! Glad it helped. I posted my comment as an answer, in case anybody else will be looking to solve same task. Also, added some tags to your question.
Answer: Navigate to "Translate strings" interface in "Regional and language" admin section (<code>/admin/config/regional/translate/translate</code>).
Search for "Home" and translate all untranslated instances of that string. This should fix the issue with translation of default breadcrumbs.
Useful tip: strings search is case sensitive, so make sure you enter your strings as they appear in html source (this condition gets easily overlooked).


Capybara undefined method 'create'

Question: In a view I have a link_tohelper that posts to the Commitments controller:
    <%= link_to "Engage in this project",
    commitments_path( {participant_id: current_user.id, participated_project_id: p.id}),
    method: :create %>

When I try to run the following integration-test:
 describe "participating in a project" do
   let!(:project) {FactoryGirl.create(:project)}
   before do
     visit projects_path
     click_on "Engage in this project"
   end
   it "should add that project to the users participated projects" do
    user.participated_projects.should include(project)
   end
  end

… I get the error
 NoMethodError:
 undefined method `create' for #<Capybara::RackTest::Browser:0x007ffcc1072ce8>

The code works in a manual test, however I would like to use Capybara, any ideas=
Answer: :create is not a HTTP method. If your link is a post link, then the method is :post.

Capybara undefined method 'create'


How to show real analyticity without extending to complex plane

Question: Suppose we have some $f \in C^\infty(\mathbb{R},\mathbb{R}).$  For example, $$f(x)=(1+x^2)^{-1}.$$  Using complex analysis, we can easily show $f$ is real analytic.  Is there an easy, general method to show this which doesn't use complex analysis?
Comment: Not really easy, but there are growth conditions for the derivatives that ensure that the remainder term in the Taylor approximation tends to $0$ uniformly in a neighbourhood of the centre of the expansion. Seeing that it's the restriction of a holomorphic function is usually much easier.
Comment: How about $f(x)=\sum\frac{f^{(n)}(0)x^n}{n!}$?
Comment: Not general, but the function $f(x) = (1 + x^{2})^{-1}$ is "obviously" analytic: $g(x) = (1 + x)^{-1} = \bigl[(1 + a) + (x - a)\bigr]^{-1}$ has a geometric series expansion about an arbitrary real number $a$, $h(x) = x^{2}$ is polynomial, and $f = g \circ h$.
Comment: [General, yes; easy, not necessarily](http://en.wikipedia.org/wiki/Analytic_function#Alternative_characterizations)
Answer: The most popular general method is to calculate the general term $f^{(n)}(a)$, and if that's possible, and for every $a$, find an interval $[a-h,a+h]$, such that
if
$$
M_n=\max_{x\in[a-h,a+h]}\lvert \,f^{(n)}(x)\rvert,
$$
then
$$
\limsup_{n\to\infty} \left(\frac{k_n}{n!}\right)^{\!1/n}=L<\infty.
$$
The $M_n$ can be approximated using Taylor expansion remainder.
Answer: Sums, products, quotients, and compositions of real analytic functions are real analytic. So in your example, $1+x^2$ is real-analytic, and so is $1/x,$ hence so is $1/(1+x^2).$


SSH occasionally (rarely) doesn't connect

Question: I've been running this script for a few days:
<code>while [ true ]; do ssh USER@SERVER echo -n . || date +"%s"; done
</code>
Obviously, my terminal is filled with dots, but sometimes (quite rarely) I get this
<code>.......................................................................
.......................................................................
.......................................................................
.......................................................................
.......................................................................
..............ssh: connect to host SERVER port 22: Connection refused
1323454879
ssh: connect to host SERVER port 22: Connection refused
1323454879
ssh: connect to host SERVER port 22: Connection refused
[snip]
1323454879
ssh: connect to host SERVER port 22: Connection refused
1323454879
ssh: connect to host SERVER port 22: Connection refused
.......................................................................
.......................................................................
.......................................................................
.......................................................................
.......................................................................
</code>
I tried this with different server providers, source servers, target servers, time of day, geographic locations. Sooner or later that error comes up for a brief second or two.
Is this to be expected or do I have an issue?
Comment: You're flooding ssh with connections. I am not surprised by this behavior at all. It could be any number of things.
Comment: Is there some reason you haven't put at least a 1 second sleep in that loop?  If you were doing something like that against my servers I would probably blacklist you in my firewall.
Comment: I wait for SSH connections to close, so I am not sure how this is a problem.
Comment: The problem is that you are filling the logs with junk, and probably wasting resources.  Perhaps you can share why you are doing this?  Because it looks extremely wasteful to me.
Comment: are you talking about syslog? How is THAT an issue? If anything, I am not logging enough.
Comment: Initially, the reason I started looking into this was the fact that Nagios would occasionally trigger error on check_ssh, always with different servers.
Comment: You may be triggering the sshd MaxStartups rate-limiter.  See also:
http://serverfault.com/questions/529812/intermittent-ssh-exchange-identification-connection-closed-by-remote-host
Comment: People seem to have fixated on your loop, but of course a quick Google shows people run into random "Connection refused" from ssh in a wide variety of systems and situations. I'm writing a provisioning script for Ubuntu on Linode and get this about 10% of the time. It remains a mystery whether there is a single common cause for most of these, or if the ssh networking milieu is really just generally that fragile and too many things could go (intermittently) wrong.
Answer: This is likely not aberrant behavior but something to be expected.
You may want to check:

firewall rules
anti-brute force tools
ssh configuration

Firewall rules can rate limit SSH connections. I use this in many of my iptables-based firewalls to stifle brute force SSH attacks.  The rules limit then nubmer of new connections to a specified port.
There are tools like fail2ban, denyhosts, and others that may block access after a number of attempts.
Lastly, SSH's configuration (sshd_config) may have a maxium number of servers specified.  If you are rapidly hitting SSH, you may hit this limit.
Comment: I've tried with different servers (CentOS and Ubuntu) and with and without firewalls. All anti-brute force tools (I use bfd) are disabled.
Comment: ssh connections are NOT initialized in the background, so there is no more than one at a time. SSH limit shouldn't be an issue.
Comment: What is an option in sshd_config that would limit the number of servers?  You can limit number of concurrent not yet authed connections, or limit the number of connections per ip, but those would result in "Connection closed by remote host" not "Connection refused"
Comment: @pitr how it initializes is irrelevant.  If the implemented something like [Evan suggested](http://serverfault.com/questions/17870/hundreds-of-failed-ssh-logins/17879#17879) then you would get failed connections.
Answer: This error means that the destination server is reachable, but the port 22 is closed (SSH daemon is not running or running on non-default port).
Another possibility is that you have a firewall between you and the destination server that translates the port 22 to something else not opened on the destination server.
You did not say whether you are getting this error always on the same server or not.
Comment: In this case it would not be on a non standard port as he's looping the connection and it is known to work on port 22.
Comment: This is for more general (hopefully useful) information!
Comment: SSH server is constantly running.

I tried it on different servers, initiating connection from different machines.
Comment: Can you run packet capturing tools like wireshark or tcpdump? This will confirm what you are receiving in both cases.


How to communicate regression model performance to non-stats people?

Question: In R I created a gradient boosted random forest from 100,000 records with 10 cross validation folds using the gbm library. I want to communicate the strength and accuracy of the model, because it worked very well (far surpassing the random forest, kNN or SVM).
There are plenty of strength and accuracy tests (RMS, MAE, etc.) but the one I favor in the work place is correlation, cor(), because it has proven to be the most intuitive for non-stats people.
The correlation between the actual and predicted values was 0.80. I understand that correlation is a measure of linear association, but in this example, it is also a measure of predictive ability. If cor = 1, we are 100% accurate. But is it fair to say we are 80% accurate if cor = 0.80? Or if cor = -1, could we say it is -100% accurate; that doesn't seem right.
So my question is:

For predictive regression models, how are you communicating the
strength and accuracy of the model to non-stats people?
Answer: The squared correlation $R^2$, which in your case would be $0.8^2 = 0.64$, has the interpretation of the proportion of variance in the response that is explained by the model. Note that what counts as a "good" R-square is context-dependent. A physicist might be unhappy with an $R^2$ of 98%, while someone working with social science, business or econometric data might be happy with 50%.


filling a combobox in vbnet when combobox is in a groupbox

Question: I am trying to write a generic routine to fill comboboxes when the form loads.  I get the data from MySql and fill the comboboxes, but it does not work for any combobox inside a groupbox.  Tried passing in formname, groupbox name, comboname byVal and byRef, tried passing in as objects, strings, controls, tried various ctypes and trycast, can't seem to find the magic syntax.  I have a  test form with 2 comboboxes, one outside and one in a groupbox and this code.
Public Function TESTloadComboBoxOrHelp(ByRef formName As Form, ByVal boxName As Object, ByVal callingName As String) ', ByVal groupBx)
    'loadComboBoxOrHelp(me,"comboboxname",me.name)
    'tried passing byVal and byRef, no difference
    'frmCmbTest has 2 combo boxes, one in a groupbox and one not in groupbox, the one NOT in works
    '
    If formName.Name.ToString = "frmCmbTest" Then
        CType(formName.Controls(boxName), ComboBox).Items.Add("ABC") '  1: this WORKS because combobox1 is NOT in a groupbox BUT does not work for combobox2 in groupbox
        frmCmbTest.ComboBox2.Items.Add("ZYZ") ' 2: NOT Generic, this WORKS even though combobox2 is in a groupbox so why does line 1: above NOT work for a groupbox ?
        'formName.boxName.Items.Add("ZYZ")    ' 2.1: this does NOT work even though its the equivalent syntax (didn't expect it to)
        'formName.groupBx.boxName.Items.Add("ZYZ")    ' 2.2: NOPE, Tried passing in the name of the groupbox
        'frmCmbTest.CType(formName.controls("Groupbox1"), GroupBox),CType(formName.Controls.boxName.Name.ToString), ComboBox).Items.Add("DEF") ' 3: so of course this should not work, tried to replicate line above (2:) could not figure out syntax that would work.
        'frmCmbTest.GroupBox1.ComboBox2.Items.Add("ZYZ") ' 4: does not work, as is expected not to.
        'TryCast(formName."GroupBox1".Controls(boxName.Name), ComboBox).Items.Add("MNO") '5: I am guessing I need to add the groupbox name somewhere
        TryCast(formName.Controls(boxName), ComboBox).Items.Add("MNO")  ' 6: out of ideas, works for combobox1 not in groupbox, does not work for combobox2 in groupbox1
    End If
    Return 1
End Function

Currently I have 5 functions, one generic one for filling comboboxes that are not in groupboxes on various forms and the 4 functions that are not generic and its driving me crazy.
Comment: you are making it too complicated.  1) why not just bind the CBOs if the data source is a DB?  2) Barring that, since you want the data to go into a SPECIFIC cbo, write a sub to post the data passing the DS/DT and CBO object reference.  All the find control by formname and control name is confusing you.
Comment: not sure why you are doing this when you only have 1 form? you can just name your combobox and fill it and it does't matter if it is in a groupbox or not. Just plain combobox1.items.add() / combobox2.items.add() should do
Comment: I have several forms and I had not thought of binding it, I am so used to just doing plain old SQL that I didn't think of that.  I will look into it since it makes sense.
Answer: You are dealing with 2 different ControlCollections, since it appears that you are using Windows Forms, the Control Colllection has a Find method that will check if the item is in the parent collection and its Children. It will return an array of all of the matches so make sure that your device names are unique and not a subset of each other. i.e. boxName and boxName1 searching for boxName with give you a result with 2 items
Dim c As Control() = Controls.Find("boxName", True) 'Search for boxName in parent and all child controls
If c.Count > 0 Then                                 'Check to see if we got a match
    CType(c(0), ComboBox).Items.Add("ABC")
End If

Answer: as per my comment to Mark above his answer works !!!
 This is what I ended up (for future reference)
    Public Function TESTloadComboBoxOrHelp(ByRef formName As Form, ByVal boxName As Object, ByVal callingName As String) ', ByVal groupBx)
    'loadComboBoxOrHelp(me,"comboboxname",me.name)
    '
    Dim c As Control() = formName.Controls.Find(boxName, True) 'Search for boxName in parent and all child controls
    If c.Count > 0 Then                                 'Check to see if we got a match
        Try
            conn.Open()
            myCommand.Connection = conn
            Dim query = "SELECT name, lookupValue " _
                    & "FROM lookups " _
                    & "WHERE name = '" & formName.Name.ToString & "." & boxName.ToString & "'"
            myCommand.CommandText = query
            If debug Then evl.WriteToSimpleLog(query, callingName)
            myReader = myCommand.ExecuteReader()
            While myReader.Read
                CType(c(0), ComboBox).Items.Add(myReader.GetString("lookupValue").ToString)
            End While
        Catch ex As Exception
            MessageBox.Show("Error while retrieving records on table Lookups..." & ex.Message, "Lookups Table")
        Finally
            If conn.State = ConnectionState.Open Then conn.Close()
        End Try
    End If

I will try the data binding also that was suggested, I just had not thought of that but this is finally working, I hated my workaround that I had been using


Métodos get e set no java para boolean e char

Question: Estou desenvolvendo um código que utiliza os metodos get e set para entrada e processamento dos dados. O objetivo é entrada com 9 valores cada um com um tipo de dado, mas não estou conseguindo fazer as conversões para o tipo char e para o tipo boolean.
package javaapplication2;

public class Geladeira {
    char classificacao;
    short garantia;
    String cor;
    int voltagem;
    long totalLitros;
    double preco;
    float consumo;
    byte puxadores;
    boolean iluminacao;

    //Metodo setter
    public void setClassificacao(char c){
        classificacao = c;
    }

    public void setGarantia(short g){
        garantia = g;
    }

    public void setCor (String a){
        cor = a;
    }

    public void setVoltagem(int v){
        voltagem = v;
    }

    public void setTotalLitros(long t){
        totalLitros = t;
    }

    public void setPreco(double p){
        preco = p;
    }

    public void setConsumo(float con){
        consumo = con;
    }

    public void setPuxadores(byte px){
        puxadores = px;
    }

    public void setIlumincao(boolean i){
        iluminacao = i;
    }

    //Metodo getter
    public char getClassificacao(){
        return classificacao;
    }

    public short getGarantia(){
        return garantia;
    }

    public String getCor(){
        return cor;
    }

    public int getVoltagem(){
        return voltagem;
    }

    public long getTotalLitros(){
        return totalLitros;
    }

    public double getPreco(){
        return preco;
    }

    public float getConsumo(){
        return consumo;
    }

    public byte getPuxadores(){
        return puxadores;
    }

    public boolean getIlimunacao(){
        return iluminacao;
    }

    void getGarantia(short parseShort) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

E:
package javaapplication2;

import java.util.Scanner;

public class Principal {
    public static void main (String[] args){

        Scanner SC = new Scanner (System.in);

        Geladeira dadosG = new Geladeira();

        System.out.println("Digite a classificação energética: ");
        dadosG.setClassificacao(SC.next());

        System.out.println("Digite a garantia: ");
        dadosG.setGarantia(Short.parseShort(SC.nextLine()));

        System.out.println("Digite a cor: ");
        dadosG.setCor(SC.nextLine());

        System.out.println("Digite a voltagem: ");
        dadosG.setVoltagem(Integer.parseInt(SC.nextLine()));

        System.out.println("Digite o total de litros: ");
        dadosG.setTotalLitros(Long.parseLong(SC.nextLine()));

        System.out.println("Digite o preço: ");
        dadosG.setPreco(Double.parseDouble(SC.nextLine()));

        System.out.println("Digite o consumo: ");
        dadosG.setConsumo(Float.parseFloat(SC.nextLine()));

        System.out.println("Digite a quantidade de puxadores: ");
        dadosG.setPuxadores(Byte.parseByte(SC.nextLine()));

        System.out.println("Digite 1 se exitir ilimuninação interna ou 0 caso não exista: ");
        dadosG.getIlimunacao(Boolean.parseBollean(SC.nextLine()));

    }

}

Comment: `parseBollean` está mal escrito, e espera que seja escrito `true` ou `false` e não `0` ou `1`. Sempre que estiver na duvida [confirme na documentação](https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#parseBoolean(java.lang.String))
Answer: Você pode usar o next com regex:
// Aceita um caracter de a até f
dadosG.setClassificacao(SC.next("[a-f]").charAt(0));

// Aceita um caracter de 0 até 1
dadosG.setIlumincao(!SC.next("[0-1]").equals("0"));

Lembrando que você precisa tratar a exceção de InputMismatch, caso o que o usuário digite não seja o que você espera.


Fetch and print request body using ContainerRequestContext

Question: I have the below code using which I am trying to fetch and print the request stream's entities using ContainerRequestContext. However, its breaking the API call after I read the input stream. I am able to fetch other details from "ContainerRequestContext" using getters such as responseContext.getURiInfo() etc. Please note I dont want to use "aroundReadFrom" of "ReaderInterceptor" and Lombok anywhere. Any help is appreciated. Thanks !!
UPDATE:
The request payload is "x-www-form-urlencoded" and how do I set the request payload back to "x-www-form-urlencoded" after reading it ? It might be the reason why the request fails after I read the payload. I might not be setting the "setEntityStream()" correctly.

public String getRequestEntityStream(ContainerRequestContext requestContext) throws IOException {

        try (InputStream in = requestContext.getEntityStream()) {
            ByteArrayOutputStream out = new ByteArrayOutputStream(64 * 1024);
            IOUtils.copy(in, out);
            byte[] entity = out.toByteArray();
            //restore input
            requestContext.setEntityStream(new ByteArrayInputStream(entity));
            String str=new String(entity);

            return str;
        }
    }

I am using the above as below to append to StringBuilder :

@Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        StringBuilder sbRequest = new StringBuilder();

        sbRequest.append(" - Request Entity Stream : ").append(getRequestEntityStream(requestContext));

    }
Comment: From the code, the problem might be caused by different implementation of InputStream. You might try using the same implementation for setEntityStream and recheck.
Comment: Thanks, The Input stream is "x-www-form-urlencoded " . After reading the payload of the inputStream how to encode it back to "x-www-form-urlencoded " - Thts where i am stuck.
Comment: what is the real implementation? have you tried using wrapper to help to ready body multiple times: https://stackoverflow.com/questions/4449096/how-to-read-request-getinputstream-multiple-times?noredirect=1&lq=1
Comment: I am using "ContainerRequestContext" to intercept the request payload. I am not using a wrapper here and hence the implementation is not "HttpServletRequestWrapper".
Answer: The reason you are getting null when trying to fetch the request stream's entities using ContainerRequestContext is that the input stream is being read and consumed when you call IOUtils.copy(in, out).
Once the stream is read, the stream pointer reaches the end of the stream, and there are no more bytes left to read. Hence, when you try to access the request entity stream using requestContext.getEntityStream() after the input stream is read, it returns null.
To fix this issue, you can create a new instance of the ByteArrayInputStream using the entity byte array and set it back to the ContainerRequestContext using requestContext.setEntityStream() before returning the entity string. This will ensure that the request entity stream is reset to its initial state, and you can access it again if needed.
Try this please :
public String getRequestEntityStream(ContainerRequestContext requestContext) throws IOException {

    try (InputStream in = requestContext.getEntityStream()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream(64 * 1024);
        IOUtils.copy(in, out);
        byte[] entity = out.toByteArray();

        //reset the input stream
        ByteArrayInputStream inNew = new ByteArrayInputStream(entity);
        requestContext.setEntityStream(inNew);

        String str = new String(entity);
        return str;
    }
}

Comment: Thanks for your response. Unfortunately It didnt work. Probably I will have to just read the input stream without converting to byteArray. This will ensure that the dataType of Input stream is not messed.


why $C_{2}[a,b]$ is an inner product space under the given inner product, while $C[a,b]$ is not?

Question: I could not see the problem here How can I prove if this is an inner product? as the calculation of the inner product is 1 with me, and also why $C_{2}[0,1]$ is an inner product space with the inner product defined by
$<f,g>=∫_{0}^{1}f(x)\bar g(x)dx$
, what is the difference?
Comment: The inner product in the linked case has the derivative of $f$ under the integral. So if $f\equiv 1$ then $\langle f,f\rangle = \int_0^1 f'(x) f(x) dx = \int_0^1 0 \times 1 d x = 0$. $C[0,1]$ would be an inner product space with the inner product that you describe.
Comment: Yeah, I can see how that could be confusing lol.
Comment: @TrevorNorton  I thought it is the conjugate not the derivative ....... hahaha
Answer: The linear space $C[a,b]$ of continuous functions on $[a,b]$ is an inner product space under $\langle f,g\rangle = \int_{0}^{1}f(t)\overline{g(t)}dt$. The only property in question is whether $\langle f,f\rangle =0$ iff $f=0$. But this property follows easily from the Fundamental Theorem of Calculus. For suppose
$$
   \int_{0}^{1}|f(t)|^2dt = 0.
$$
Then $\int_{0}^{x}|f(t)|^2dt=0$ for all $0 \le x \le 1$ because
$$
 0 \le \int_{0}^{x}|f(t)|^2dt \le \int_{0}^{x}|f(t)|^2dt + \int_{x}^{1}|f(t)|^2dt = \int_{0}^{1}|(f)|^2dt = 0.
$$
$|f(t)|^2$ is continuous because $f$ is. Hence, $0=\frac{d}{dx}\int_{0}^{x}|f(t)|^2dt=|f(x)|^2$ for all $x$.
The linear space $C_2[0,1]$ is also an inner product space under the same inner product.
Note that neither space is a Hilbert space; the completion of either space is $L^2[0,1]$.
Comment: @Idonotknow  $L^2$ consists of equivalence classes of Lebesgue measurable, square integrable functions on $[0,1]$, grouped by the equivalence relation that the functions are equal a.e. with respect to Lebesgue measure. There should be a proof in most Functional Analysis texts.
Comment: Is the there is a link for the proof that $L^2[0,1]$ is complete on this site?
Answer: The normed space is an inner product space if and only if the parallelogram law holds. This is Jordan-von Neumann Theorem (1937). Check whether or not the parallelogram law holds in $C[0,1]$.
Comment: I know that it does not hold ..... it is written in Kreyszig ..... but why the other space is an inner product ?
Comment: Because in $L_2$ (yes, the notation should be like that, we consider the functions integrable with a square) all the axioms are fulfilled. For instance, let $\langle f,f\rangle=0$. Then $\int_0^1 |f|^2 dx=0$ which means that $f=0$ almost everywhere. This is OK since $L_2$ is a space of equivelence clesses of functions equal almost everywhere. Try to check the remaining axioms.
Comment: But the other space is $C_{2}$ not $L_{2}$, what is the relation between them? ... what is the space $C_{2}$?