k8s - Cinder "0/x nodes are available: x node(s) had volume node affinity conflict"

Question: I have my own cluster k8s. I'm trying to link the cluster to openstack / cinder.
When I'm creating a PVC, I can a see a PV in k8s and the volume in Openstack.
But when I'm linking a pod with the PVC, I have the message k8s - Cinder  "0/x nodes are available: x node(s) had volume node affinity conflict".
My yml test:
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: classic
provisioner: kubernetes.io/cinder
parameters:
  type: classic

---

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-infra-consuldata4
  namespace: infra
spec:
  storageClassName: classic
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: consul
  namespace: infra
  labels:
    app: consul
spec:
  replicas: 1
  selector:
    matchLabels:
      app: consul
  template:
    metadata:
      labels:
        app: consul
    spec:
      containers:
      - name: consul
        image: consul:1.4.3
        volumeMounts:
        - name: data
          mountPath: /consul
        resources:
          requests:
            cpu: 100m
          limits:
            cpu: 500m
        command: ["consul", "agent", "-server", "-bootstrap", "-ui", "-bind", "0.0.0.0", "-client", "0.0.0.0", "-data-dir", "/consul"]
      volumes:
      - name: data
        persistentVolumeClaim:
          claimName: pvc-infra-consuldata4

The result:
kpro describe pvc -n infra
Name:          pvc-infra-consuldata4
Namespace:     infra
StorageClass:  classic
Status:        Bound
Volume:        pvc-76bfdaf1-40bb-11e9-98de-fa163e53311c
Labels:
Annotations:   kubectl.kubernetes.io/last-applied-configuration:
                 {"apiVersion":"v1","kind":"PersistentVolumeClaim","metadata":{"annotations":{},"name":"pvc-infra-consuldata4","namespace":"infra"},"spec":...
               pv.kubernetes.io/bind-completed: yes
               pv.kubernetes.io/bound-by-controller: yes
               volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/cinder
Finalizers:    [kubernetes.io/pvc-protection]
Capacity:      1Gi
Access Modes:  RWO
VolumeMode:    Filesystem
Events:
  Type       Reason                 Age   From                         Message
  ----       ------                 ----  ----                         -------
  Normal     ProvisioningSucceeded  61s   persistentvolume-controller  Successfully provisioned volume pvc-76bfdaf1-40bb-11e9-98de-fa163e53311c using kubernetes.io/cinder
Mounted By:  consul-85684dd7fc-j84v7
kpro describe po -n infra consul-85684dd7fc-j84v7
Name:               consul-85684dd7fc-j84v7
Namespace:          infra
Priority:           0
PriorityClassName:  <none>
Node:               <none>
Labels:             app=consul
                    pod-template-hash=85684dd7fc
Annotations:        <none>
Status:             Pending
IP:
Controlled By:      ReplicaSet/consul-85684dd7fc
Containers:
  consul:
    Image:      consul:1.4.3
    Port:       <none>
    Host Port:  <none>
    Command:
      consul
      agent
      -server
      -bootstrap
      -ui
      -bind
      0.0.0.0
      -client
      0.0.0.0
      -data-dir
      /consul
    Limits:
      cpu:  2
    Requests:
      cpu:        500m
    Environment:  <none>
    Mounts:
      /consul from data (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-nxchv (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  data:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  pvc-infra-consuldata4
    ReadOnly:   false
  default-token-nxchv:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-nxchv
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason            Age                  From               Message
  ----     ------            ----                 ----               -------
  Warning  FailedScheduling  36s (x6 over 2m40s)  default-scheduler  0/6 nodes are available: 6 node(s) had volume node affinity conflict.

Why K8s successful create the Cinder volume, but it can't schedule the pod ?
Comment: What k8s version are you running?
Comment: Hi,
Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.3", GitCommit:"721bfa751924da8d1680787490c54b9179b1fed0", GitTreeState:"clean", BuildDate:"2019-02-01T20:00:57Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"}
Answer: Try finding out the nodeAffinity of your persistent volume:
$ kubctl describe pv pvc-76bfdaf1-40bb-11e9-98de-fa163e53311c
Node Affinity:
  Required Terms:
    Term 0:        kubernetes.io/hostname in [xxx]

Then try to figure out if xxx matches the node label yyy that your pod is supposed to run on:
$ kubectl get nodes
NAME      STATUS   ROLES               AGE   VERSION
yyy       Ready    worker              8d    v1.15.3

If they don't match, you will have the "x node(s) had volume node affinity conflict" error, and you need to re-create the persistent volume with the correct nodeAffinity configuration.
Answer: I also ran into this issue when I forgot to deploy the EBS CSI driver before I tried to get my pod to connect to it.
kubectl apply -k "github.com/kubernetes-sigs/aws-ebs-csi-driver/deploy/kubernetes/overlays/stable/?ref=master"


How to turn *argv[] into a string inside isaplha

Question: New to programming C++ and am having an issue with using isaplha to recongnize and display an error message when an argument is a letter. A, A1, and any combination of alpha-numerals starting with a letter displays an error, how ever 1a will pass as containing no letters. My code is as follows.
for(int s = 1; s< argc; s++)
{
    if (isalpha(*argv[s]))
    {
        cout << "You have entered a letter, however letters are not valid arguments";
    }
    else etc... etc...

Any help would be appreciated!
Comment: @Welshboy `argv[s]` is a char array. `*argv[s]` is a char. You can't check `isalpha` on an array.
Comment: You'll have to iterate over the char-array. What happens now is that you take the n-th argument (`argv[s]`) and dereference that (pointer to the first character of the n-th argument).
Comment: *argv[s] is the first character of the argument, so you're not checking subsequent letters at all.
Comment: I don't think you need the * before argv, you can just do isalpha(argv[s]) I think...
Comment: I don't understand what your expected behaviour is, exactly - do you want to treat any string containing a letter (uppercase or lowercase) to yield an error message?
Comment: @zenith ah, I stand corrected, thanks for the correction.  Appreciate it.
Answer: // Store args in a vector of strings for ease of use (excluding first arg)
auto args = std::vector<std::string>{argv+1, argv+argc};

// Iterate through each argument
for(auto& arg : args)
{
    // If any of the characters in arg (a string) are alpha
    if(std::any_of(arg.begin(), arg.end(), std::isalpha))
        /*...*/
    else
        /*...*/
}

Answer: Break it down into pieces.
argv[1] is the first command-line parameter.
(argv[2] is the second, and so on...)
It has a length, determined by strlen.
Iterate over that length, checking each character:
int main(int argc, char* argv[])
{
    char* Param1 = argv[1];

    for(int s = 0; s< strlen(Param1); s++)
    {
        if (isalpha(Param1[s]))
        {
            cout << "You have entered a letter, however letters are not valid arguments";

Answer: Since argv is an array containing C-strings, argv[s] is a C-string, and *argv[s] (which is equal to argv[s][0]) accesses only the first character in that string.
If you want to check that there are no letters in the entire char array, you'll have to loop through that array too:
for(int s = 1; s < argc; s++) // loops through the array of C-strings
{
    for(int c = 0; c < strlen(argv[s]); c++) // loops through each C-string
    {
        if (isalpha(argv[s][c]))
        {
            cout << "You have entered a letter, however letters are not valid arguments";

Comment: Do you mean strlen(argv[s])?
Comment: Yeah I fixed that one ages ago ;)
Comment: @Sam Bianco At least do `if (std::any_of(argv[s], argv[s]+strlen(argv[s]), isalpha))`. There is a movement these days not to write your own loops whenever possible. Using std algorithms reads better, like english "if any of the [chars in a string] are alpha". That said, use my answer instead, below.


How to Practice Torrent Etude (Chopin, Op. 10 no. 4) measure 2

Question: Even though I got my ARCT 5 years ago and can stretch to reach a 10th, simply put, the torrent etude is the hardest etude I have come across played at the right speed, true presto, like how Richter did. At that speed, I have played all the other parts correctly but somehow the right hand in the start of the 2nd bar always gets me.
How can I practice that in a way that accounts for the physiology of the hand? Some people suggest playing it EXTREMELY slow, but it doesn't work as I tried that for 3 months already and there's no improvement. I then tried playing it at Richter's speed for that section for 2 months, and in each practice session there were a few tries hitting the correct sequence of notes, but it isn't consistent, no clear improvement until I tapered from doing that for 1 month. I can then play the section with greater accuracy at high speeds for 3 days, but the next few days I couldn't do it. The tapering process is too slow.
Some people suggested tapping on the table, but clearly, tapping on the table with a book the same height as the note's pressed depth doesn't work both when lifting the fingers to tap and no lifting of the fingers. Also, I've tried all sorts of different positions for the section but sometimes they work and sometimes they don't, and it's not a problem with strength because I don't work out my forearms AND I found that power napping helps with playing it at high speeds in a controlled manner (power napping relaxes certain muscles and improves others); hence, it's a problem with muscle activations – but the muscle/joint movements are extremely subtle, simply practicing trilling doesn't work.
My question is, for people who know hand anatomy very well, how can I improve the torrent etude? Or is there a more general tactic like power napping to focus on muscle activation for that specific section? I mean, I really want to get this section right so I can carry on with other pieces, and at times I can play it at high speeds in a controlled and accurate way, but it isn't consistent.
Some more information: I notice when playing at the position of the "controlled accurate way" which is the slight bend of the second finger joint in anticipation of the next part and immediate bend of the fifth finger joint upon the fourth finger hitting, sometimes my middle finger doesn't activate after the fourth finger hitting, but it always activates when the fifth note doesn't get hit, so 2343 is accurate at high speeds, not 23435. Possibly it is the stretch that makes it hard for me compared to Richter's massive hands. Also, 3435 with both the second finger holding the note down and second finger pointing horizontally is accurate at high speeds (however, I did notice that my middle finger in this case moves a little laterally to press the second time, maybe it uses the interossei instead of the fdp? Maybe I should focus on practicing middle finger pressing down straight, so to activate the other muscle), but just not 23435 – it's the combination 23435 that hinders me, when broken down into specific parts such as 3435 and 2343 it works quite well. But somehow, I managed to pull the section off at Richter's speed 5 times in a row accurately and in a controlled way in the 3 days after taper, so it's doable, I think.
Comment: I'm voting to close this question because in its current form, as a purely anatomical/physiological question, it's a question for a physical or occupational therapist.
Comment: Just to clear up potential confusion, I think you are referring to "bar 2." The pickup bar doesn't count as a bar (see any edition with bar numbers).
Comment: You're having trouble with bar 3 right hand, but could play all other parts in the entire piece with no problem? What about bar 7 left hand? Or bar 11, 53, and 61 right hand? Those are some other where the same figure as bar 3 right hand occurs. How is it that you could play those parts, but can't play bar 3?
Comment: I don't know, but all the other parts are alright, just bar 3 right hand and its repeated parts.
Comment: my fingering for that part is also what Richter did (third-fourth-third-fitfth-second-third-second-fifth-first-third-second-fifth)
Comment: I'm unclear on whether you're asking about bar 2 or bar 3. Bar 2 is the one with the repeated high C#; Bar 3 is the one with the wide broken chords in tenths.
Comment: @Aaron it's bar 2, bar 3 is easy for me
Comment: Reading through the question again with your update, as well as the various other posts and comments, it sounds like what you're really looking for is an explanation of the anatomy/physiology involved in the passage. Is that a fair interpretation?
Comment: @Aaron yes, I want to know an explanation to my inconsistency in a physiological way so I can practice the right way
Comment: Got it. I've updated my answer to explicitly address how it relates to physiology. (I've also updated your question to clarify the emphasis, but the changes can be rolled back if you feel they don't properly express your intentions.)
Answer: Some unorganized thoughts:

If you really want help, you should see a teacher (even if over a video call). Even if you shared a video with us, it would still be difficult to assess why you are not being able to play that passage without the interaction of a real conversation. Your post is quite detailed, but it would still take a lot of guesswork for us to pinpoint the root of your problem.
Not directly relevant Josh Wright has a video that may be helpful to you. At 2:24 he mentions an alternate fingering that you might try.
The fingering that Richter uses (that you mention in the comments) can be quite difficult and potentially injurious if you are not playing correctly. Although it may seem economical in the sense that your hand/arm does not need to move laterally very much, this just means your small finger muscles have to do a lot of work, especially at a fast tempo. If you insist on using this fingering, remember to move your hand/arm to the right as you hit the 5th finger notes, rather than stretching the 5th finger out. Stretching the fingers causes tension and will inhibit you from playing faster. Use the large muscles in your arm so that the small muscles in your fingers have to do less work. It might seem counterintuitive ("why should I waste large arm/hand motions on such a small movement?") but it is much easier to make movements with the arm than by stretching fingers. Some teachers teach this arm motion using the cue of "leading with the elbow," i.e. before you reach the 5th finger note, you have already started moving your elbow outward to initiate a nice circular motion heading to the 5th finger and then back left. Note that these movements don't have to be huge or even visually noticeable, but it may help to exaggerate at first to get the feeling, and then minimize it later once you feel more comfortable.
That said, I think you should explore other fingerings, like Josh Wright's. Another one that appears in the Henle edition is the following. Using 3-4-2-5 in the beginning of the measure instead of 3-4-3-5 does two things: it avoids the difficult 3-4-3 trill, and also gives you an opportunity to reposition your arm rightward using the 2nd finger to prepare for the 5th finger.
If you are struggling with a passage, fast practice will not do you any favors (actually it might just make things worse, as it will build bad habits). On the other hand, if genuinely did slow practice for 3 months and could not find any improvement, then something deeper must be wrong. (Again, a teacher would be the best way to diagnose.) When doing slow practice, make sure you are completely concentrating on every aspect. Your body should be completely relaxed and you should be feeling every in and out of the passage for ergonomical comfort. As you gradually increase the tempo, keep this ideal comfort in mind, and the difficult spots will reveal themselves so that you can focus on making those parts more comfortable at a slow tempo before increasing the tempo.
One thing you can do to make slow practice more interesting/challenging: Playing alternate rhythms or phrasing can help your brain focus in on awkward parts of the passage. For example, putting pauses in certain points in the bar like the following, or grouping in groups of 3s instead of 4s, as follows.
Your comment about activating the middle finger reminded me of this: make sure your palm is not too low to the keys. When your palm is low, your fingers need to "cock back" (pull upward/backward) before striking, and this motion is is relatively difficult because it is near the limit of the range of motion of your fingers. If your palm is higher, your fingers are in the middle of their range of motion, and it is easier to initiate the downward motion.
Comment: Hey thanks for the reply! However, for your suggested fingering, it just makes it even more difficult to play at high speeds since I tried it for a few weeks. About the arm movements, it wouldn't work as well – have you tried playing it? And for the slow tempo, there's no one-size-fits-all rule for it always working, my previous music teacher is big on that but I think more generally, accurate comfort is the thing we should seek after, regardless of speed. Bad habits developing when playing things wrong? At this level, I think this can only occur in coordination problems.
Comment: Also, I'm not sure if a teacher is the best way to go, unless they know hand anatomy and its practical applications – at this level, I expect a lot for a teacher. However, I did notice my middle finger doesn't activate that fast all the time, perhaps that's the root of the problem? Coupled with my fourth finger possibly throwing it off balance when hitting the key preceding it?
Comment: I personally use the fingering 3425132513251215.
Comment: @SunlightScreen I added another note to my answer regarding activating the finger.
Comment: @SunlightScreen I'm not quite sure what kind of answer you are expecting to get without even showing how you are playing the passage. I have no way of knowing whether my suggestions are relevant because I don't have a clear picture of what you are struggling with, nor do I have any way to convince you that my suggestions (which you dismiss) could be helpful to you because this site isn't conducive for extended discussions and video demonstrations. I really suggest you see someone in person. A good piano teacher will definitely know about hand anatomy and how to work on specific hard passages.
Comment: @angryavian I guess I'm looking for someone who has played the etude before and has played that passage as fast as Richter, it will be great if Nikolay Leschenko can comment if he is interested at all.
Answer: @angryavian covers a variety of excellent suggestions. In addition,
a fingering suggestion...
Fingers 3 and 4 have overlapping tendons. This makes it difficult to play the two in rapid succession, especially when one of them must be repeated (3-4-3 or 4-3-4). This can be seen in the "Finger extensor" illustration, on the website for the American Society for Surgery of the Hand.
One way around that physiological reality is, when arriving in measure 2, try 3-1-3 for the first three notes. It allows for speed, naturally brings finger 5 to the C#, and leaves fingers 2-3-5 in a good position for the next grouping.
...and two related practice suggestions.
Another aspect of playing very quickly, especially if a finger must be activated more than once, is that the effort of playing that finger doesn't get fully released, or released quickly enough, for the re-attack.
These exercises are designed to address the minutiae of relaxation and exact finger placement (an imprecision which can also slow one down). They are independent of the fingering chosen for the passage.

Begin by practicing in pairs as block chords. The emphasis is on landing cleanly (relaxed, and without requiring even micro-adjustments to finger/hand/arm positions) on the second chord of the pair.
a. Play [G# A C#] together as a block, staccato. Use the fingering you plan normally to play with. Spring off the keys as though leaping to the next chord. Your hand/arm should make a smooth parabolic arc; no direction changes or other adjustments.
b. Land on [F# G# C#], again as a block, but this time let your hand and arm come to rest on that chord, so that any effort from the "leap" is released. Make sure you land "cleanly": that is, no small finger or hand position adjustments. Even the smallest adjustment will throw you off at speed, so one must be able to get from chord to chord in exactly one fluid motion.
c. First, practice each pair individually until you can land cleanly. Then practice consecutively, landing on a chord, then replaying it to leap to the next chord -- again, until each landing is clean. Finally, leap through all four chords without pause, finally landing/relaxing on the downbeat of the next measure.

Similar to #1, but now as written.
a. Play the first four-note grouping of the bar, at speed (or faster), landing (and coming to rest/relaxing) on the first note of the next grouping. Make sure all fingers land cleanly on their respective notes in that grouping, but only actually play the first note.
b. As with #1, practice group 1 to the first note of group 2 until clean; then group 2 to group 3, etc. Always ensure that although you only land with the thumb, the other fingers must land cleanly on their respective keys. Then practice through all groups, landing on the downbeats, relaxing, and replaying the downbeat pitch for the next group-move.


How can I label and store (n) number of (a) inputs like a1, a2

Question: <code>#include <iostream>
using namespace std;
int n, a, k;
main(){
cin>>n;
for(k=1; k<=n; k++){
cin>>a;}}
</code>
how can I store inputs to use them in future operations, I'm beginner programmer, I'm looking for easiest way for that.
Comment: Welcome to Stack Overflow! What you want is called an array, or a `std::vector`.
 That said, it sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)
Comment: Please format your code with tabs, it is good to know the good practice ince the beginning.
Comment: You are looking for something like `array` or `vector`.
Comment: Related question: https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c
Comment: Possible duplicate of [How do I use arrays in C++?](https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c)
Answer: If you want to read n integers you can use a vector:
<code>#include <iostream>
#include <vector>

int main()
{
   int n;
   std::vector<int> vec;    //Better try to use namespaces
                            //Some spaces add clarity
   std::cin >> n;
   vec.resize(n);

   for(int k=0; k<n; k++)   //Define local varibales relative to loop for iterator
   {
      std::cin >> vec[k];
   }

   return 0;      //Always return a code at the finish of the program
}
</code>
Comment: btw there is no need for globals and `using namespace std;` is also best avoided right from the start, but well... the worst mistake is gone
Comment: Please format your code with tabs, it is good to know the good practice since the beginning.
Comment: dv taken back. Better make comment on that, as OP might miss this tiny change with bad consequences
Comment: Thank you for the observation @Adrian, I change my code to other better one.
Comment: @MauricioRuiz Excellent! I hope you can forgive the sarcastic nature of my comment!
Comment: "Always return a code at the finish of the program" - `main` is special in that not returning anything is equivalent to returning 0. Some people might consider it good practice to explicitly write that, but it's not necessary.


Do 1/2 size violins sound at normal pitch?

Question: With wind instruments, young kids with small hands are often advised to start on smaller instruments (e.g. Soprano Sax, Eb Clarinet) before moving to full-size instruments. (Terrible advice IMO, but that's a different thread!)
These instruments sound in a different key to their 'full-size' counterparts, so are often inconvenient for teachers, or in group settings.
My understanding is that many young violinists also start on a 1/4 size, or 1/2 size violin. Are these instruments also in a different key to full-size violins? And if not, how does that work? As surely the strings must be shorter?
Comment: I agree with what you say about saxes and clarinets. I must confess I don't know any wind teachers who start children on soprano sax or Eb clarinet. My colleagues seem to start them on alto and Bb, but usually after having used recorder to develop a basic wind technique. I'm not a wind player though...
Comment: I'd hope no good teacher would, Bob! But it's something I've seen a few times before, and some instruments are marketed as such, e.g. [link](http://www.johnpacker.co.uk/Catalogue/Woodwind/Clarinet/Harmony-Clarinets/Eb-Clarinet/Student/JP123-Clarinet-Eb-Ebonite-Nickel-Plated-Keys-101792#.VF5VjjSsX0w). (Starting someone on an Eb clarinet is just cruel!)
Answer: Yes, they are tuned at the same pitch. And according to this source the strings are usually the same gauge too. This means that the strings will be looser (i.e. have less tension) when tuned to the same pitches. The source linked to above suggests that this contributes to smaller sized violins being hard to tune. I don't play violin, but I have certainly noticed that half and three-quarter size guitars tend not to stay in tune as well as full size instruments, and the strings do feel more loose, particularly for small electric guitars.
The source above also points out that you should use shorter strings intended for smaller violins, rather than cutting full-size strings, as you can on guitar, because violin strings have thread wound around the peg end of the string.
EDIT: following the discussion with the OP below, I thought it would be worth noting that a half-size violin does not have strings half the length of a full-size violin. It is not in fact half the size of a full-size instrument, despite its name, and certainly its scale-length is not half that of a full-size instrument. This page gives the scale lengths (string lengths) for different sizes of violin, and other stringed instruments. For example, it lists a full-size violin scale length of 330mm and half-size scale length of 285mm (not 165mm!) Again, this makes sense to me as a guitarist: a half-size guitar would be about the size of a ukelele if it had half the scale length!
Comment: Sure, I'll add that last link in!
Comment: Really? There's that much slack in them to allow that? Cool! (If you don't mind Bob, I'll leave it 24 hrs to see what comes along before accepting, but cheers.)
Comment: What do you mean about there being slack?
Comment: As in, I would have thought a string only had a small range over which it could be in tune, and make a sound i.e. not snap, or be too loose to play. Say, a couple of tones. From your answer, if the same string, made half the length, can be adjusted to play the same note simply by how tight it is - my assumption must be very wrong!
Comment: @Chris, I think I get what you mean. It might be worth noting that a half-size violin doesn't have strings with half the length. In other words, the scale length is not half that on a full size instrument. See this page for more info on scale lengths: http://www.fretlessfingerguides.com/measure_violin_scale_string_length.html
Comment: Ah - that I also didn't realise! Maybe worth adding to your answer? Thanks! It looks like I took things too literally!
Comment: +1 for "worth noting that a half-size violin does not have strings half the length of a full-size violin."


how to remove columns using indexes

Question: How do I remove columns starting from a certain index to another, I need to remove columns from 1950 to 2004?
I tried running this but it didn't work
test = df.drop(df.iloc[:, 1:55],  axis = 1)

Comment: `df.drop(list(range(1950,2005)),  axis=1, errors='ignore')`?
Comment: https://stackoverflow.com/a/48671822/1560708 <-- this does not solve your problem?
Comment: Does this answer your question? [python dataframe pandas drop column using int](https://stackoverflow.com/questions/20297317/python-dataframe-pandas-drop-column-using-int)
Answer: Assuming the column names are integers:
test = df.drop(list(range(1950,2005)), axis=1, errors='ignore')

For strings:
test = df.drop(list(map(str, range(1950,2005))), axis=1, errors='ignore')

how to remove columns using indexes


how to convert datetime to a yyyy-mm-dd hh:mm:ss format in perl?

Question: How do I convert datetime to a different format?
This is my date: Tue Feb 11 08:47:59 2014
how to convert to 2014-02-11 08:47:59
Thanks!
Answer: The Time::Piece module has been included with Perl since 2007.
<code>#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $input = 'Tue Feb 11 08:47:59 2014';

my $dt = Time::Piece->strptime($input, '%a %b %d %H:%M:%S %Y');

say $dt->strftime('%Y-%m-%d %H:%M:%S');
</code>
Comment: be aware though, as I had been wrestling with this way to long... that `strptime` and `strftime` are *locale* dependant and case sensitive. My system was running on `nl_NL.UTF-8`
Answer: You can use the DateTime module.


Solutions of an integral equation

Question: Given the integral equation:
$$\sqrt{f(x)}\int_{0}^{x}f(\tau)d\tau=g(x)$$ with g(x) known function,
in what cases and how is it possible to solve it?
Thanks
Comment: If $g(x)=k_1x^\beta$ then the solution has a simple form $f(x)=\sqrt{(\alpha+1)k_1} x^\alpha$ being $\alpha=\frac{2}{3}(\beta-1)$ with $\beta\ne 1$.
Answer: Let us assume that $g(x)$ is differentiable (in fact $g(x)$ should be also positive and monotonously increasing $f(x)$ has to be positive such that the square root is properly defined).
Take a derivative of your equation and you obtain
$$ f(x)^{3/2} + \frac{g(x)\, f'(x)}{2 f(x)} =g'(x). $$
Thus, you have reduced your equation to a differential equation with the initial condition $f(0) = g(0)$.
Answer: Square both sides of the equation :
      $$F^'(x) \  (F(x))^2=(g(x))^2$$
with $F(x) = \int_{0}^{x}f(\tau)d\tau $.
Now by integration between 0 and t :
$$\frac{(F(t))^3}{3} =  \int_{0}^{t} (g(x))^2 dx$$
F(t) can now be expressed :
$$F(t) =\sqrt[3]{3} \ \left( \int_{0}^{t} (g(x))^2 dx \right)^{1/3}$$
since $F'(t)=f(t)$, by derivation we obtain :
$$f(t) = \sqrt[3]{3} \ (g(t))^2 \left(\int_{0}^{t} (g(x))^2 dx \right)^{-2/3}$$

Solutions of an integral equation


Facebook API: Why can I load a user's image off one domain but not another?

Question: Image 1 is at fbcdn-photos-a.akamaihd.net
Image 2 is at fbcdn-sphotos-a.akamaihd.net
The crossdomain files are identical:
https://fbcdn-sphotos-a.akamaihd.net/crossdomain.xml
https://fbcdn-photos-a.akamaihd.net/crossdomain.xml
I can load image thumbs (which are on server 1), but I cannot load the full images (which are on server 2). I get SecurityError: Error #2123: Security sandbox violation.
For 2 hours I've been playing with LoaderContext settings,  Security.allowDomain, and Security.loadPolicyFile. Nothing gives.
Answer: I too was struggling whith this a few days ago... But the all of sudden, it worked by
adding this somewhere when my app inits:
        Security.loadPolicyFile("http://graph.facebook.com/crossdomain.xml");
        Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");
        Security.allowDomain("*");
        Security.allowInsecureDomain("*");

And then i used this to get the picture:
public function getProfilePicture():void {
            var myLoader:Loader = new Loader();
            myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void {
                pic.bitmapData = Bitmap(myLoader.content).bitmapData;
            });
            var fileRequest:URLRequest = new URLRequest("http://graph.facebook.com/" + this.uid + "/picture");
            var lc:LoaderContext = new LoaderContext();
            lc.checkPolicyFile = true;
            myLoader.load(fileRequest, lc);
}

Comment: No, but I found a away around it which is kinda hacky. I'm able to get the original image URL via the Graph API then switch the https to http. For whatever reason, Flash has no problem loading it from there even though the crossdomains are exactly the same.
Comment: Werid, when I tried http I would get an error than said graph requires a secure connection (https).
Comment: Thank you Matt, this solved the problem for me also. Maybe this could be add as an answer, hacky but it solves the actual problem.
Answer: If you are attempting only to get the user's profile image, you can access it unsecured from http:/graph.facebook.com/USERID/picture/ . But if you are talking about any other image (photos, etc.), you can do it only from the domain declared in the facebook app page, "Facebook integration" tab. That prevents any malicious intent of accessing your user's data in the event that somebody obtains your APP_ID and APP_SECRET.
Comment: Nice!  That worked perfectly.  Just ran into this myself, and this is an excellent work around.
Answer: The problem described here is that Graph API redirects you to one of the Facebook CDN domains. You have to load crossdomain policies from these domains into your Flash client in order to be able to call them using Security.loadPolicyFile("<protocol>://<domain>/crossdomain.xml");. Protocol is also important. List of these CDN domains is not available, so you can't bake it into the app. I described similar problem with profile pictures in this bug: http://developers.facebook.com/bugs/470699803010338 It'd be ideal if Facebook provided a list of CDN domains for it's developers via API so we could load appropriate crossdomain policies without having to allow everything or compromise security in other ways.
Answer: This worked for me:
loader.load(new URLRequest("https://graph.facebook.com/" + user.uid + "/picture?type=normal"), new LoaderContext(true, null, SecurityDomain.currentDomain));

Answer: As the error message states you are attempting to load something from a different server which is a security violation. It might not appear to make sense as you know they are identical but only you know that. This same security principal is what prevents js in a browser from one site stealing a cookie that belongs to another. If this security principal did not exist then the web would be a much worser place, with identity theft a much bigger problem.


PostgreSQL multidimensional arrays in SQLAlchemy, not sure of syntax

Question: I'm creating a schema for my DB using PostgreSQL and SQLAlchemy in declarative base and ran into a question that I think is answered but I'm somehow getting the syntax wrong.
I'm thinking of having an entry that's a multidimensional array (I only need 2D, but I figured I'd ask for an n-dimentional array solution in case I run into other issues).  I essentially need to have some_field[string][string] but am not sure of how to do that.
class SomeTable(Base):
    __tablename__ = 'some_table'
   multi_d_array = Column(postgresql.ARRAY(String)) #How do I make 2D+?

With an earlier version dimensionality was apparently unenforced (link: PostgreSQL multidimensional arrays in SQLAlchemy), but apparently this was patched (link: https://groups.google.com/forum/?fromgroups=#!topic/sqlalchemy/w4-nbMdxxUg).  The documentation still says it's unenforced (link: http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html) but I just wanted to make sure the code works alright before having my DB blow up.
Thanks for helping me with my newbie question.
Answer: Postgresql itself does not enforce the dimensionality of the array - all arrays are N-dimensional even if you specify it with a specific number of dimensions.   From the linked email:
http://www.postgresql.org/docs/9.1/static/arrays.html
"The current implementation does not enforce the declared number of dimensions either. Arrays of a particular element type are all considered to be of the same type, regardless of size or number of dimensions. So, declaring the array size or number of dimensions in CREATE TABLE is simply documentation; it does not affect run-time behavior."
In SQLAlchemy 0.8, the ARRAY type now includes an optional parameter "dimension=N" whereby you can give it the specific number of dimensions, which will allow the SQLAlchemy type to process incoming array data more quickly in Python (it doesn't need to guess the number of dimensions), and also cause it to emit DDL (i.e. CREATE TABLE) with that number of dimensions specifically, but without this parameter everything would still work as is.   The email you refer to is a user who wanted it to specifically say "INTEGER [][]" with that exact number of dimensions when emitting DDL, but it's really not necessary.
Comment: Thanks, I just needed a reality check from someone more knowledgeable -- and to confirm that by implementing it without specifying dimensionality would not cause it to break in future iterations.
Comment: Side question in case you knew: what if I wanted something that was ARRAY[string][int][some_type] -- where the different dimensions are differently typed?
Comment: I'm having trouble visualizing what that means.  an array is a grid of scalars, the dimensions are coordinate scales.   I don't see how an additional type gets associated with a dimension.  seems like you're thinking of an associative array, perhaps.


Como colocar isso num ciclo for?

Question: código:
if (label1.Text != string.Empty && label2.Text != string.Empty && label3.Text != string.Empty && label4.Text != string.Empty && label5.Text != string.Empty && label6.Text != string.Empty && label7.Text != string.Empty && label8.Text != string.Empty && label9.Text != string.Empty)
{
    empate();
    return true;
}

Comment: a comparação é feita errada ... e se você tem uma sequencia pode ser feita um ciclo realmente pegando as label por algum quesito, pelos controles desse formulário ... acho que é Windows Forms ou é WebForms?
Comment: É windows forms. Comparação feita errada?
Answer: Não ficou muito claro o que pretende, mas se for para substituir essa linha longa por um ciclo for, pode fazer assim:
int count = 0;
for (int i = 1; i <= 9; i++)
{
    if (this.Controls["label" + i].Text != string.Empty) count++;
}

if (count == 9)
{
    empate();
    return true;
}

Outra opção seria usar um container, por exemplo um panel, com as 9 labels lá dentro, e fazer:
if (this.panel1.Controls.Cast().Count(lbl => lbl.Text != string.Empty) == 9)
{
    empate();
    return true;
}

Comment: É exatamente isso, obrigado
Comment: @GonçaloSousa editei a resposta com outra opção.

Como colocar isso num ciclo for?


Creating instances of a function via a configuration file

Question: We have a configuration file that is read and stored as a dictionary, e.g.
config = {'type': A, 'input': {'color': 'red', 'border': 'thick', 'shape': 'square'}}

Now we want to use this config object to create an instance of a class, say, Drawing_Class with the condition that if the type is 'A', the colour is always blue, and if the type is 'B' the shape is always a circle.
I have written a function to achieve this which seems very unpythonic, and was wondering if there is a better way to achieve my goal? Of course, in the example I've given one could just input the desired colour and shape in the configuration file, but the actual problem is more complex and that can't be achieved.
Here is my function.
def drawing_dictionary(type):
    if type == 'A':
        value = config['inputs'].pop('color')
        output = drawing_function(**config['inputs'], colour='blue')
        config['input']['color'] = value

    if type == 'B':
        value = config['inputs'].pop('shape')
        output = drawing_function(**config['inputs'], shape='circle')
        config['input']['shape'] = value

    return output

It achieves what I need it to achieve, i.e. creating custom instances based on this configuration file, but in a way that seems very inelegant. Help would be much appreciated.
Comment: may be this way: `import copy
local_config = copy.deepcopy(config)
if type == 'A':
    local_config['input']['color'] = 'blue'
if type == 'B':
    local_config['inputs']['shape'] = 'circle'
output = drawing_function(**local_config)`
Comment: This is very unclear. If `type` is 'A', you are removing value `config['inputs']['color']` and assigning that value to `config['input']['color']` when `config['input']` doesn't exist, so that is clearly an error. Regardless, you seem to be wanting to ignore whatever color is in the configuration and use 'blue' and then put back what was the original configured color. Right? But you don't say why you need to do that. If for type 'A' the color is always 'blue', why don't you just have 'blue' in the configuration to begin with?
Comment: what does drawing_function look like? Is it creating a functor or is it just running a function? You say you want instances of a function aren't you just calling a function?
Comment: @Booboo The reason that I can't just have blue in the configuration file is because, 'type' in the configuration file actually represents a .csv file, which contains time-dependant information on what Type we're actually working with. At one time it could be Type A and one time Type B, I tried to boil down the problem to it's essence
Answer: It seems that you have a hierarchy of configurations with the global configuration "if A then color=blue, if B then shape=circle" taking precedence over the configuration file. Such a hierarchy can be modeled with the help of collections.ChainMap, see the following example:
from collections import ChainMap

GLOBAL_CONFIG = {
    'A': dict(color='blue'),
    'B': dict(shape='circle'),
}

def drawing_dictionary(config):
    return drawing_function(**ChainMap(
        GLOBAL_CONFIG.get(config['type'], {}),
        config['input'],
    ))

def drawing_function(**kwargs):
    import pprint
    pprint.pprint(kwargs)

drawing_dictionary({'type': 'A', 'input': {'color': 'red', 'border': 'thick', 'shape': 'square'}})
drawing_dictionary({'type': 'B', 'input': {'color': 'red', 'border': 'thick', 'shape': 'square'}})

Answer: I asked a question about drawing_function but figured I'd put some things down in an answer and update as necessary.
First off do not name a variable type as while it isn't a reserved keyword in python it is a built in function that allows you to determine the type of an object.
Second you say you want to create an instance of a function, are you talking about a functor? Is drawing_function a class? or are you just calling a function with different arguments depending on a config file (this is what your code seems to indicate and what I have assumed)?
The other code in your project will have an impact on the argument list you want to use and how you want to move data around so that the function gets the correct arguments. Your example code looks like you've made config a global variable which I would not recommend.
What if the config file has extra values in it or is missing values? You'd cause an exception I've added a theoretical validation routine.
Some recommended changes to your example code:
def drawing_dictionary(config):
    config = validate_config(config) #remove values you don't understand
    #and confirm all the values you need are present set type to 'Error'
    #if something is wrong
    if config['type'] == 'Error':
        handle_error()#maybe set a default config?
    else: #this assumes you can't fix the config
        return drawing_function(**config['inputs'],config_type=config['type'])

    return some_sort_of_error_value_or_throw_exception

inside of drawing_function you will have all the values in the config['inputs'] unpacked so you'll have a variable named colour and one names shape then you can handle the changes by type in that function to ensure it always happens and without changing the config dictionary:
if config_type == 'A':
    colour = 'blue'
elif config_type == 'B':
    shape = 'circle'

You could also swap out the if elif stuff for a match case statement if you're using python 3.10 or newer.
Comment: I guess it depends on how you know that the config file will not have extra values. Omitted values don't matter if you have defaults you're effectively doing part of the validation as part of creating the class. If you know the files are good because you're validating them somewhere else then you already have a validator, if not you really should have one in case your assumptions about them being correct change in the future. Since the only difference between the classes you create is how you handle default variables I think you should just move that logic into the constructor as per my answer
Comment: if you're already effectively validating things somewhere else then there is no need at all for the drawing_dictionary function. The constructor can do all the work seamlessly if it knows the type that is being used to create it. If the type significantly affects the functioning of the classes (I don't think it does) you could use an if elif or match construct to make different classes depending on type but if it's just the same code with different data I can't think of any reason to do it. The key is making your code and architecture easy to understand and reason about.
Comment: Yes sorry, drawing function is a class, I've edited the original post to account for this mistake. Config is also not a global variable, I just simplified the code to ask the question without overcomplicating things with additional classes. The config file should not have extra values, and if it has missing values the class will be initiated with default values specified in it's __init__ method. Would it be best practice to include a validator anyways?  Thanks
Answer: I like to use dicts to take the place of potentially-large if-elif blocks, so the first thing I would do is to create a lookup for the type names, containing the field name and default value for each type.
types = {
    "A": ("color", "blue"),
    "B": ("shape", "circle"),
}

I would also recommend copying the contents of the config table, rather than modifying it. This will keep you from accidentally modifying it, and also makes the function re-entrant. Here's my version:
def drawing_dictionary(typename):
    key, default = types[typename]
    kwargs = config["inputs"].copy()
    kwargs[key] = default
    return drawing_function(**kwargs)

With this implementation, supporting a new type is as simple as adding a row in types, rather than defining a new if block.
Comment: you could include `drawing_a` and `drawing_b` in the `types` entry, and then unpack it as something like `key, default, drawing_func = types[typename]`, then call it as `drawing_func(**kwargs)`
Comment: in some cases dictionaries are nicer than if elif statements, but they do have their downsides. For one you now have to handle an exception if you get data of any type that isn't contained in the dictionary and the dictionary is not immediately obvious in the drawing_dictionary function (though you could just move it there) If you're using python 3.10 or newer a match case statement is more expressive and functions like the dictionary approach. Since the type value only overrides one argument all the dict copying seems excessive to me but likely unimportant if this code isn't called much.
Comment: Thank you, and how would you handle cases where you're returning different objects based on type? E.g. if Type A return drawing_a(**kwargs) and if Type B return drawing_b(**kwargs)

Adding to the dictionary in this case i.e.:

`
types = {
    "A": ("color", "blue", drawing_a(**kwargs)),
    "B": ("shape", "circle", drawing_b(**kwargs)),
}
`

wouldn't really make sense right because kwargs isn't defined at that point


driver.wait() throws IllegalMonitorStateException

Question: All the variations of wait(...) are throwing the below exception from the following code. What am I doing wrong?
java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at LoginPage.main(LoginPage.java:29)

try
        {
            driver.get("http://domain:port/coco/webapp/login/login.faces");

            driver.findElement(By.id("clientCode")).sendKeys("coco");
            driver.findElement(By.id("systemCode")).sendKeys("consumer");
            driver.findElement(By.id("userId")).sendKeys("ffadmin");
            driver.findElement(By.id("password")).sendKeys("password");

            driver.findElement(By.className("af_commandButton")).click();
            driver.wait();
            Assert.assertTrue(driver.getPageSource().contains("Administration"));

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

Answer: You can only wait on an object if you've acquired the lock for it using synchronized.
I don't know whether you're meant to use wait using WebDriver - if you are, you'd need something like:
synchronized (driver)
{
    driver.wait();
}

However, if you're waiting for something to occur, it's more likely that there's an alternative method you're meant to be using. Perhaps WebDriverWait?
Comment: Apparently wait is not required from seleniunm 2 onwards as it supports implicit waits. With implicit waits, you only need to use one of the findElement methods, and if the target element does not exist or is not visible, Selenium will wait until it is. Unfortunately this example is out of date, however if you look at some of my more recent examples, hopefully you will find them to be working. http://seleniumexamples.com/blog/examples/selenium-2-examples/
Answer:
I hope this helps you
driver.manage().timeouts().implicitlyWait(long time, java.util.concurrent.TimeUnit unit);

OR
WebDriverWait wait = new WebDriverWait(driver, long timeOutInSeconds);

WebElement element = wait.until(presenceOfElementLocated(org.openqa.selenium.By locator));

Please note that I have not executed this code as I don't have webdriver but I wrote this after referring to javadocs.
Please refer javadocs for more details on this.
Comment: There is an error here, the last line should not include the timeout as a parameter for wait.until. At least, not as of the 2015 code (but I can't see why the old version would have that duplication either).
Comment: This worked for me `driver.manage().timeouts().implicitlyWait(2000,TimeUnit.MILLISECONDS);`
Answer: driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); is the best solution. Else, you have surround the driver.wait by synchronize block
Answer: This is a necro, but since there aren't better answers, and someone else might happen by: you're calling the wrong method.
You probably intended to call the selenium method to wait for a condition:
https://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html
What you actually called was the very primitive multithreading method (to wait until someone else has called notify() on your thread):
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
Answer: Use the below code, this will work.
synchronized (driver)
{
  driver.wait(2000);
}
driver.context(NATIVE_APP);
driver.findElementByXPath("//android.widget.Button[@resourceid='android:id/button1']").click();


Como renderizar Action acessando controller neste caso?

Question: Estou usando um template pronto e faço o usdo do bootstrap, porém a transação de menus é feita através de animações em javascript e com o uso da tag
 do html, como da seguinte forma:

            @Html.RenderAction("Create", "ProfessionalUser")

Porém quando clico no botão ele não renderiza a página que quero com este @Html.RenderAction("Create", "ProfessionalUser)
e é justamente o que preciso fazer, se eu usar o RenderPage ele até rendereiza o Html, porém não passa pela Action Create que é o que eu preciso (e também creio que não seja uma boa prática), pois nesta action ela retorna para a View duas listas que preciso usar.
Action Create:
public ActionResult Create()
        {
            ProfessionalSpecializationDAO pSpecializationDAO = new ProfessionalSpecializationDAO();
            ViewBag.ListProfessionalSpecialization = pSpecializationDAO.ListProfessionalSpecialization(0);

            ProfessionalTypeDAO pTypeDAO = new ProfessionalTypeDAO();
            ViewBag.ListProfessionalType = pTypeDAO.ListProfessionalType(0);

            return View();
        }

View Create:
@using ManyLife.ASP.Areas.Professional.Models
@model ManyLife.ASP.Models.ProfessionalUser

Novo Profissional

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        <fieldset>
            <legend></legend>

                    @Html.LabelFor(model => model.IdProfessionalUser)

                    @Html.EditorFor(model => model.IdProfessionalUser)
                    @Html.ValidationMessageFor(model => model.IdProfessionalUser)

                    @Html.LabelFor(model => model.Email)

                    @Html.EditorFor(model => model.Email)
                    @Html.ValidationMessageFor(model => model.Email)

                    @Html.LabelFor(model => model.ReEmail)

                    @Html.EditorFor(model => model.ReEmail)
                    @Html.ValidationMessageFor(model => model.ReEmail)

                    @Html.LabelFor(model => model.Password)

                    @Html.EditorFor(model => model.Password)
                    @Html.ValidationMessageFor(model => model.Password)

                    @Html.LabelFor(model => model.RePassword)

                    @Html.EditorFor(model => model.RePassword)
                    @Html.ValidationMessageFor(model => model.RePassword)

                    @Html.LabelFor(model => model.Name)

                    @Html.EditorFor(model => model.Name)
                    @Html.ValidationMessageFor(model => model.Name)

                    @Html.LabelFor(model => model.IdProfessionalRegister)

                    @Html.EditorFor(model => model.IdProfessionalRegister)
                    @Html.ValidationMessageFor(model => model.IdProfessionalRegister)

                    @Html.LabelFor(model => model.IdProfessionalSpecialization)

                    Especializações:
                    @{
                        foreach (var item in ViewBag.ListProfessionalSpecialization)
                        {
                            specialty
                        }
                        Html.ValidationMessageFor(model => model.IdProfessionalSpecialization);
                    }

                    Tipos:
                    @{
                        foreach (var item in ViewBag.ListProfessionalType)
                        {
                            specialty
                        }
                    }

                    @Html.LabelFor(model => model.City)

                    @Html.EditorFor(model => model.City)
                    @Html.ValidationMessageFor(model => model.City)

                    @Html.LabelFor(model => model.State)

                    @Html.EditorFor(model => model.State)
                    @Html.ValidationMessageFor(model => model.State)

                    @Html.LabelFor(model => model.Phone)

                    @Html.EditorFor(model => model.Phone)
                    @Html.ValidationMessageFor(model => model.Phone)

        </fieldset>

            <input type="submit" value="Create" />

    }

Answer: O que você está tentando cai mais dentro do conceito de Actions com PartialViews. Portanto, são necessárias algumas pequenas mudanças no seu código.
Html Principal

        @Html.Action("ProfessionalUser")

Seu Controller
[ChildActionOnly]
public ActionResult ProfessionalUser()
{
    ProfessionalSpecializationDAO pSpecializationDAO = new ProfessionalSpecializationDAO();
    ViewBag.ListProfessionalSpecialization = pSpecializationDAO.ListProfessionalSpecialization(0);

    ProfessionalTypeDAO pTypeDAO = new ProfessionalTypeDAO();
    ViewBag.ListProfessionalType = pTypeDAO.ListProfessionalType(0);

    return PartialView(new ProfessionalUser());
}

A View está ok.
Comment: Esta dando o seguinte erro no VS:
"Erro ao executar a solicitação filho do manipulador 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'."

No navegador aparece:
"A public action method 'ProfessionalUser' was not found on controller 'ManyLife.ASP.Controllers.HomeController'."
Comment: Você modificou o nome do método no `Controller`, conforme eu indiquei na resposta? De `Create` para `ProfessionalUser`?
Comment: Sim, troquei tudo como esta ali
Comment: "A public action method 'ProfessionalUser' was not found on controller 'ManyLife.ASP.Controllers.HomeController'." A InnerException me levou até aqui, porém, não faço requisição ao HomeController em nenhum momento. Só se o ChilgActionOnly o chama de alguma forma, se for, também não sei como resolver.
Comment: Essa `Action` precisa estar no `Controller` que chama a `View`, senão não vai mesmo funcionar.
Comment: Deixo nos 2 controllers então?
Comment: O ideal é deixar em um só, mas faça funcionar primeiro. Depois você remove um deles.


Add inner-marging to a 4 columns CSS

Question: I am not a CSS expert (mainly because I haven't had the need to use much HTML/CSS stuff lately), so I came up with the following style/divs to create a 4 column layout:

note: most of this stuff comes from this google result, I just adapted it to 4 columns.
The HTML then looks like this:

 SOME TEXT

 SOME LAST TEXT

Ok, I've simplified that a bit (there's a small image and some
 text in there too) but the thing is that I'd like to add some space between the columns. Here's how it looks now:

Do you have any idea what CSS property should I touch?
note: If I add margin or padding, one column shifts down because (as I understand it) it doesn't fit. There might be other CSSs as well, since this came in a template (I have been asked for this change, but I didn't do any of this, as usual).
Thanks for any insight.
Answer: You need to add padding to the columns. But when you do that, you also need to subtract the same amount from the width property. This i because of the box-model.
.col4 .first{ left: auto;width:24%; padding-right:1% }
.col4 .second{ left: auto;width:24%; padding-right:1% }
.col4 .third{ left: auto;width:24%; padding-right:1% }
.col4 .last{ left: auto;width:24%; padding-right:1% }

Comment: Thanks, that did the trick. I was adding the padding, but wasn't properly substracting from the width. (I thought it was automatic). Too much non-web programming I guess ;)
Answer: inner margin = padding
Answer: http://www.w3schools.com/css/css_padding.asp

padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;

Add inner-marging to a 4 columns CSS


Sum and product rules for continuous variables in probability

Question: I have seen that a formal justification for the sum and product rules applied to continuous variables requires measure theory. Does anyone know where I can find this formal justification?
The rules are:
\begin{align*}
p(x) = \int p(x,y)dy \\
p(x,y) = p(y|x)p(x)
\end{align*}
Thanks!
Comment: They hold by the [law of total probability](https://en.wikipedia.org/wiki/Law_of_total_probability)
Answer: I suppose you're refering to Bishop's book "Pattern Recognition And Machine Learning". If yes one should first mention those notations are a bit confusing as $p$ is used for both the measure on the implicit probability space and densities for all continuous random variables. Let's make this more explicit. We have a probability space $(\Omega, \sigma_\Omega, P)$ with probability measure $P$. Let's remind that a random variable $X$ defined on $\Omega$ has a density if function $x \in \mathbb{R} \mapsto P(X \leq x)$ is differentiable. In that case we can define its density as:
$$f_X : x \in \mathbb{R} \mapsto \frac{d}{dx}P(X \leq x)$$
For two continuous random variables $X$ and $Y$ we can defined the joint density
$$f_{X,Y} : (x,y) \in \mathbb{R}^2 \mapsto \frac{\partial}{\partial x}\frac{\partial}{\partial y}P(X \leq x \wedge Y \leq y)$$
What Bishop calls the sum rule is then the fact that:
$$f_X(x)=\int_{y \in \mathbb R} f_{X,Y}(x,y) dy$$
which is pretty straightforward:
$$\int_{y \in \mathbb R} f_{X,Y}(x,y) dy = \int_{y \in \mathbb R} \frac{\partial}{\partial x}\frac{\partial}{\partial y}P(X \leq x \wedge Y \leq y) dy$$
$$= \frac{d}{dx}P(X \leq x \wedge Y \in \mathbb R) = \frac{d}{dx}P(X \leq x) = f_X(x)$$
To my knowledge the product rule just follows from the definition of the conditional density:
$$f_{Y|X}(y|x) := \frac{f_{X,Y}(x,y)}{f_X(x)}$$


How to reference top level object with this from within a function that is within another object

Question: I have an object of colors as strings - a subset of those colors contains another object called gradients which is an object of functions. Within those functions - how do I reference the other colors that are siblings of gradient?

test0 is { ...cyan400,...}
test1 is {}
this within the function is undefined

Can we get an explanation for the reason behind the values of this's in each case?

{
    ...
    cyan400: "#a6fcff",
    cyan200: "#d9feff",

    test0: this,

    gradients: {

        test1: this,

        g1: (angle = "0deg") => oneLineTrim`
            linear-gradient(
                ${angle},
                ${this.magenta600} 0%,
                ${this.purple800} 50%,
                ${this.indigo800} 100%
            )
        `,
        ...
    }
}

Comment: The top-level object is always referenced with `this` if `this` is not called inside a non-arrow function. You have to bind colors object to some variable and then reference it by the variable name.
Comment: @Deda - In this case, it appears the OP wants a reference to the object that contains the property `cyan400` which is not something you can get to with `this`.
Answer: In short, when you have objects nested inside of others, there is no such a thing as a "parent" object in Javascript.  The language won't help you get a reference to the parent.  You will have to either reference the top level object by name directly yourself or manually put a reference to the top level object in the lower level object as a property.
When I define your object and assign it to a variable data and run your code and look at the values of data.test0 and data.gradients.test1 and value of this inside of the data.gradients.g1() function, they all have exactly the same value for me which is the lexical value of this in the scope where the object was defined.  That's how it should work.  this refers to the lexical scope where the objects were declared, it does not refer to the object itself.  Inside a non-fat arrow method (method declared with a regular function), this will be determined by how the method was called.
Some people get confused on this because when you call a regular method (not defined with a fat-arrow), the value of this inside that method will often be the object that the method is part of.  This is because of how that value of this is set when a method is called.  You can see the six ways the value of this is set in a regular method call in this answer: The six ways the value of this is controlled or determined.
There is no mechanism in the Javascript language to reference a "parent" object automatically.  Objects in Javascript are not actually "contained" within one another.  When you do a nested definition like this, the inner objects are created on their own and garbage collected on their own and the outer object just contains a reference to them.  It's quite possible that other variables elsewhere in your program can contain the same reference to those nested objects, included inside other object's properties.  So, there is no actual "parent" object in Javascript.
So, let's look at some runnable code, related to what you posted:
this.greeting = "hello";

let data = {
    cyan400: "#a6fcff",
    cyan200: "#d9feff",
    test0: this,
    gradients: {
        test1: this,
        g1: (angle = "0deg") => {
            console.log(this);
        }
    }
}

console.log(data.test0);
console.log(data.gradients.test1);
data.gradients.g1();

When I run this in node.js these last three statements all show the exact same output:
{ greeting: "hello" }

Because all three values of this are the same, which is as expected.
If I then, add a regular method to the gradients object and call it:
this.greeting = "hello";

let data = {
    cyan400: "#a6fcff",
    cyan200: "#d9feff",
    test0: this,
    gradients: {
        test1: this,
        g1: (angle = "0deg") => {
            console.log(this);
        },
        g2: function() {
            console.log(this);
        }
    }
}

data.gradients.g2();

Then, the value of this in g2 will be the gradients object.  That's because it was called with obj.method() syntax and it was declared as a regular function (not a fat-arrow function) so the value of this for obj.method() is set to obj which in this case is the gradients object.

If you're trying to reference properties in a parent object, there is no automatic way to reference that in Javascript using this or any other mechanism.  You will have to either place a reference to the top level object inside of gradients like this:
let data = {
    cyan400: "#a6fcff",
    cyan200: "#d9feff",
    test0: this,
    gradients: {
        test1: this,
        g1: (angle = "0deg") => {
            // use property manually set on this object
            // to get to the object that has the colors
            console.log(this.colors.cyan400);
        }
    }
}

// set reference to parent object that contains the colors
// can't be done inside the static declaration, has to be done afterwards
data.gradients.colors = data;

Or, reference the top level name of the object itself and get to the colors that way:
let data = {
    cyan400: "#a6fcff",
    cyan200: "#d9feff",
    test0: this,
    gradients: {
        test1: this,
        g1: (angle = "0deg") => {
            // reference top level object directly
            console.log(data.cyan400);
        }
    }
}


Erro ao gravar arquivo stream

Question:
O fluxo não era gravável

Recebe essa exceção ao tentar alterar um arquivo que esta no resource. Segue o código:
<code>var assembly = Assembly.GetExecutingAssembly();
        Stream str = assembly.GetManifestResourceStream("PCCLC9875.versao.txt");

        String linha = "versao=" + INICIAL_VERSAO + ";revisao=00;compilacao=00";
        StreamWriter sw = new StreamWriter(str);
        sw.WriteLine(linha);
        sw.Close();
        str.Close();
</code>
Só consigo fazer a leitura, mas ao tentar alterar da erro.
Answer: Esse stream foi disponibilizado só para leitura mesmo, não pode tentar gravá-lo. O erro diz explicitamente isto.
Se quiser mexer nos metadados do assembly até é possível, mas é preciso cuidado e entender todas implicações, que não são poucas.
Apenas para iniciar o estudo sobre o assunto:

Setting Assembly attributes
AssemblyBuilder

Coloquei no GitHub para referência futura.
Comment: Saquei, achei que faltava alguma manobra nesse código pra funcionar.  Vlw

Erro ao gravar arquivo stream


Como criar um vector2 em C?

Question: Gostaria de saber se tem como eu criar uma classe, para armazenar 2 variáveis, por exemplo, um Vector2, onde eu instanciaria e usaria assim:
Vector2 tile;
int posX, posY;
posX = tile.x;
posY = tile.Y;

ou algo do tipo.
Answer: Em C, com struct (C nao tem class), faz assim
/* define struct Vector2 com dois elementos */
struct Vector2 {
    int x;
    int y;
};

/* define tile como uma variavel pertencente ao tipo struct Vector2 */
struct Vector2 tile;

/* atribui valores aos membros de tile */
tile.x = 42;
tile.y = -1;

Comment: Ha quem goste de usar `typedef` para especificar outro nome para o tipo sem ter que escrever `struct`. Eu nao vejo grande vantagem nisso (escrever `struct` nao custa e pode tornar o programa mais legivel), por isso nao uso o `typedef` com esse efeito.
Answer: Em C, não utiliza-se Classes, como é feito em C++.
Quando desejamos armazenar dados de tipos diferentes, utilizamos struct:
struct estrutura {
    int nBase;
    int nAltura;
    double fArea; };

e aí podemos criar estruturas do tipo struct estrutura:
 estrutura triangulo1;
 estrutura retangulo1;

e acessar seus elementos independentes entre si:
triangulo1.nBase = 10;
triangulo1.nAltura = 5;
triangulo1.fArea = triangulo1.nBase * triangulo1.nAltura / 2.0;
// triangulo1.fArea terá valor de 7.5

retangulo1.nBase = 7;
retangulo1.nAltura = 3;
retangulo1.fArea = nBase * nAltura;
// retangulo1.fArea terá valor de 21.0

Espero ter ajudado!
Comment: Hmmm ... o tipo `estrutura` nao existe sem um `typedef`. O comentario relativo a fArea tem um valor diferente de 25.

Como criar um vector2 em C?


Multiple server processes on a Multihomed machine with one process bound to 0.0.0.0

Question: I develop a data broker service that repeats individual device data onto multihomed IP addresses on a single interface. Each repeat server is a separate process bound to a specific TCP IP and port (e.g. 10.0.34.50:29950 and 10.0.34.51:29950). Also on this sever is another process, which binds to 0.0.0.0:29950 as well.
On Ubuntu, client connections to the individual Multi-Homed IP's route successfully to those repeat server processes. On Red Hat 8.8, the process bound to 0.0.0.0:29950 accepts all incoming connection.
Clients should be able to connect to the individual Multi-Homed IP's when they are specified, and not always connect to the process bound to 0.0.0.0 (listen on all interfaces/subnets). As this seems to work on Ubuntu and not Red Hat. There's something I'm missing.
There is a configuration difference between these OS's that I haven't found yet.
I've been digging into tunables such as
net.ipv4.conf.all.rp_filter
net.ipv4.conf.all.arp_filter
net.ipv4.conf.all.accept_source_route
I'm wondering whether this requires policy based routing? I'll be trying that as well.
Comment: welcome, what is your business environment or relationship in here? because I don't see any. More over 0.0.0.0 matches any address and will block the port that is bound to. what research has been already done here?
Comment: To know what proper routing happened, you'd have to provide full examples of what did or didn't work, with the way to reproduce it, along the system's routes (which might differ between RHEL 8.8 and Ubuntu 22.04). Without proper additional socket options using setsockopt(2) (that you did not mention), you can't bind twice to the same port (no mention of port either...) when addresses overlap. Then the protocol does matter. UDP can behave differently than TCP in a multi-homed environment (specifically replies can get wrong if UDP setup is too simple).
Comment: Sorry, first question. Read through the asking a good question docs. Will update more after further troubleshooting. The edits detail what's been tried so far
Comment: Again: this doesn't work by default. There's a collision between binding to 0.0.0.0:29950 and any other x.y.z.t:29950 unless specific options are used. So as you don't know about such options (which I made sure to not explicitly mention to wait for you to describe their use), your problem is different. At a guess: something is running in a container.
Answer: 0.0.0.0 is the unspecified address. When binding a socket it means this host, ie. on any interface or with any IP address.
Accordingly, that behavior you describe seems to be correct. You need to configure that server to only use the address you want.
If that server/service cannot be configured as required you can use firewall filtering (iptables) to restrict connectivity.


How can I add text in my theme?

Question: Drupal is a complex CMS but all I need is simply a text on my page in the specific region of the page ( that will be rarely changed ) that can be changed by an admin.
Here's my theme mockup.

The text is going to be in the red square area as seen above. That text is going to be rarely changed. I was trying to do this with 'Basic page' content type block but It isn't showing me what I want it creates some text showing up
"No front page content has been created yet. Add new content"
and when I create new content It shows up Read more and then redirects me to node/1 URL If I click it.
There must be some other simpler way of doing this. I mean all I want is text that is editable by admin in control panel not some fancy blog posts. Also please notice that I am still learning Drupal and any answer would be great!
Comment: possible duplicate of [Removing the "No front page content has been created yet." message from the front page](http://drupal.stackexchange.com/questions/57258/removing-the-no-front-page-content-has-been-created-yet-message-from-the-fron)
Answer: By Default Drupal front page shows the list of Contents you create, the number of contents you can list is controlled in Site Configuration. To answer you particular scenario would be too much of an answer here, I'd recommend you to read some Beginner Documents or watch some Videos in the net. Good place to Start is Drupal documentation
To displaying content in front page go-to UR-URL/admin/config/system/site-information and change the default front page to node/1 (in your case). This will display static front-page when your created the Basic page.
Be aware this is not the best bet, so, I'd suggest you to explore Drupal bit more before actually starting the site building.
Comment: Is there any other way of doing the same thing but without having to worry about the default front page ( like in my case 'node/1' ) ? Any Modules? What If I have many textual regions on 1 page? Can't I just say that region of the page is text_1 and that region of the page is text_2 and admin can change these text_1 and text_2 content?
Comment: Oh yes there are, and there are lots of choices to choose from like `views`, `display suite`, `panels` etc. But you have to explore more and find out what's best for you.

How can I add text in my theme?


How to configure programmatically a unique constraint on several fields of a custom entity?

Question: How could I configure a unique constraint on several  fields of a custom entity I have already created with drupalconsole.
The purpose is not allowing insert of two record of the same entity having for example same lastname and fisrtname.
Answer: As suggested by elstevenson, I used the validation API.
Here the steps.

Create a repository in your module repo.
/src/Plugin/Validation/Constraint
Create a constraint (name = Unique)
<code>namespace Drupal\module_name\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;

/**
* @Constraint(
*   id = "Unique",
*   label = @Translation("Unique ", context = "Validation"),
*   type = "entity:entity_name"`
* )
*/

class UniqueConstraint extends Constraint {
   public $message= 'Unique entity!';
   }
</code>
Create a constraintValidator, and we populate the validate method with an entity query to make sure that there is no record having the same value of field1 and field 2:
<code> namespace Drupal\module_name\Plugin\Validation\Constraint;
 use Symfony\Component\Validator\Constraint;
 use Symfony\Component\Validator\ConstraintValidator;

class UniqueConstraintValidator extends ConstraintValidator {

/**
 * {@inheritdoc}
 */
public function validate($entity, Constraint $constraint) {
 $field1 = $entity->field1->value;
 $field2 = $entity->field2->value;
 $entity_type_id = $entity->getEntityTypeId();
 $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
  ->condition('field1',  $field1)
  ->condition('field2',  $field2)
  ->range(0, 1)
  ->count()
  ->execute();
if ($value_taken)
{
$this->context->addViolation($constraint->message);

}
</code>
}
  }
Then configure our constraint in our entity (annotations part):

/**
<code>* Defines the entity_name entity.

*

    * @ingroup entity_name
    *
    * @ContentEntityType(
    *   id = "entity_name",
    *   label = @Translation("entity_name"),
    *   handlers = {
    *     ...
    *     "form" = {
    *     ..
    *     },
    *  ....
    *
    *   constraints = {
    *     "Unique" = {}
    *   }
    * )
    */
</code>

Then you should uninstall your module and then reinstall it . (if your entity is populated with data, you have to delete all the date).
In your code (for example in your form) , you have to ensure the validation :
<code>$violations = $entity->validate();
if ($violations->count() > 0)
{
 $violation = $violations[0];

 drupal_set_message($violation->getMessage(),'warning');
}
</code>

Hope it will help.
Comment: For french people, all these steps are explained in this article in french  [link] (https://mydrupalworld.wordpress.com/2017/01/26/entity-validation-api-cas-pratique/)
Comment: We can't use Symfony's native UniqueEntity constraint http://symfony.com/doc/2.3/reference/constraints/UniqueEntity.html because Drupal doesn't actually use Symfony validation constraints. Here's a list of constraints implemented in Drupal core validation API:  https://api.drupal.org/api/drupal/vendor%21symfony%21validator%21ConstraintValidator.php/class/uses/ConstraintValidator/8.2.x
Answer: I asked something similar a little while ago: How do I do a 'required if other field = x' using the entity validation api?
Basically, you want to use the Entity Validation API to create a Validation Plugin for your form.
Comment: Yes. What you'd want to do it what I described in my own answer to the question (http://drupal.stackexchange.com/a/215280/66405), ie create an Validation Plugin for your entity. If you go into the Comment module in core modules, there's a check against database content in that. There's some more notes on what I did in the answer I linked to.
Comment: thanks, but my need is a validating in database insert. It's basically adding a constraint unique in databse


como representar um campo monetário com pontos e vírgula em javascript jquery

Question: Estou com uma enorme dúvida.
Preciso pegar os valores que estão no banco de dados com casas decimais de 3 (por exemplo: 56826.497) e mostrar na tela o valor 56.826,497. Já tentei usar o maskMoney e o priceformat, mas não deram certo.
O maskMoney até serve pra inserir os valores corretamente, me obrigando a inserir somente números e da forma que eu formatar (56.826,497). Porém, na hora que ele carrega o valor do banco de dados pra visualizar na tela, aparece como 56826.497.
detalhe: estou carregando os valores assim:
No HTML eu estou usando o código abaixo:
//----------------------------------------------------------------- no cabeçalho
*
//------------------------------------------------------------------ no cabeçalho
*

PS.: Experimente trocar o formatador para $ 0,0.00 e ver como não é introduzido nenhum erro de arredondamento.
PS2.: Uma outra grande vantagem de se utilizar o numeral.js é que naturalmente o seu sistema já nasce pronto para internacionalização (i18n)
Comment: @AdrianoSUV você vai usar o método `{ render: function(numeroSemFormatacao) { return formatar(numeroSemFormatacao); } }`
Comment: você poderia me mostrar como aplicar esse plugin na formatação de uma coluna do [link] https://datatables.net [/link] ? , exemplo: `"aoColumns": [ { "sName": "ValorUnitario", "mData": "ValorUnitario", "sWidth": "10%" },`.
Answer: Existem alguns modos de transformar isso em moeda.
Plugin externo
Você pode usar o plugin do Google Code, formatcurrency para fazer isso, baixe ele aqui: https://code.google.com/p/jquery-formatcurrency/
Por código
Outra maneira é usar regex ou então código JS para fazer.
Via jQuery:
$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\,)/g, "$1.").toString());

(Você pode checar aas respostas deste tópico)
Comment: Usar `toFixed` com dinheiro é cilada! Existem problemas bem conhecidos de arredondamento com `toFixed`. E outro detalhe, o parseFloat só recebe um parametro. O radix é apenas para o `parseInt`. Eu sugiro uma biblioteca como o [bigmoney.js](https://github.com/demchenkoe/bigmoney.js) se você pretende fazer qualquer calculo financeiro. Alem do mais ele tem uma funcinalidade de formatacao que pode ser util
Comment: Outra biblioteca que pode ser útil é o [numeral.js](https://github.com/adamwdraper/Numeral-js)
Comment: Definindo `total=56826.497` Seu código me resulta `"56,826.50"` o que estaria "incorreto" para esta pergunta, ou seja, fora do formato correto de milhar(pontos) e vírgula, do qual está no titulo da pergunta, e também no conteúdo da pergunta você pode ler `"e mostrar na tela o valor 56.826,497"` e notar que seu resultado está invertido.
Comment: É só você inverter o ponto com a virgula no regex
Comment: Mas o que estou dizendo é que para que esta seja uma resposta **válida** você já deveria ter feito isso, entende?
Comment: Entendo, mas as respostas tem intuito de ajudar o máximo possível, o resto vai do usuário poder interpretar o código e incorporar o mesmo em sua aplicação. Creio que esta resposta seja válida, pois seu problema foi resolvido, detalhes de exibição e pormenores podem ser ajustados dentro da sua aplicação. De qualquer forma vou editar por motivos de pesquisa de outros usuários também.
Comment: muito obrigado. ajudou bastante


Existe a possibilidade de juntar dois arquivos de áudio em um só em android?

Question: Exemplo: Audio A + Audio B = Audio C. Preciso que os sons se juntem mesmo, não concatenem.
O formato pode ser WAV, mas preferia que fosse MP3.
Encontrei alguns exemplos na net, mas nenhum funcionou.
protected Void myMethod() {
    List<String> selection = new ArrayList<String>();

    selection.add("a.wav");
    selection.add("b.wav");

    isProcessingOn=true;
    int RECORDER_SAMPLERATE = 0;
    try {
        DataOutputStream amplifyOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory() + "/ssmultitrackPlus/project1/NOVO.wav")));
        DataInputStream[] mergeFilesStream = new DataInputStream[selection.size()];
        long[] sizes=new long[selection.size()];
        for(int i=0; i<selection.size(); i++) {
            File file = new File(Environment.getExternalStorageDirectory() + "/ssmultitrackPlus/project1/" +selection.get(i));
         sizes[i] = (file.length()-44)/2;
        }
        for(int i =0; i<selection.size(); i++) {
            mergeFilesStream[i] =new DataInputStream(new BufferedInputStream(new FileInputStream(Environment.getExternalStorageDirectory() + "/ssmultitrackPlus/project1/" +selection.get(i))));

           // if(i == selection.size()-1) {
                mergeFilesStream[i].skip(24);
                byte[] sampleRt = new byte[4];
                mergeFilesStream[i].read(sampleRt);
                ByteBuffer bbInt = ByteBuffer.wrap(sampleRt).order(ByteOrder.LITTLE_ENDIAN);
                RECORDER_SAMPLERATE = bbInt.getInt();
                mergeFilesStream[i].skip(16);
          //  }
            //    else {
               //     mergeFilesStream[i].skip(44);
           //     }

        }

        for(int b=0; b<selection.size(); b++) {
        for(int i=0; i<(int)sizes[b]; i++) {
             byte[] dataBytes = new byte[2];
             try {
             dataBytes[0] = mergeFilesStream[b].readByte();
             dataBytes[1] = mergeFilesStream[b].readByte();
             }
             catch (EOFException e) {
                amplifyOutputStream.close();
             }
             short dataInShort = ByteBuffer.wrap(dataBytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
             float dataInFloat= (float) dataInShort/37268.0f;

            short outputSample = (short)(dataInFloat * 37268.0f);
            byte[] dataFin = new byte[2];
           dataFin[0] = (byte) (outputSample & 0xff);
           dataFin[1] = (byte)((outputSample >> 8) & 0xff);
          amplifyOutputStream.write(dataFin, 0 , 2);

        }
        }
        amplifyOutputStream.close();
        for(int i=0; i<selection.size(); i++) {
            mergeFilesStream[i].close();
        }

    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    long size =0;
    try {
        FileInputStream fileSize = new FileInputStream(Environment.getExternalStorageDirectory() + "/ssmultitrackPlus/project1/NOVO.wav");
        size = fileSize.getChannel().size();
        fileSize.close();
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final int RECORDER_BPP = 16;

    long datasize=size+36;
    long byteRate = (RECORDER_BPP * RECORDER_SAMPLERATE)/8;
    long longSampleRate = RECORDER_SAMPLERATE;
    byte[] header = new byte[44];

     header[0] = 'R';  // RIFF/WAVE header
     header[1] = 'I';
     header[2] = 'F';
     header[3] = 'F';
     header[4] = (byte) (datasize & 0xff);
     header[5] = (byte) ((datasize >> 8) & 0xff);
     header[6] = (byte) ((datasize >> 16) & 0xff);
     header[7] = (byte) ((datasize >> 24) & 0xff);
     header[8] = 'W';
     header[9] = 'A';
     header[10] = 'V';
     header[11] = 'E';
     header[12] = 'f';  // 'fmt ' chunk
     header[13] = 'm';
     header[14] = 't';
     header[15] = ' ';
     header[16] = 16;  // 4 bytes: size of 'fmt ' chunk
     header[17] = 0;
     header[18] = 0;
     header[19] = 0;
     header[20] = 1;  // format = 1
     header[21] = 0;
     header[22] = (byte) 1;
     header[23] = 0;
     header[24] = (byte) (longSampleRate & 0xff);
     header[25] = (byte) ((longSampleRate >> 8) & 0xff);
     header[26] = (byte) ((longSampleRate >> 16) & 0xff);
     header[27] = (byte) ((longSampleRate >> 24) & 0xff);
     header[28] = (byte) (byteRate & 0xff);
     header[29] = (byte) ((byteRate >> 8) & 0xff);
     header[30] = (byte) ((byteRate >> 16) & 0xff);
     header[31] = (byte) ((byteRate >> 24) & 0xff);
     header[32] = (byte) ((RECORDER_BPP) / 8);  // block align
     header[33] = 0;
     header[34] = RECORDER_BPP;  // bits per sample
     header[35] = 0;
     header[36] = 'd';
     header[37] = 'a';
     header[38] = 't';
     header[39] = 'a';
     header[40] = (byte) (size & 0xff);
     header[41] = (byte) ((size >> 8) & 0xff);
     header[42] = (byte) ((size >> 16) & 0xff);
     header[43] = (byte) ((size >> 24) & 0xff);
   // out.write(header, 0, 44);

    try {
         RandomAccessFile rFile = new RandomAccessFile(Environment.getExternalStorageDirectory() + "/ssmultitrackPlus/project1/NOVO.Wav", "rw");
        rFile.seek(0);
        rFile.write(header);
        rFile.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

O código acima concatena as faixas, eu gostaria que juntasse os dois ou mais sons ao mesmo tempo.
Answer: Sua lógica esta correta, infelizmente você não mostrou como está tentando fazer em Android, você talvez precise conhecer um pouco de teoria para entender o que está acontecendo com o seu código, qualquer tipo de som pode ser definido como vibrações se propagando pelo ar até chegar em seus ouvidos:

Você já se perguntou como consegue escutar um vasto número de sons acontecendo simultaneamente?
R: Sem você saber tudo está sendo mixado, todas as vibrações ocorrendo no ambiente se unem e são interpretados pelo seus sistema auditivo!
Computacionalmente estamos simulando o sistema auditivo, se queremos que diferentes origens sonoras se juntem apenas somamos os pulsos vibracionais.
Como fazer isso ?
R: você vai precisar da informação crua para poder manipular seu áudio, isso se aplica para qualquer tipo de manipulação necessária ex: mudar o volume do áudio, alterar a frequência, deixar mais lento ou mais rápido, etc.
Quando eu disse "informação crua" eu quero dizer que são os dados do seu áudio antes de sofrer qualquer codificação em mp3, wav, ogg, etc, e para conseguir isso em áudios gravados e codificados é preciso decodificar, para cada formato de áudio você vai encontrar um algoritmo diferente, comece com samples em .wav são mais simples de decodificar/codificar, eu acredito que deva existir uma vasta alternativa em Android para este passo!
OK com os dados decodificados você pode ter um vetor(se o áudio for mono), com os valores manipuláveis, eu aconselho que os valores decodificado fiquem no formato float point 32bit, os valores de seu vetor vão estar entre -1 e 1.
Com estes dados você pode simplesmente somar os dois vetores decodificados no formato float, para prevenir algum eventual transbordo nos valores com amplitude próximo da extremidade (prevenir ruídos) você pode multiplicar os dois vetores por 0.5 e depois somar, por fim você pode normalizar a saída, um pseudo código com este passo seria:
resultado = (vetor1 * 0.5) + (vetor2 * 0.5)

Para normalizar encontre o máximo valor absoluto do resultado acima e multiplique pelo resultado
Resultado_final_normalizado = (1 / max(abs(resultado))) * resultado

Ps: Os dois áudio que você deseja juntar precisar ter o mesmo sample rate, outro ponto a ser observado é se os dois vetores após a decodificação vão possuir o mesmo tamanho, se forem diferentes concatene o vetor menor com zeros para ficar do mesmo tamanho!
EDIT:
Código usado para juntar três arquivos de áudio:
private void mixFiles(){
                try {
                        InputStream is1 = getResources().openRawResource(R.raw.test1);
                        List<Short> music1 = createMusicArray(is1);

                        InputStream is2 = getResources().openRawResource(R.raw.test2);
                        List<Short> music2 = createMusicArray(is2);

                        InputStream is3 = getResources().openRawResource(R.raw.test3);
                        List<Short> music3 = createMusicArray(is3);

                        completeStreams(music1,music2,music3);
                        short[] music1Array = buildShortArray(music1);
                        short[] music2Array = buildShortArray(music2);
                        short[] music3Array = buildShortArray(music3);

                        short[] output = new short[music1Array.length];
                        for(int i=0; i < output.length; i++){

                                float samplef1 = music1Array[i] / 32768.0f;
                                float samplef2 = music2Array[i] / 32768.0f;
                                float samplef3 = music3Array[i] / 32768.0f;

                                float mixed = samplef1 + samplef2 + samplef3;
                                // reduce the volume a bit:
                                mixed *= 0.8;
                                // hard clipping
                                if (mixed > 1.0f) mixed = 1.0f;
                                if (mixed < -1.0f) mixed = -1.0f;
                                short outputSample = (short)(mixed * 32768.0f);

                                output[i] = outputSample;
                        }
                        CHAME_AQUI_SUA_FUNCAO_PARA_SALVAR_EM_WAVE
                } catch (NotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }

Repare na variável output ela vai conter os arquivos mixados em raw, chame alguma função que salve o resultado em wave. O código mostrado por você parece ter uma função que escreve o header + data do arquivo para .wave, você pode reutilizar este pedaço de código.
O código acima é um pouco diferente do proposto por mim, neste caso ele apenas verifica se a amplitude do sinal é superior a 1 ou -1 se sim a amplitude é forçada a ficar em seus extremos.
Comment: A normalização dos dados esta errada: como os áudios PCM estão entre `[-1,1]`, e a proporção deles no resultado é 50% cada, o resultado final também estará no intervalo `[-1,1]`. Assim, a expressão `max(abs(resultado))` será sempre no intervalo `[0,1]` que quando operado no vetor `resultado`, irá reduzir os valores das amostragens, reduzindo o volume do som. O correto seria então: `Resultado_final_normalizado = (1.0 / max(abs(resultado))) * resultado`
Comment: Bem lembrado @ViníciusGobboA.deOliveira, estou editando a resposta :-)
Comment: De forma que sou apenas um novato, nessa parte, ta faltando bastante coisa nesse fonte, vou ter que estudar bastante pra conseguir juntar essas faixas, mas obrigado pela ajuda...mas por hora não consegui ...
Comment: Poxa que pena o código pra mim é claro como uma manhã ensolarada, se você realmente quer escrever códigos para análise, processamento e manipulação de áudio construa uma boa base matemática/algebrica, leia artigos e livros sobre processamento digital. Entenda o básica como conceitos de sample, frame, taixa de amostragem, etc. Eu consideto Mixar sons da maneira que deseja uma das operações mais simples no domínio do tempo.
Comment: Depois de muito estudar e pesquisar, consegui mixar os wavs, mas ainda estou utilizando essas explicações como base, agora meu problema é outro é otimizar a mixagem...mas isso é assunto pra outro tópico ^^
Comment: muito bom meus parabéns, você acaba de fazer uma das operações mais básicas no domínio do tempo :-), sobre otimização abra uma nova pergunta para que eu ou outra pessoa te auxiliar.