Transition without properties specified

Question: I am learning how to make modal images in CSS and came across this example where there are two declaration blocks containing a transition specifying only the duration(?):
#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

and
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

It is written on the chapter 'How to...Modal Images' . (w3Schools). Is this correct? and if yes, is it a replacement for transition: all 0.3s; ?
Answer: Like Sean said the initial value for transition is all. This does not mean you should use it like that though. It is known that using the initial value could cause drawbacks in performance, read this.
It is better if you declare each value that you want your transition be applied to. You may not see the performance hit at first, but as you keep extending your CSS file it is something you want to keep an eye on.
Examples:

Without declaring all value:

.shape {
  display: inline-block;
  border-radius: 50%;
  border: 20px solid;
  border-color: #4285F4 #0F9D58 #F4B400 #DB4437;
  width: 50px;
  height: 50px;
  transition: 0.5s ease-in;
}
.shape:hover {
  border-radius: 0;
  width: 100px;
  height: 100px;
}

Declaring all value:

.shape {
  display: inline-block;
  border-radius: 50%;
  border: 20px solid;
  border-color: #4285F4 #0F9D58 #F4B400 #DB4437;
  width: 50px;
  height: 50px;
  transition: all 0.5s ease-in;
}
.shape:hover {
  border-radius: 0;
  width: 100px;
  height: 100px;
}

Better performance:

.shape {
  display: inline-block;
  border-radius: 50%;
  border: 20px solid;
  border-color: #4285F4 #0F9D58 #F4B400 #DB4437;
  width: 50px;
  height: 50px;
  transition: border-radius 0.5s ease-in, width 0.5s ease-in, height 0.5s ease-in;
}
.shape:hover {
  border-radius: 0;
  width: 100px;
  height: 100px;
}

Even better Perfomance
If you can afford the element overlap and the border-width increment to avoid redraw.

.shape {
  display: inline-block;
  border-radius: 50%;
  border: 20px solid;
  border-color: #4285F4 #0F9D58 #F4B400 #DB4437;
  width: 50px;
  height: 50px;
  transition: border-radius 0.5s ease-in, transform 0.5s ease-in;
  transform-origin: top left;
}
.shape:hover {
  border-radius: 0;
  transform: scale(2);
}

Read this for further explanation.
Answer: According to the MDN, the initial value for transition-property is all, so if you don't specify it in the shorthand transition it should function the same way.
https://developer.mozilla.org/en-US/docs/Web/CSS/transition
Same thing from the W3: https://www.w3.org/TR/css3-transitions/#the-transition-property-property-

Transition without properties specified


Can't print } on Visual Studio 2017 on Italian keyboard

Question: When I press the keyboard shortcut CTRL+ALT+SHIFT+] on an Italian keyboard to add a closed curly brace, Visual Studio selects a block of my code instead of printing it.
I have already tried to reset the keyboard mapping on Visual Studio but to no avail.
Other programs works without problems. How can I fix this problem?
Comment: To check what shortcut is hijacking a keypress you can use the method I described in https://stackoverflow.com/q/51921583
Comment: You can also type the curly braces by pressing SHIFT + ALT GR + braces.
Comment: @Banex they are telling me that also `SHIFT + ALT GR + {` is affected
Answer: It is a new feature appeared in Visual Studio 2017 version 15.8.0.
It is called ExpandSelectionToContainingBlock and it is mapped to the keyboard shortcut CTRL+ALT+SHIFT+] or CTRL+ALT+SHIFT++ (For VS in Italian)
But this mapping has removed the ability, from some keyboards without the key for the closing brace (like the Italian one), to press those keys and get the, indispensable for many programming languages, close curly brace.
As far as I know there are two workarounds

Go to Tools menu and select Customize
Press the Keyboard button
Search for Edit.ExpandSelectionToContainingBlock
Press Remove

or just use the numeric keypad and press
ALT+0125
For Italian readers with the Italian version of VS, the search above at point 3 should be for Modifica.Espandiselezioneabloccocontenitore. I don't know if other languages are affected by this 'translation vice' but it is a thing to be aware of.
The problem has already been reported to MS (Thanks Albireo)
EDIT: It seems that they have fixed the problem, in version 18.5.2 there is anything assigned to the shortcut. But I am not sure if this is an effect of my previous action or if this (no shortcut) is the real default now.
Comment: The problem has already been reported in https://developercommunity.visualstudio.com/content/problem/289516/cannot-type-close-brace.html (and many other closed as duplicates), the answer given is the same as yours.
Comment: Thank you very much! It works!
Comment: Regarding the keys combination: on an Italian keyboard the correct combination is `SHIFT`, `CTRL`, `ALT` and `+`, *not* `]`. The `]` is not available on the keyboard without modifiers and is obtained by using `CTRL`, `ALT` and `+`. You can also see the culprit shortcut in the screenshot in this answer: https://stackoverflow.com/a/51927127 Source: have an Italian keyboard.
Comment: @Albireo Interesting, me too, but Visual Studio is the English version and the shortcut is linked to the closing square bracket. Indeed the + and the ] are in the same physical key on my Microsoft Comfort Keyboard 5000
Comment: @jessehouwing why did you close this as duplicate and not the other one?
Comment: I started closing against that one answer and then started searching for other questions. If I had stumbled upon this one first I'd likely had closed them into this one. When I noticed this was older and had more votes I had already closed other questions against the other question. Flip of a coin type situation.


How to make getopt_long() print nothing when there is error command-line arguments?

Question: I have a program use getopt_get() to parse command line arguments.
My code is like this :
int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
};
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }

When I pass correct command line arguments to program, it works wells.
But when wrong arguments are passed to program, it will print annoying and superfluous words like this.
For example, i pass wrong argument 'q' to program
$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t

When there are wrong arguments, I just want it run my function help() without printing any word.
./program: invalid option -- 'q'

How can I stop getopt_long to print this annoying word and just print nothing?
Answer: Read the fine manual...

If getopt() does not recognize an option character, it prints an error
  message to stderr, stores the character in optopt, and returns '?'.
  The calling program may prevent the error message by setting opterr to
  0.

So, try this before calling getopt_long:
opterr = 0;

Comment: `opterr` is POSIX:  http://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html, so even though `getopt_long()` isn't POSIX, it's likely to work.
Comment: Thanks, It work! And `opterr = 0;`  should  written before optget_long() as a flag.
Comment: A better online manpage link: http://man7.org/linux/man-pages/man3/getopt.3.html . The bad editing in the old version clouds the fact that you can also suppress error messages by putting a colon at the front of the option string.


What chord is this and when is it the dominant?

Question: For a song I've written I do a chromatic descending climb with the bass note in a Cm chord and end up with my fingers like this:

First of all I'd like to know what chord this is, my guess is an A diminished +5th however I'm not certain.
Also I would like to know when this is the dominant (7th) chord, what is the tonic so that I can transpose another section of music to that key (making them work well together.)
That section of music is chords: Dm, F(inversion), B Dim, Bb --> Transpose to what?
Comment: Just want to point out that "descending climb" is a little counter-intuitive and contradictory.
Answer: This is an Am7b5 - also known as A half-diminished.
This chord would never be a dominant seventh in of itself. You would need to raise the 3rd and 5th degree of the chord for that to happen.  In that case, the music would normally resolve back to D minor (in your case.)  Alternatively, you can use this chord as a pivot chord using it as a ii7 before moving to V (D major), or vii° (F#dim) before modulating to G maj/min.
Just a simple idea.
Tonal centers for songs work well if they are somehow related to one another - the relative / parallel minor or major, the dominant, the sub-dominant and their respective relative / parallel minors and majors are all tried and true techniques.
Comment: Could also be a Cm6, especially with C as a root here.
Comment: @Hilmar - with due respect, Cm6 isn't actually a real chord.  More than likely the C will be heard as the third of the chord instead of the root. Chord nomenclature deals with harmonic functionality. In the key of D minor, a "Cm6" would be the bvii6/5 which, harmonically speaking, doesn't make any sense as that roman numeral doesn't offer any function.  Lastly, just note that the lowest note of a chord *does not* immediately indicate the root of the chord.
Comment: OK thanks. Fist off yep, I didn't mean descending climb (whoops.) Just so you know I've decided to take it as a pivot chord (as per your advice) as I wanted to move to a minor tonality.So I went to ii7 (Dmajor) and transposed my next section to Gm making it Gm,A#(inversion),E Dim and D#. You've also introduced me to parallel minors and majors that I didn't know existed so thanks for the brilliant answer.
Comment: @CoreyFord - glad to help!
Comment: @jjmusicnotes: I am not sure what you mean. Surely you can have a m6, for example on the root? My Funny Valentine: Cm  -  Cmmaj7 - Cm7 - Cm6.
Comment: @Gauthier - there is more than one way to notate a single chord.  Cm6 may make sense if there was a pedal (as there appears to be in your example) or if that nomenclature reflects some sort of harmonic function (which, in the case of your piece could be argued.) My comments were more with respect to the OP's  particular case: Cm6 isn't really a real chord in D minor.
Comment: Oh I'm with you. I find it kind of dirty to notate the descending line of My Funny Valentine (C, B, Bb, A) in the chords. It's not really the harmonic function, as you say. I was just reacting to your "isn't a real chord", because if a composer really want a minor chord on I with a sixth, what else could they write?
Comment: It seems strange to me to call this a chord of Am. The notes I see from low to high are: c - g - a - e♭ - g. While it is true that the Am7-5 consists of these notes. But there are 2 reasons why it may not sound as a chord of A minor. 1) It is a 1st inversion chord, allowing C to be felt as root. 2) It has a doubled 7th. That is very unusual: since the 7th has a tendency to descend by step, we would now have two of these, forming a parallel octave.

Without any context of the surrounding harmony, it seems much more straightforward to me to say that this is a Cm chord with added 6th.
Answer: It looks like a simple c minor with an added major 6th to me.
Answer: Definition: ^ = "scale degree"
In Jazz, the tritone of a dominant 7th chord is the defining characteristic.  In tonal theory the 7th chord built on the V includes ^4 and ^7 resolving to ^3 and ^1.  In jazz, Tritone Substitution allows you to resolve these in the opposite direction to a chord whose root is a TT away from the expected resolution.
So from this perspective, your chord's dominant characteristic is that it contains the Tritone A-Eb.  This TT could resolve to ^3 & ^1 in a Bb Major chord, a Bb minor chord, or via Tritone Substitution to an E Major chord or an E minor chord.
jjmusicnotes is correct as far as I know regarding common practice harmony, but I wanted to provide a different perspective on chords containing a tritone.  Likely these will sound more jarring than the common practice resolutions.  I might be mixing up the precise meaning of Tritone Substitution a bit, but the takeaway is that, what I have learned from Jazz is that the tritone content of a chord is extremely important to its sound and resolution characteristics.
Comment: 1) By "common practice" I mean harmonic practices of the western classical tradition through mid-late 19th century.  Jazz literature has chord resolutions that are not typically found in the "common practice" literature.  Obviously Jazz grew out of the common practice tradition, I don't think many would argue that point.  2)  The chord in question shares 3 chord tones with an F7 and some musicians could see/hear it as a F7 add 9 chord which is missing it's root.  Clearly you do not see or hear it this way.  It's a different way of looking at things.
Comment: you would be correct if the chord in question were in fact an F7.  But as it is, this chord is not, and is also not a dominant seventh, and therefore in this context the tritone can function differently, such as a pre-secondary-dominant.  Resolving to Bb would make sense if you ignored the G entirely, but as it is, a half-diminished seventh is not a cadential chord.  I would also be careful about making statement regarding "common practice" resolutions - it is from "common practice" that jazz came into existence.
Comment: How you hear a chord entirely depends on context - plugging "what-if" scenarios to fit a possible chord does little to explain exactly what was presented.  The notes the OP provided could be fitted into hundreds of different chords - all of them with a different function and with different merit, and yet not all advice would be pertinent to the OP's question. Supposition leads to sloppy theoretical analysis.
Answer: I'm a professional jazz-classical pianist, composer, author.
Here is the biggest question which also has the answer in it:
What do you hear with this chord?
I would say this chords is right before the chord "G, B, D#, F#, A, E" to me if I was composing a piece for my latest book -Contemporary Studies for Piano.
The name is not important. *How you hear, how you feel, how you make* connections between chords matter. Rest of it just daily conversations between people.
I would recommend you to to work on basic classical harmony and functional, non-functional harmony.
Don't worry about the chord names. Listen more, improve your sense and ears. Don't be afraid composing new pieces. Rest of it for the people who will listen your creations and try to understand what you have done there.
Music is nature. A bird's voice still would be so wonderful before you gave a name to this bird.


Have I computed these likelihood ratios correctly?

Question: I'm the author of the ez package for R, and I'm working on an update to include automatic computation of likelihood ratios (LRs) in the output of ANOVAs. The idea is to provide a LR for each effect that is analogous to the test of that effect that the ANOVA achieves. For example, the LR for main effect represents the comparison of a null model to a model that includes the main effect, the LR for an interaction represents the comparison of a model that includes both component main effects versus a model that includes both main effects and their interaction, etc.
Now, my understanding of LR computation comes from Glover & Dixon (PDF), which covers basic computations as well as corrections for complexity, and the appendix to Bortolussi & Dixon (appendix PDF), which covers computations involving repeated-measures variables. To test my understanding, I developed this spreadsheet, which takes the dfs & SSs from an example ANOVA (generated from a 2*2*3*4 design using fake data) and steps through the computation of the LR for each effect.
I would really appreciate it if someone with a little more confidence with such computation could take a look and make sure I did everything correctly. For those that prefer abstract code, here is the R code implementing the update to ezANOVA() (see esp. lines 15-95).
Answer: Although the reasoning about calculating the LR from the SS values is quite fair, a least-squares method is equivalent but not the same as a likelihood estimate. (The difference can be illustrated eg in the calculation of the se, which is divided by (n-1) in a least-squares approach and divided by n in a maximum-likelihood. The maximum likelihood estimate is thus consistent, but slightly biased).
This has some implications: you can calculate the LR as the likelihood is proportional to $\frac{1}{s}$, but that doesn't give you the likelihood of your anova model itself. It just tells you something about the ratio. As the AIC is classically defined in terms of the likelihood, I'm not sure if you can use the AIC as you intend.
I've looked at the spreadsheet, but the values for the "uncorrected LR within"(I'm also not completely following what exactly you're trying to calculate there) seem highly unlikely to me.
On a side note, the power of LR testing is that you can just contrast the models you want, you don't have to do that for all of them (which lowers the multitesting error). If you do this for every term, your LR is completely equivalent to an F test, and in the case of least squares, as far as I know even numerically about the same.
Your mile may vary, but I've never been confident mixing concepts of two different frameworks (i.e. least squares versus maximum likelihood). Personally, I'd report the F statistics and implement the LR in a function that allows to compare models (eg. the anova function for lme models which does exactly that).
My 2 cents.
PS : I did look at your code, but couldn't really figure out all the variables. If you would annotate your code using comments, that would make life a bit easier again. The EXCEL sheet is also not the easiest to figure out. I'll check again later to see if I can make something from it.


RedHat iptables forwarding to VirtualBox Windows Server 20120 VM for RDP

Question: I have a server with RedHat 6.5, this has the NIC eth2 connected to the internet at address 126.96.36.199. On this server I have installed VirtualBox 4.3.2 and created a VM with Windows Server 2012 SR2, the win VM has a NAT connection and Host Only connection and IP Adress 192.168.56.101. The host only connection is defined at Linux level as vboxnet0, below the partial output of command ip addr show:
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000
link/ether 2c:76:8a:5a:b4:c2 brd ff:ff:ff:ff:ff:ff
inet 188.8.131.52/27 brd 18.104.22.168 scope global eth2
inet6 fe80::2e76:8aff:fe5a:b4c2/64 scope link
   valid_lft forever preferred_lft forever

9: vboxnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
link/ether 0a:00:27:00:00:00 brd ff:ff:ff:ff:ff:ff
inet 192.168.56.1/24 brd 192.168.56.255 scope global vboxnet0
inet6 fe80::800:27ff:fe00:0/64 scope link
   valid_lft forever preferred_lft forever

Remote desktop is enabled on the VM win box, I can successfully connect from the Linux box using rdesktop 192.168.56.101.
What I want to do is to be able to RDP connect the vm win box from the internet, ie to 188.8.131.52:3389, by forwarding the request to 192.168.56.101:3389. Forwarding is enabled, I am using the following iptables rules, but it doesn't work.
iptables -A INPUT -p tcp --dport 3389  -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -t nat -A PREROUTING -d 188.8.131.52 -p tcp --dport 3389 -j DNAT --to 192.168.56.101:3389
iptables -A FORWARD -p tcp --dport 3389 -d 192.168.56.101 -j ACCEPT
iptables -t nat -A POSTROUTING -p tcp --dport 3389 -d 192.168.56.101 -s 192.168.56.101 -j MASQUERADE

Can anybody help? I am stuck.
Thanks for any help.
Comment: VirtualBox is not suitable for this. Use the KVM virtualization included with RHEL.
Comment: Hi thanks for your reply. Why do you think Virtual Box is not suitable? Would the iptables rules in my question work with KVM? thanks
Answer: So I followed Michael Hampton hint, I created a vm using KVM and I added the following iptables rules
iptables -t nat -I PREROUTING -p tcp -d 220.127.116.11 --dport 3389 -j DNAT --to-destination   192.168.122.1:3389
iptables -t nat -I PREROUTING -p udp -d 220.127.116.11 --dport 3389 -j DNAT --to-destination 192.168.122.1:3389
iptables -I FORWARD -m state -d 192.168.122.1 --state NEW,RELATED,ESTABLISHED -j ACCEPT

All is working now. The iptables rules were adapted from the ones provided in this post:
Forwarding ports to guests in libvirt / KVM
Thanks, regards


Google Cloud IOT, block communication via API

Question: I'd like to block communication with a device in a registry in Google Cloud IOT.
The gcloud command that is used to block communication: https://cloud.google.com/iot/docs/gcloud-examples#block_or_allow_communication_from_a_device
The Patch API doesn't make it clear how one can block communication of a device using the API
So how is this achieved?
Answer: There is an example snippet for patching a device available that may be helpful for you.
Instead of sending a EC value in the patch body, you could update the device to have communication blocked.
In Python, you would do this as:
<code>client = get_client(service_account_json)
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

patch = {
    'blocked': 'True'
}

device_name = '{}/devices/{}'.format(registry_path, device_id)

return client.projects().locations().registries().devices().patch(
        name=device_name, updateMask='blocked', body=patch).execute()
</code>


Is there any way to avoid being affected by an master merge from my colleagues' modules

Question: We use git+puppet to develop our puppet codes and deploy them to our server nodes.
The technology diagram(including some Chinese but matters little) is:
here
Common configurations like packages source list,dns servers ,and system related files is coding into puppet modules named with pkgmgr,networkmgr and sysenv.They are developing ,testing and releasing in different branches then pushed to /modules/env(branch)/common directory on puppet master node. On the other hand,we have many projects having their own  configurations,including or declaring common modules,coding into a module named after project name and then copied to modules/env(branch)/projects in the same way.
Servers in every project acting as puppet agent can be set a specific puppet environment like production,testing.For example when the production environment is selected, the resources from modules defined in /modules/production/common and /modules/production/projects/project_A will be deployed.
Common modules is maintained by another apartment , any update merged to master branch will affect our projects servers in production environment.Is there any way to satisfy:

1 Some of our projects servers do not want any update anymore before they are offline
2 Any change to common modules will generate a tagged snapshot like version and can be selected by our project positively

I know is hard to release puppet module in version like other offline softwares,but any way else to satisfy the two requirements elegantly?
Answer: Release management of software can be tricky with lots of teams.
My recommendation is don't use the same repository, if you can use one repository per module (although this can introduce quite a bit of overhead). Instead you can just use multiple git repositories and vendor your companies "common" modules in using say librarian-puppet.
Comment: Ok...Do you mean providing common modules separately and offline? Just like download modules from puppet forge ? Then the question is how to arrange them under puppet modules directory and allow us to select the specific version
Comment: That's what librarian-puppet will do for you. You can point it at puppet forge or a git repo, if you use a git repo you can select a branch, tag or SHA as your version. Librarian puppet will automatically place these modules in your module directory (although I prefer to keep them in vendor/modules, so I know which ones are mine and which are upstream)
Comment: It makes sense. And I am going to try it practically and tell you if there is other problems. thank you.


how to force foreach reset in php

Question: Is possible in php to reset The foreach?
for example:
foreach($rows as $row)
{
  if(something true)
  {
     continue foreach;
  }
  else
  {
     break;
     reset foreach;//I mean start foreach again...
  }
}

----------------------------------Edited
Thanks my friend for your answers...
The condition generate from result of foreach so I can not use function.
I wana sortet it by (fro example) alphabet...in many DIV html.
I can not filter result by SQL for same reson.
So mybe I have to use a css trick.
Comment: `break` breaks out of the loop. So why do you need to start again? What do you need this for?
Comment: No That can not be possible. Make use of for if that's the case. but do not understand why do you want to reset your loop?
Comment: I suggest using a for-loop here, that's the easiest way. (using `reset` creates more headaces and won't work as expected on Iterator objects)
Answer: You could do something around these lines (and avoid the limitations of recursion):
while (True) {
    $reset = False;
    foreach ($rows as $row) {
      if(something true) {
         continue;
      } else {
          $reset = True;
          break;
      }
    }
    if ( ! $reset ) {
        break; # break out of the while(true)
    }
    # otherwise the foreach loop is `reset`
}

Comment: This is magnificently dirty, but highly effective. I love it!
Comment: Thanks...with a bit change solved it for me with your simple solution.
Answer: It seems that reset inside a foreach has no effect.
You can implement this if you make your own Traversable.
Answer: Try using reset/while/each which is functionally equivalent to foreach according to the manual then you can use reset within the loop like so:
<?php
$arr = array(1=>'one',2=>'two',3=>'three');
reset($arr);
$resets=0;
while (list($key, $value) = each($arr))
{
    echo "$key => $value
\n";
    if($value=='three')
    {
        if($resets==0){$resets++;echo "==Resetting==
\n";reset($arr);continue;}
    }

}

Output:

1 => one
2 => two
3 => three
==Resetting==
1 => one
2 => two
3 => three
As pointed out by Mike Kormendy in the comments, each is deprecated as of php 7.2.
If for some reason you like my approach, you can emulate each using a combination of key(), current(), and next() like so:
<?php
$arr = array(1=>'one',2=>'two',3=>'three');
reset($arr);
$resets=0;
while ( list($key,$value) = [key($arr),current($arr)] )
{
    if($key === NULL){ break; }
    next($arr);

    echo "$key => $value
\n";
    if($value=='three')
    {
        if($resets==0){$resets++;echo "==Resetting==
\n";reset($arr);continue;}
    }
}

Output:

1 => one
2 => two
3 => three
==Resetting==
1 => one
2 => two
3 => three
This answer was posted many years ago.
Going forward, I'd avoid this type of approach like the plague.
The accepted answer is a lot more elegant.
Comment: And now in PHP 7.2 each is deprecated.
Comment: And in PHP 8.0 `each` has been removed: https://www.php.net/manual/en/function.each.php
Answer: I think you can do that by putting the for each in a function and then calling the function from itself.
function doForEach($rows) {
    foreach($rows as $row)
    {
        if(something true)
        {
            continue foreach;
        }
        else
        {
            break;
            doForEach($rows);
        }
    }
}

Be very careful with this however, you'll likely end up in a loop.
Comment: You should avoid recursion at all costs in languages that do not support tail call optimizations. Otherwise you're limiting your algorithms to the max stack size and/or max stack depth (In PHP that's only 100 by default).
Comment: I didn't know that. I did some Googling on this and you are right, however the limit of 100 comes from xdebug and not from PHP. So in practice you can get over 100, but you have no control over when your PHP will crash.
Comment: I've always been under the impression it was PHP that imposed the limit. I've learned something new today as well, thanks for the correction ;)
Answer: Why reset the foreach ? If you really need this... But care about infinite loop !
function myForeach($array){
    foreachforeach($rows as $row){
        if(something true){
           continue foreach;
        }else{
           myForeach($array);
        }

Answer: Yes it is possible to reset a foreach but not the way you described it in your question. You can read my approaches below.
--------- Implement Iterator --------------------------------
Implement the Iterator interface.
Link: https://www.php.net/manual/en/class.iterator.php.
Code example:
class myIterator implements Iterator {

    private $maxIterations = 2; // the maxumum amount of iterations
    private $currentIteration = 1; // the current iteration number

    private $lastKey = null;
    private $lastValue = null;
    private $currentValue = null;

    private $position = 0;

    private $array;

    public function __construct($array) {
        $this->array = $array;
        end($array);
        $this->lastKey = key($array);
        $this->lastValue = current($array);
    }

    public function rewind() {
        $this->position = 0;
        reset($this->array);
    }

    public function valid() {
        // Reset when there are no elements
        if($this->position > $this->lastKey &&
           $this->currentValue === $this->lastValue &&
           $this->currentIteration < $this->maxIterations){

           $this->rewind();
           ++$this->currentIteration;
        }
        $isSet = isset($this->array[$this->position]);
        return $isSet;
    }

    public function current() {
        $this->currentValue = $this->array[$this->position];
        return $this->currentValue;
    }

    public function key() {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }
}

$array = array("A",
      "B",
      "C",
);
$it = new myIterator($array);

// the iterator will traverse the array twice
foreach($it as $key => $value) {
    echo 'key : ' . $key . '
';
    echo 'val : ' . $value . '
';
    echo '
';
}

The output
key : 0
val : A

key : 1
val : B

key : 2
val : C

key : 0
val : A

key : 1
val : B

key : 2
val : C

--------- InfiniteIterator + LimitIterator --------------------------------
You can use InfiniteIterator in combination with LimitIterator.
$obj = new stdClass();
$obj->Mon = "Monday";
$obj->Tue = "Tuesday";
$obj->Wed = "Wednesday";
$obj->Thu = "Thursday";
$obj->Fri = "Friday";
$obj->Sat = "Saturday";
$obj->Sun = "Sunday";

$infinate = new InfiniteIterator(new ArrayIterator($obj));
foreach ( new LimitIterator($infinate, 0, 14) as $value ) {
    print($value . PHP_EOL);
}

// OUTPUT:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

See link: http://php.net/manual/en/class.infiniteiterator.php
--------- ArrayObject + ArrayIterator --------------------------------
According to the PHP manual it should also be possible to achieve it by using ArrayIterator.

When you want to iterate over the same array multiple times you need
to instantiate ArrayObject and let it create ArrayIterator instances
that refer to it either by using foreach or by calling its
getIterator() method manually.

Their description is not clear to me, but it think that they mean something like this.
$array = array('honda', 'toyota', 'suzuki', 'mazda', 'nissan');

end($array);
$lastKey = key($array);
$maxIterations = 2;
$currentIteration = 1;
$arrayObj = new ArrayObject($array);
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next()){

    echo $iterator->key() . ' : ' . $iterator->current() . '
';

    if( $iterator->key() === $lastKey &&
        $currentIteration < $maxIterations ){

        $iterator->rewind();
        ++$currentIteration;

        echo $iterator->key() . ' : ' . $iterator->current() . '
';
    }
}

OUTPUT:
0 : honda
1 : toyota
2 : suzuki
3 : mazda
4 : nissan
0 : honda
1 : toyota
2 : suzuki
3 : mazda
4 : nissan

Link: http://php.net/manual/en/class.arrayiterator.php
Answer: You can reset the foreach with: "using it in this below as well"
$value = "";

Or restart by pointing where to go after the end:
a:
"as restarting"
goto a;

So in the code from the asker in this post do like this:
a:
foreach($rows as $row){
  $value++;
  if(something true){
  continue foreach;
  }
  else {
  break;
  $value = ""; // A value reset
  goto a; //I mean start foreach again...
  }
$value = ""; //perhaps a value reset here?
}

how to force foreach reset in php


How to collect individual results of the threads within a block?

Question: In my Kernel, the threads are processing a small part of an array in global memory.
After processing I would also like to set a flag indicating that the result of the calculation is zero for all threads within a block:
__global__ void kernel( int *a, bool *blockIsNull) {
  int tid = blockIdx.x * blockDim.x + threadIdx.x;
  int result = 0;
  // {...} Here calculate result
  a[tid] = result;

  // some code here, but I don't know, that's my question...
  if (condition)
    blockIsNull[blockIdx.x] = true; // if all threads have returned result==0
}

Each individual thread owns the information. But I don't find an efficient way to collect it.
For example, I could have a counter in shared memory that is atomically incremented by each thread when result==0. So when the counter reaches blockDim.x it means that all threads have returned zero. Althought not tested, I am afraid that this solution will have a negative impact on performance (atomic functions are slow).
A zero result does not occur very often, so it is very unlikely to have zeros for all threads within a block. I would like to find a solution that has little impact on the performance in the general case.
What would be your recommendation ?
Answer: It sounds like you want to perform a block level reduction of the condition value across a block. Just about all CUDA hardware supports a set of very useful warp voting primitives. You could use the __all() warp vote to determine that each warp of threads satisfied the condition, and then use __all() again to check whether all warps satisfy the condition. In code, it might look like this:
__global__ void kernel( int *a, bool *blockIsNull) {

    // assume that threads per block is <= 1024
    __shared__ volatile int blockcondition[32];
    int laneid = threadIdx.x % 32;
    int warpid = threadIdx.x / 32;

    // Set each condition value to non zero to begin
    if (warpid == 0) {
        blockcondition[threadIdx.x] = 1;
    }
    __syncthreads();

    //
    // your code goes here
    //

    // warpcondition holds the vote from each warp
    int warpcondition = __all(condition);

    // First thread in each warp loads the warp vote to shared memory
    if (laneid == 0) {
        blockcondition[warpid] = warpcondition;
    }
    __syncthreads();

    // First warp reduces all the votes in shared memory
    if (warpid == 0) {
        int result = __all(blockcondition[threadIdx.x] != 0);

        // first thread stores the block result to global memory
        if (laneid == 0) {
             blockIsNull[blockIdx.x] = (result !=0);
        }
    }
}

[ Huge disclaimer: written in browser, never compiled or tested, use at own risk ]
This code should (I think) work for any number of threads per block up to 1024. You could, if required, adjust the size of blockcondition to a smaller value if you were confident of an upper block size limit less than 1024. Probably the smartest way would be to use C++ templating and make the warp count limit a template parameter.
Comment: I didn't know the warp level `__all()` vote function but it seems to be the appropriate answer. I will test it in the future. Thanks !


How to check if a view is grouped?

Question: In a views template, I need to check if the views rows are grouped. Which property of the $view object contains this information?

In the example below, $grouped = !empty($options['grouping'][0]); seems to work. However I don't know/understand all details about the $view object and I'm not sure if this really is a solid solution. Will this work in all situations?
Currently, my views-view-unformatted.tpl.php looks like this:
<?php
$grouped = !empty($options['grouping'][0]);
$heading_classes = $grouped ? ' class="group-heading"' : '';
?>

<?php if ($grouped): ?>

<?php endif; ?>

<?php if (!empty($title)): ?>
  <h3<?php print $heading_classes; ?>><?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

<?php if ($grouped): ?>

<?php endif; ?>

Answer: Some tips about your solution:
1- It looks right to me. I would try keep the logic separate from the template. I'd also declare my own template to avoid problems. Another style plugin, for example a custom style plugin, could use the original template.
HOOK_preprocess_views_view_unformatted(&$vars){
  if(!empty($options['grouping'])){
    $vars['heading_classes'] = $grouped ? ' class="group-heading"' : '';
    // My own template
    $vars['theme_hook_suggestions'] = 'views_view_unformatted_group';
  }
}

/*
* Implement hook_theme
*/
HOOK_theme($existing, $type, $theme, $path){
  return array(
    'views_view_unformatted_group' => array(
     'variables' => array(),
     'path' => 'PATH/TO/YOUR/MODULE',
     'template' => 'views_view_unformatted_group',
  ),
}

Template views_view_unformatted_group.tpl.php

 <?php if (!empty($title)): ?>
 <h3<?php print $heading_classes; ?>><?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
  <?php print $row; ?>

<?php endforeach; ?>

2 - The default function that manage the grouping is render_grouping_sets() in an style plugin object. The documentation warn about that:

Plugins may override this method if they wish some other way of handling
     * grouping

The unformatted list, html list, grid and table style inherit the default methods and they don't override it.
3 - If you have nested groups, Views wrap the parent group with the next function in theme.inc:
function theme_views_view_grouping($vars) {
  $view = $vars['view'];
  $title = $vars['title'];
  $content = $vars['content'];

  $output = '
';
  $output .= '
' . $title . '
';
  $output .= '
' . $content . '
' ;
  $output .= '
';

  return $output;
}

How to check if a view is grouped?


How do I wrap the label text of a checkbox with a span tag?

Question: I have noticed that Drupal 7 generates check-boxes with a markup like this:

<input type="checkbox">
Label text ..

I want to wrap  Label text .. inside a span tag, how to do that via the Drupal 7 API?
The result should be:

<input type="checkbox">
Label text ..

Answer: You would either need to override theme_form_element in your theme, or, do a hook_form_alter, target specific checkbox form elements, and change their #theme_wrappers callback to your own theme implementation.
I personally would do the latter, since overriding theme_form_element will change the default rendering for any form element in your theme, and that may not be desirable in every scenario.
Comment: Thanks.. My issue was related to Bootstrap's theme, I simply copied `theme_form_element` and `theme_form_element_label` to my custom theme's `template.php` and that's is, issue solved and desired output obtained.


Is a Lie group connected?

Question: I want to know if a Lie group is connected in general situation.I also want some example of Lie group. I will appreciate your help.
Comment: For example $GL(n)$ is not connected, it has two components.
Comment: In general a Lie Group is not connected, e.g. $O(n)$ has two connected components.
Answer: Lie groups need not be connected in general. Examples are the isometry groups of compact Riemannian manifolds. They are nonconnected Lie groups.
Many examples of Lie groups arise from classical matrix groups. For more references see here.

Is a Lie group connected?


How to use press statistic for model selection

Question: I am confused about how to use the PRESS statistic to compare models.I understand that the PRESS statistic is calculated by summing the square of the residuals as :
$$\text{PRESS} = \sum_{i=1}^n (y_i - \hat{y}_{i, -i})^2$$
where the residual is the difference between the observed and predicted value for the $i$-th data point, with the prediction coming from a model trained on data with the $i$-th data point removed. My confusion lies in the fact that a new regression equation (hence a new model) is estimated each time a data point is dropped (so $n$ different models are trained in the process of calculating PRESS) - so the final PRESS statistic is not tied to a single model. In that case, how can you use the PRESS statistics to compare two different models? How do you calculate a PRESS statistic for a given regression model? I think I am making a basic mistake somewhere here but not sure where my reasoning is off. Thanks for any help.
Answer: You calculate PRESS on a model trained on $n$ values to get an idea of its out-of-sample performance, by leaving out one sample at a time. So while you indeed end up with $n$ models to determine the statistic, you eventually use the original model trained on all $n$ values.
Since you are only leaving out a single observation at a time (like in LOOCV), the addition of the 'last' sample has minimal influence on the final model. Because of this you can safely use PRESS to compare models, even though the actual models you are comparing were not used to calculate it.
If you have a larger sample size, you could consider a form of nested cross-validation, comparing models with the inner cross-validation and evaluating the performance of the 'winning' model on the outer cross-validation loop.
Comment: So the $n$ models that are calculated are basically the same since leaving out a single observation does not change the result much? So I can use Press to compare two models with different variables? I'm a little confused how the Press is calculated for a single model.
Comment: Also what if the omitted point was an outlier and caused differences in the estimated model?
Comment: Upvoted for the excellence of the answer.
Comment: @user2450223 Just like least squares, PRESS is not very robust to outliers, because the differences are squared. However, remember that you are adding $n$ models, so the larger $n$ is, the smaller this outlier's contribution is to the total PRESS statistic.
Comment: @user2450223: if leaving out a singe data point causes substantial changes in the model, then the model is *unstable*. Checking that your model fitting procedure is stable is worth while and recommended. Unfortunately, LOO cross validation schemes do not allow this (iterated aka repeated cross validation does, and that requires more than 1 case to be left out) as they have collinearity between (surrogate) model and test case so that "case-to-case" variance cannot be separated from "model-to-model" variance.
Comment: The linear algebra means you can work out the leave-one-out outputs of the model, but we are not limited to using them for computing the leave-one-out squared error, we can estimate any model selection criteria we like that depends only on the outputs (e.g. mean absolute error, or AUROC or accuracy for classifier systems)
Answer: "My confusion lies in the fact that a new regression equation (hence a new model) is estimated each time a data point is dropped"
This usually isn't the case, at least for standard [ridge-] regression models; you don't actually create a new model each time, but instead can work out what the output of that model would be by looking at the "hat matrix"
$\matrix{H} = \matrix{X}[\matrix{X}^T\matrix{X}]^{-1}\matrix{X}^T$
You can think of the hat matrix as providing information about the stability of the model to each datapoint ("leverage"), so you can view this as being a representation of the quality of the model.  If the model is highly sensitive to the particular sample of data to which it has been fitted (points have high leverage), it's PRESS statistic will be much higher than the resubstitution MSE (the MSE on the training data).
However, cross-validation (including PRESS) is best thought of as a means of evaluating the performance of a method of constructing a model, rather than directly of the model itself.  So PRESS is an estimate of the generalisation performance of a model trained using that procedure on the entire dataset.


why do we need to prove that the limit of a contraction is a fixed point in the contraction mapping theorem

Question: In this chapter they first prove that iteratively applying a contraction is a cauchy sequence. Since the metric space is complete we know that sequence converges, and it does so to a unique point. So why do they then additionally prove that the point of convergence is a fixed point of the contraction, isn't this already implied by the proving the sequence is cauchy. I feel like it's more of a corollary since it applies to any arbitrary function that is continuous in the domain.
Answer:
So why do they then additionally prove that the point of convergence
is a fixed point of the contraction

Because that's what the theorem states, and therefore, that's what the proof should conclude with.

isn't this already implied by the original proof.

What do you mean by "original proof"? There is only one proof and it can be divided into the following parts:

Prove that the sequence, defined by $x_{n+1} = T(x_n)$ converges.
Prove that if a sequence, defined by $x_{n+1}=T(x_n)$, converges, then the limit of the sequence is a fixed point of $T$.
Conclude from 1 and 2 that $T$ has a fixed point.
Prove that $T$ can have at most one fixed point.
Conclude from 3 and 4 that $T$ has exactly one fixed point.

Now, sure, alternatively, the authors could cite point number 2 above as a separate lemma, and prove it before proving the main theorem, but I'd say it's cleaner this way, for two reasons:

The proof is short, so splitting it into subtheorems would not help readability
The lemma itself is not all that interesting.

Edit:
It is, of course, also possible to prove point 3 directly from 1 and from the fact that $T$ is continuous. However, this would most probably lead to a proof that is harder to follow, and possibly even longer than original.
But the mere fact that you can prove something without a particular sub-lemma does not mean that that particular lemma is "useless" for the proof. Technically, every proof in mathematics can be trimmed down to base principles, but at a great cost of readability.
Comment: Sorry I could have made myself a bit clearer, doesn't proving 1. (the sequence is cauchy) imply 2.?
Comment: @questions You also need that $T$ is continuous.
Comment: i mentioned the continuity requirement in my post, so that should mean 2.) is really a corollary of proving 1.)  right?
Comment: @questions No. It is not a corrolary. $A$ is a corrolary of $B$ if the logical statement $B\implies A$ is true, and that is simply not the case here.
Comment: @questions The statement 2 is a corrolary of **two** separate facts. One, the sequence $x_n$ converges, and **two**, $T$ is continuous. Without continuity of $T$, you cannot infer 2 from 1 alone.
Comment: @5xum but in this case T refers to a contraction which is continuous on the domain by definition, so proving 1 would be sufficient surely.  2 doesn't prove that T is continuous it just states that if T is continuous then the point of convergence is a fixed point. Since we know that T is both continuous (by definition) and induces a cauchy sequence it directly implies 2.
Comment: @questions You cannot, logically, infer point 3 from **only** from point 1. If you only prove point 1, you have not proven that $T$ has a fixed point. That's why you either *need* point 2, or you need some other way of proving point 3 directly from point 1. But any other way will probably be longer, which is why the proof you linked went the way it went. If you think the proof could be significantly shortened, I invite you to try it, write down the shorter proof, and I can go through it to see if it is logically sound.
Comment: @5xum Using just 1, and the fact that T is continuous within the domain. Let x' be the point of convergence if T(x') =/= x' then we could never converge to x' therefore, x' must be a fixed point
Comment: @questions OK, great. You did it, you proved point 2. So... what's your question?
Comment: @5xum I just wanted to know whether 2. was necessary.  As you said $A$ is a corollary if $B \implies A$ which i believe makes 2. a corollary. I don't feel like 2 contributes to the theorem it seems like it was more to just help with clarity but I wasn't entirely sure so I decided to ask
Comment: @questions If you do not feel like 2 contributes to the theorem, feel free to write the proof without it, and compare the two proofs. I can almost guarantee one will be much less clear. And adding clarity **is** a contribution to the theorem. I mean, you can prove the theorem from first principles, so basically, anything above first principles is only there to add clarity.
Comment: @5xum I do agree with that, if you append your answer to summarise our discussion i'd be happy to select your answer. and if you could do so without modifying the original answer too much because I do also like the clarity of your original answer in highlighting the steps
Comment: @questions I added another paragraph to my answer, I think it now has all you asked.


Como percorrer uma lista encadeada em java

Question: Preciso percorrer uma lista encadeada para comparar se o número que o usuário irá digitar é igual a um atributo de uma classe (médicos) que tem uma lista encadeada.
Tenho as seguintes Classes: Nó, Lista_Simples, Médicos e Sistema.
O erro está no case 2 do Sistema, estou tentando usar um atributo do tipo Nó que está em Lista_Simples para percorrer (o aux está pegando o valor de primeiro que chamei de prim), só que acredito que talvez essa não deva ser a forma correta de percorrer.
Classe Nó:
public class No {
    private Medicos m;
    private No prox;

public No(Medicos me) {
    this.setM(me);
    this.setProx(null);
}
}

Classe Lista_Simples:
public class Lista_Simples {
private No prim;        //Primeiro nó
private No ult;         //Último nó
private int qntdno;     //Quantidade de nós
private No aux;

 Medicos M = new Medicos();

//Construtor
public Lista_Simples(){
    this.prim = null;    //Iniciando com null
    this.ult = null;     //Iniciando com null
    this.qntdno = 0;     //Iniciando com 0
    this.aux = this.prim;
}

//Saber se a lista é vazia, se estiver nulo então é criado o primeiro nó
public boolean listavazia () {
    return (this.prim == null);
}

public void inserirPrimeiro(Medicos p) {
    No novoNo = new No(p);
    //Se a lista não for vazia o primeiro nó também é o último
    if(this.listavazia()){
        this.ult = novoNo;
    }
    novoNo.setProx(this.prim);      //O próximo nó se tornará o primeiro nó
    this.prim = novoNo;             //O novo primeiro será novoNo
    this.qntdno++;                  //Incrementando a contagem de quantidade de nós
}
public No getAux() {
    return aux;
}

public void setAux(No aux) {
    this.aux = prim;
}

}

Classe Médicos:
public class Medicos {

private String nome;
private int crm;

public int getCrm() {
    return crm;
}

public void setCrm(int crm) {
    this.crm = crm;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}
}

Classe Sistema:
  public class Sistema {
//static Pacientes P;
//Medicos m;
//m = new Medicos();
//private int crmnovo = 0;

public static void main(String[] args) {

    //Pacientes P = new Pacientes();
    Lista_Simples ListaPacientes = new Lista_Simples();
    Lista_Simples ListaMedicos = new Lista_Simples();

    while(true) {
        System.out.println("Escolha a ação que deseja executar:"
                + "\n1-Cadastrar Paciente"
                + "\n2-Cadastrar Médico"
                + "\n3-Editar dados do Médico");
        System.out.println("Digite o número da ação que deseja executar: ");
        Scanner menu = new Scanner(System.in);
        int acao = menu.nextInt();

        Medicos M = new Medicos();

        switch(acao) {
            case 1:
                int fim2 = 0;

                Scanner nomeM = new Scanner(System.in);
                System.out.println("\nDigite o nome do médico:");
                String nomemedico = nomeM.nextLine();
                M.setNome(nomemedico);
                System.out.println("\nO nome é "+M.getNome());

                Scanner crmM = new Scanner(System.in);
                System.out.println("\nDigite o CRM do médico:");
                String crm = crmM.nextLine();
                M.setNome(crm);
                System.out.println("\nO CRM é "+M.getCrm());

                do {
                    ListaMedicos.inserirPrimeiro(M);
                    fim2++;
                    break;
                }while(fim != 0);

                System.out.println(ListaMedicos.imprimirLista(M));

                break;

            case 2:
                //Medicos M = new Medicos();
                System.out.println("\nDigite o seu CRM: ");
                Scanner editar = new Scanner(System.in);
                int crmexiste = editar.nextInt();
                //System.out.println("\n"+crmexiste);
                while (ListaMedicos.M.getCrm() != crmexiste) {
                    if (crmexiste != ListaMedicos.M.getCrm()){
                        //O ERRO ESTÁ AQUI, BASICAMENTE EU NÃO CONSIGO PERCORRER A LISTA DE MÉDICOS, TEM ALGUNS CÓDIGOS QUE COMENTEI AQUI QUE DERAM ERRADO
                        System.out.println("Erro aqui!");
                        //ListaMedicos.getAux().setProx(ListaMedicos.getAux());
                        ListaMedicos.getAux().getProx();
                        System.out.println(ListaMedicos.getAux());

                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                    }
                    else {
                        //M2.getListademdc().pesquisarNo(crmexiste);
                        System.out.println("\nDigite o seu CRM: ");
                        Scanner novo = new Scanner(System.in);
                        int novocrm = novo.nextInt();
                        ListaMedicos.M.setCrm(novocrm);
                    }
                }
                break;

        }
    }
}
}

Desde já obrigado pela ajuda!
Comment: A sua ação "cadastrar paciente", cria um novo médico? E vc precisa usar lista encadeada ou pode resolver com outra estrutura?
Answer: Vc não consegue percorrer a lista de médicos pq vc está acessando o objeto Medicos que está na sua ListaSimples e não os médicos de cada nó. Não tem necessidade de criar um médico na sua classe ListaSimples, portanto remova essa linha dessa classe: Medicos M = new Medicos();
1) Antes de percorrer a lista de médicos, vamos preenche-la corretamente.
Construa um objeto Medicos novo toda vez que vc for cadastrar um novo médico. Da forma que está ai, vc criou um objeto e está modificando-o toda vez que chama o case 1. Portanto, mova a sua linha Medicos M = new Medicos(); para o início do seu case 1, ficando assim
Deixe o seu case 1 assim:
2) Percorrer a lista
Para percorrer a lista, vc deve ir nó por nó, portanto o seu while do case 2 não irá funcionar. A sua classe Sistema com as alterações ficaria basicamente assim:
public class Sistema {
//static Pacientes P;
//Medicos m;
//m = new Medicos();
//private int crmnovo = 0;

public static void main(String[] args) {

    //Pacientes P = new Pacientes();
    Lista_Simples ListaPacientes = new Lista_Simples();
    Lista_Simples ListaMedicos = new Lista_Simples();

    while(true) {
        System.out.println("Escolha a ação que deseja executar:"
                + "\n1-Cadastrar Paciente"
                + "\n2-Cadastrar Médico"
                + "\n3-Editar dados do Médico");
        System.out.println("Digite o número da ação que deseja executar: ");
        Scanner menu = new Scanner(System.in);
        int acao = menu.nextInt();

        switch(acao) {
            case 1:
                int fim2 = 0;
                // LINHA MOVIDA
                Medicos M = new Medicos();

                Scanner nomeM = new Scanner(System.in);
                System.out.println("\nDigite o nome do médico:");
                String nomemedico = nomeM.nextLine();
                M.setNome(nomemedico);
                System.out.println("\nO nome é "+M.getNome());

                Scanner crmM = new Scanner(System.in);
                System.out.println("\nDigite o CRM do médico:");
                String crm = crmM.nextLine();
                M.setNome(crm);
                System.out.println("\nO CRM é "+M.getCrm());

                do {
                    ListaMedicos.inserirPrimeiro(M);
                    fim2++;
                    break;
                }while(fim != 0);

                System.out.println(ListaMedicos.imprimirLista(M));

                break;

            case 2:
                //Medicos M = new Medicos();
                System.out.println("\nDigite o seu CRM: ");
                Scanner editar = new Scanner(System.in);
                int crmexiste = editar.nextInt();
                //System.out.println("\n"+crmexiste);

                No no = ListaMedicos.getPrim();

                // NOVO WHILE
                while (no != null && no.getMedicos().getCrm() != crmexiste) {
                    if (crmexiste != ListaMedicos.M.getCrm()){
                        //O ERRO ESTÁ AQUI, BASICAMENTE EU NÃO CONSIGO PERCORRER A LISTA DE MÉDICOS, TEM ALGUNS CÓDIGOS QUE COMENTEI AQUI QUE DERAM ERRADO
                        System.out.println("Erro aqui!");
                        //ListaMedicos.getAux().setProx(ListaMedicos.getAux());
                        ListaMedicos.getAux().getProx();
                        System.out.println(ListaMedicos.getAux());

                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                    }
                    else {
                        //M2.getListademdc().pesquisarNo(crmexiste);
                        System.out.println("\nDigite o seu CRM: ");
                        Scanner novo = new Scanner(System.in);
                        int novocrm = novo.nextInt();
                        ListaMedicos.M.setCrm(novocrm);
                    }
                }
                // PASSA PARA O PRÓXIMO NÓ
                no = no.getProx();
                break;

        }
    }
}
}

Olhando para as suas classes, vc vai precisar criar os getters utilizados em cada uma (getProx(), getMedicos() e getPrim())
Dica: Tem muita coisinha ai que poderia ser melhorada e algumas boas práticas poderiam ser aplicadas, então de uma pesquisada sobre quando puder. Segue um link sobre listas encadeadas tbm que vai ajudar.
https://www.caelum.com.br/apostila-java-estrutura-dados/listas-ligadas/
Comment: Entendi. O problema de deixar no geral é que vc vai trabalhar em cima do mesmo objeto sempre. Se vc não criar um novo objeto (`new Medicos()`) toda vez que for cadastrar um novo, ele vai alterar aquele objeto já existente, entendeu? Já na parte de edição vc vai precisar buscar o objeto e não criar um novo. Se estiver meio confuso ainda, avisa que eu te explico melhor. Disponha, o intuito aqui é ajudar mesmo. Abraços]
Comment: Sobre os getters eu já tenho eles, só não coloquei aqui para não ficar algo cansativo afinal podem ser gerados pela própria IDE. Como posso utilizar o Medicos M = new Medicos(); no segundo case? Aqui aparece como se fosse uma "variável local "(não sei muito bem sobre java, sei que não é uma variável e sim um objeto) do case 1
Comment: Ah sim, entendi. Vc pode deixar a declaração de M na sua classe e a inicialização do objeto no momento necessário. O importante é que seja um objeto novo, uma nova referência. Mas qual seria a necessidade de ter um novo Medico no case 2?
Comment: A sua lógica de negócio permaneceu a mesma, mas explica o que vc quer fazer quando for o case 2.
Comment: Basicamente eu tava testando como funcionava, por isso deixei como comentário ali no 2, além disso eu deixei o New Medicos no geral ali (uma espécie de global) para que pudesse usar tanto no case de cadastro quanto no de edição. Quero te agradecer, você foi paciente (já que muitos usuários costumam reclamar de descrição mal elaborada, tentei deixar a minha o mais simples e mesmo assim fui negativado, acho que posso melhorar ainda mais) e se esforçou por um problema de outra pessoa. Muito obrigado mesmo pela sua ajuda!


Suggested R packages for frontier estimation or segmentation of hyperspectral images

Question: An hyperspectral image is a multidimensional image with more than 200 spectral bands i.e. an image for which each pixel is a vector of dimension 200 (most often it is a sampled spectral curve that is encoutered in satellite imagery or medical imagery).
What are the implemented package (I am especially interested in R packages but if other free algorithms exist, I will try them) for frontier detection and (unsupervised) segmentation of this type of images?
Answer: Not an R package, but D. A. Landgrebe from Purdue (author of Signal theory methods in multispectral remote sensing) has sponsored the MultiSpec freeware.  Its a rather clunky GUI but gets the job done for most of the common hyperspectral algorithms.
Comment: interesting ! there are testing images to try it, exercices to learn how to use it...
Answer: I am afraid there is no; during my little adventure with such data we have just converted it to a data frame form, added some extra attributes made from neighborhoods of pixels and used standard methods. Still, packages ripa and hyperSpec might be useful.
For other software, I've got an impression that most of sensible applications are commercial.
Answer: The best place to look for free/open source capabilities of this nature is GRASS GIS.  The image processing manual is here.  Because this is constantly undergoing development, it would be worthwhile posting an inquiry on one of the GRASS user lists (found through links on the home page here.
Comment: Thanks a lot for the answer, I'll do the inquiry when I'll have more time
Comment: We have also a dedicated Wiki page at http://grass.osgeo.org/wiki/R_statistics
Answer: This is a very late response, so this may no longer be of interest, but I am working on putting together an R library with various hyperspectral image processing capabilities. At the moment my focus has been on endmember detection and unmixing. If this is still something which is of interest please let me know. My hope is to publish a beta version to CRAN or R-Forge in the near future but I would be happy to send out the code itself.
Best,
Dan
Comment: Hi Dan, Good initiative, I'll try to contact you.
Comment: Has anything come of this/will come of this? I'm much interested...


Replicating chord tones

Question: I've been engrossed in Jazz music for 8 months now. Since I've had 9 years experience on guitar, I can usually pick out and sing the melody being played. However, chord tones and their harmonic 'togetherness' cause my ear to stumble.
To dissect this further, I played simple open chords on my guitar:
An A minor, C major, Cmajor 7. I'd try to sing what I hear and find myself flat. If I arpeggiate the chords, I can sing the tones.
I'm wondering how I can advance my ears ability to hear chord tones? The discrepancy is strongest when I try to sing them. Is it as easy as keeping an eye on it, continued practice? Or is there a more in-depth lesson plan.
I do have a guitar instructor. We're currently working through classical pieces and I don't believe singing/ear training is his specialty.
Thanks so much guys, sorry for the dense question. I tried to format it so it's easier to read.
Comment: 20 minutes in front of the piano singing out different intervals will be tremendous aural training. Just make sure you play the piano where it is comfortable for you to sing.
Answer: I have great news for you!
There are sooooo many tools readily available with a simple Google search. I suggest musictheory.net, but there are so many options if you look for ear training exercises.
Here's a real tough exercise that I used to do for my musicianship class:

Give yourself a starting pitch.
Sing up a Perfect 5th
Sing down a tri-tone (Diminished 5th/Augmented 4th)
Sing up a Perfect 4th
Sing down a Major 3rd
Sing up a Minor 3rd
Sing down a Major 2nd
Sing up a Minor 2nd

Film yourself doing this or similar pitch strings.
Play the notes on your guitar alongside the recording and you'll see what intervals in particular give you trouble.
Hope this helps, Good Luck!

Replicating chord tones


Permutation combination problem

Question: This is how Edward's Lotteries work. First, 9 different numbers are selected. Tickets with exactly 6
of the 9 numbers randomly selected are printed such that no two tickets have the same set of numbers.
Finally, the winning ticket is the one containing the 6 numbers drawn from the 9 randomly. There is
exactly one winning ticket in the lottery system. How many tickets can the lottery system print?
Comment: Have you learned about binomial coefficients?
Answer: The number of tickets is the number of ways to choose $6$ numbers from $9$.
How do we calculate that that number? It is simplest if we know a formula for the binomial coefficient $\binom{9}{6}$ aka $C(9,6)$ aka $C^9_6$. One expression for this is $\frac{9!}{6!3!}$. Now we compute. There is a lot of cancellation.
Or we can figure out the number from first principles. How many ways are there to choose $6$ numbers (the ones that will appear on tickets) from $9$? Just as many as there are ways to choose the $3$ numbers that don't appear. (Yhis "feels" easier, since $3$ is smaller than $6$.)
There are $(9)(8)(7)$ three number strings made up of different numbers. The $6$ strings $abc,acb, bac,bca,cab,cba$ all represent the same ticket, the same choice of rejected numbers. So the total number of tickets we can print is $\frac{(9)(8)(7)}{6}$.

Permutation combination problem


Borel measurable function on the Euclidean space $\pmb{R}^4$

Question: I want to know if my function $f$ is Borel measurable function or not.
To be clear, I use the terms which are introduced in $\\$https://dspace.mit.edu/bitstream/handle/1721.1/14254/22712180-MIT.pdf?sequence=2 , page 17.
$\\$
It says, for any topological space $X$, the Borel sigma-algebra of $X$ is denoted by $\mathcal{B}_X$; it is the smallest sigma-algebra which contains all of the open sets in X. A subset of X is Borel measurable if it belongs to $\mathcal{B}_X$... . . . In particular, a real-valued function $f:X\to \pmb{R}$ is Borel measurable if $f^{-1}(B) \in \mathcal{B}_X$ for all Borel measurable $B \subset \pmb{R}$. The space of all bounded Borel measurable functions on $X$ is denoted by $\mathcal{B}(X)$.
$\\$
Now, the function $f$ is
$$
f:\pmb{I} \to \pmb{O}
$$ where $I=([0,a_1],[0,\infty),[0,\infty),[0,a_2])$ which means that the input space of the function $f$ has four dimension and the ranges of each elements are $[0,a_1],[0,\infty),[0,\infty),[0,a_2]$ respectively($a_1$ and $a_2$ are positive real numbers). The $O$ has only one dimension, $O=[0,o_1]$ ($o_1$ is positive real number).
$\\$
I think the input space $I$ is a Borel measurable subset of $\pmb{R}^4$ because every interval is a Borel set.
However, I do not understand why the author used subset notation for $B\subset\pmb{R}$. I think $f^{-1}$ is one of the function which should take the scalar value as input in here. But $B\subset\pmb{R}$ indicates that $B$ is set. So I am not sure how to check the function $f$ is Borel measurable function or not, i.e., want to know $f \in \mathcal{B}(I)$.
$\\$
Comment: Note that we usually denote $I= [0,a_1]\times [0,\infty)\times [0,\infty)\times [0,a_2)$ also the word "the" in the sentence "Now, the function $f$ is $f:I\rightarrow O$" makes no sense because there are infinitely many functions with such domain\range.
Answer: You haven't told us what the function is, only what its domain and range are, so we can't answer this.
As for the notation $f^{-1}(B)$, it denotes the preimage of the set B, i.e the set of points $x$ for which $f(x) \in B$.  A function is measurable if the preimage of each measurable set is measurable.
Comment: (+1). If the OP asks whether **any** function $f:I\rightarrow O$ is Borel measurable then the answer is **NO**.


Limite de caracteres do bcrypt no PHP

Question: Na documentação do PHP referente a função password_hash possui o aviso:

Cuidado Usando PASSWORD_BCRYPT como algoritmo, resultará no parâmetro password sendo truncado em um comprimento máximo de 72 caracteres.

Ou seja, se eu passar uma senha com mais de 72 caracteres a função desconsiderara os caracteres a mais do final
Na pergunta aqui SOpt Como fazer hash de senhas de forma segura, é dito pela melhor resposta sobre o bcrypt:

Desvantagens:
[...]

A senha de entrada é limitada a 51 caracteres. Para senhas maiores, alguém teria que combinar o bcrypt com uma função de hash (calcula o hash da senha, e usa o resultado com bcrypt). Combinar primitivos criptográficos tem riscos, então isto não é recomendado para uso geral.

Dúvidas:

É isso que o PHP usa para aumentar o limite de caracteres?

Esse limite extra traz algum problema de segurança?

Ele pode ser desabilitado ou burlado?
Answer: O limite é de 72 bytes, não de 51. O limite de 51 é errado, ou é uma confusão, ou as implementações recentes não seguem a original. Na verdade, me parece que esse limite tem origem do limite do Blowfish, o Blowfish é um algoritmo de encriptação onde o tamanho da chave era de 448 bits (56 bytes), tal algoritmo é usado pelo BCrypt.
A versão do Bcrypt 2A (e seguintes) exige que o a senha use UTF-8 e que termine um nulo, assim é utilizado 71 caracteres + 1 nulo.

É isso que o PHP usa para aumentar o limite de caracteres?

Não. O PHP usa o Bcrypt normal, inclusive o resultado dele pode ser usado em outras implementações, de outras linguagens.

Esse limite extra traz algum problema de segurança?

Não, em geral. Nenhum usuário comum utiliza senhas maiores do que 71 caracteres, entretanto seria ideal limitar a entrada do usuário e notifica-lo que a senha é longa.

Ele pode ser desabilitado ou burlado?

Use outro algoritmo, o PHP já oferece suporte para o Argon2id, que é o vencedor do PHC e em versões antigas já tem suporte para o PBKDF2, que é uma alternativa também, embora não aconselho. Se você está usando alguma versão obsoleta, então segurança não é prioridade.
Se você realmente quer usar gambiarras, existe como, mas também possuem efeitos colaterais.
password_hash(base64_encode(hash("sha384", $password, true)), PASSWORD_BCRYPT)

Isso irá fazer com que a entrada do usuário use o sha384, primeiro, antes do BCrypt. O BCrypt irá usar o resultado o sha384 (48 bytes) em Base64 (ficando dentro do limite, usando 64 caracteres). Mas, você irá diminuir a entropia máxima de 71 para 48. A razão de usar o sha384 é por causa do tamanho, e o Base64 é para impedir nulos prematuros, porque o BCrypt é vulnerável a nulos, por assim dizer.

Limite de caracteres do bcrypt no PHP


Windows azure, how to clear folder DevFCLogs?

Question: I'm working with Windows Azure Platform. I created a service and when I launch it locally that launches the Windows Azure Emulator. This emulator writes logs to the following directory
<code>C:\Users\UserName\AppData\Local\dftmp\DevFCLogs
</code>
But Windows Azure Emulator writes every 2 minutes 10mb file!
When I stop my service, the Emulator doesn't stop, so it continues to write logs.
When I stop it manually I have to clear the folder DevFCLogs.
How can I reduce the log files or stop this log system ?
Answer: There's something wrong, either with your app, or with your emulator configuration/installation.
The DevFCLogs are limited to 10Mb. Everytime they reach 10Mb, they'll roll over to a new log file. For me during a typical development day, this occurs maybe once every 90 minutes.
In addition, I only seem to have logs going back the previous 48 hours, so the emulator must be clearing up it's own logs automatically.
Look in the log files and see if there are any obvious errors which you can fix, or post the errors here and I'll see if I can help
Comment: Thanks for your answer. I don't find any error in log files. I change my service so now it run in console mode. My application uses many thread, i don't know if this has an influence... ?


Rack error on server with each cap:deploy

Question: Each time i run on my local machine cap:deploy i get next error when i open my web-page:
Ruby (Rack) application could not be started
Error message:
git://github.com/ctran/annotate_models.git (at master) is not checked out. Please run `bundle install` (Bundler::GitError)
Exception class:
PhusionPassenger::UnknownError
Application root:
/vol/www/apps/ror_tutorial/current
Backtrace:
#
File
Line
Location
0
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/source.rb
572
in `rescue in load_spec_files'
1
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/source.rb
570
in `load_spec_files'
2
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/source.rb
385
in `local_specs'
3
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/source.rb
555
in `specs'
4
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/definition.rb
147
in `block in resolve'
5
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/definition.rb
145
in `each'
6
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/definition.rb
145
in `resolve'
7
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/definition.rb
90
in `specs'
8
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/definition.rb
135
in `specs_for'
9
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/definition.rb
124
in `requested_specs'
10
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/environment.rb
23
in `requested_specs'
11
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler/runtime.rb
11
in `setup'
12
/usr/local/rvm/gems/ruby-1.9.3-head/gems/bundler-1.0.21/lib/bundler.rb
110
in `setup'
13
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/utils.rb
326
in `prepare_app_process'
14
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb
156
in `block in initialize_server'
15
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/utils.rb
572
in `report_app_init_status'
16
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb
154
in `initialize_server'
17
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb
204
in `start_synchronously'
18
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb
180
in `start'
19
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb
129
in `start'
20
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb
253
in `block (2 levels) in spawn_rack_application'
21
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server_collection.rb
132
in `lookup_or_add'
22
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb
246
in `block in spawn_rack_application'
23
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server_collection.rb
82
in `block in synchronize'
24

prelude>
10:in `synchronize'
25
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server_collection.rb
79
in `synchronize'
26
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb
244
in `spawn_rack_application'
27
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb
137
in `spawn_application'
28
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb
275
in `handle_spawn_application'
29
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb
357
in `server_main_loop'
30
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb
206
in `start_synchronously'
31
/usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11/helper-scripts/passenger-spawn-server
99
in `'

I fix that by next lines:
$ bundle install --without development test
$ bundle install --deployment
$ service nginx restart

But i really tired to do that again and again. Does anyone know how to fix it forever?
My gemfile:
source 'http://rubygems.org'

gem 'rails', '3.1.3'
gem 'gravatar_image_tag'
gem 'will_paginate'
gem 'rack'
gem 'rake'
gem 'texticle', "2.0", :require => 'texticle/rails'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails'
  gem 'coffee-rails'
  gem 'uglifier'
end

gem 'jquery-rails'

group :development do
  gem 'capistrano'
  gem 'rspec-rails'
  gem 'therubyracer-heroku'
  gem 'pg'
  gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'
  gem 'faker'
end

group :test do
  gem 'rspec-rails'
  gem 'webrat'
  gem 'spork'
  gem 'autotest'
  gem 'autotest-rails-pure'
  gem 'autotest-fsevent'
  gem 'autotest-growl'
  gem 'factory_girl_rails'
end

group :production do
  gem 'pg'
  gem 'faker'
end

config/deploy.rb
set :user, "root"
set :rails_env, "production"

default_run_options[:pty] = true
set :repository,  "git://github.com/Loremaster/sample_app.git"

set :application, "ror_tutorial"
set :deploy_to, "/vol/www/apps/#{application}"

set :scm, :git
set :branch, "master"
set :deploy_via, :remote_cache

server "my.ip", :app,
                          :web,
                          :db, :primary => true

# If you are using Passenger mod_rails uncomment this:
namespace :deploy do
   task :start do ; end
   task :stop do ; end
   task :restart, :roles => :app, :except => { :no_release => true } do
     run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
   end
end

My Server system:
Ubuntu 10.04 LTS
PostgreSQL 9.1
Rails 3.1.3
Ruby 1.9.3p27
Nginx 1.0.11 (installed/compiled by passenger)
Phusion passenger 3.0.11
Capistrano

Comment: did you solve this issue? I have the same
Comment: I created a task in capistrano.
Answer: capistrano does not automatically run the bundler command unless you specify that you use bundler in your deploy.rb. I add this line to the top of my deploy.rb file to activate bundler integration. Capistrano then automatically runs the right bundler commands when deploying.
require 'bundler/capistrano'  # Add Bundler integration to capistrano

Your solution, of running bundle install --without development test and bundle install --deployment is effectively the same, but has to be kept up to date manually. In addition, you could distill this into a single command: bundle install --deployment --without development test. In your current solution, you are running bundler twice.
Answer: I had the same problem. Of our 5 environments, our staging environment started doing this out of the blue. I was not able to find out the cause, but I was finally able to deploy  by backing up then recreating our deploy directory, followed by cap deploy:setup, cap deploy:cold then cap deploy


Can I migrate a single disk from a datastore to another with "disks consolidation is needed" on VM?

Question: I have a VMware's VM with configuration issue "Disks consolidation is needed" but Consolidation fail because datastore is full.
In this situation, Can I migrate a single disk from this full datastore to another (with empty space)? Or is it blocked?
Answer: VCSA is up and ok and I can migrate disk in this situation.


Alternatives to pvals.fnc to compute confidence intervals for fixed effects?

Question: Lately I keep encountering the same problem and I'm wondering whether other people have been able to get around it. I'm running a mixed effects model using lmer(). My model has by-subject and by-item intercepts and slopes, and random correlation parameters between them. Since the current version of lmer() does not have MCMC sampling implemented, I cannot use pvals.fnc(). I get this message:
Error in pvals.fnc(m, withMCMC = T) :
MCMC sampling is not implemented in recent versions of lme4
for models with random correlation parameters

pvals.fnc() is also the function I use to get confidence intervals (HPD95lower and  HPD95upper were two columns in the pvals.fnc output). Does anyone know of an alternative way of getting confidence intervals for the fixed effects estimates in the model? Or does using models with random correlations means that we can no longer get CIs from R?
Thanks!
NOTE: I've seen this question asked in other forums in slightly different ways. However, the answers always seem to involve (1) calculating something different as an alternative to the confidence intervals, (2) some complicated solution that is unclear  (at least to me) how to implement. I would like to know if there is some alternative way of computing CIs that is both mainstream (so that other researchers can use it) and has a function to do it in R, since I am not a programmer and I feel that trying to create that function myself would be error prone.
Comment: I would also note that the `?pvalues` help page in the the new version of `lme4` includes a lot of information on this topic.
Comment: Note that a confidence interval/CI is not the same as a Highest Posterior Density/HPD interval, or a Bayesian Credible Interval.
Comment: that's something we wanted to improve.  The number of random-effects parameters (which come first) is `n_ran <- length(getME(model,"theta"))`; the number of fixed-effect parameters is `n_fix <- length(fixef(model))`.  Thus you should be able to use `params=(n_ran+1):(n_ran+n_fix)` to get just the fixed effect parameters profiled.
Comment: @BenBolker: Thanks! I hadn't updated `lme4` in a while and I didn't know about these useful features. I am trying to use `confint` now, trying to get profile CIs. Do you know if there is a simple way to have it estimate CIs only for the fixed effects? Otherwise, given my the structure of model, it takes forever to run and it also stops  if any of the parameters cannot be estimated (which is likely when you have many, I think)
Comment: I know you have `params=` to specify the parameters you want to get CIs for, but this requires you knowing which number corresponds to which parameter, and I don't know how to do that
Answer: Most probably the packages lmerTest and lsmeans provide readily available routines for what you are looking for. Mind you, neither of them uses MCMC methodology. If you want to use something resampling-based, you can use lme4's native bootMer() function to bootstrap your model and get parametric bootstrap estimates (ver. 1.0-4 or newer).
Answer: This answer would have deserved comment status at best, but comments are too short and don't really lend themselves to extended mock code.
Also, it seems you already got a more sensible answer by @user11852, but I wanted to give a more general answer (though see the comments below!).
If all else fails, one may always (?) obtain CIs from bootstrapping. In your specific case, this may be computationally infeasible, since running the model 1000 or so times may take half a century, but it should be fairly fool proof. I don't know R well, so here is some mock code in fake matlab for the 95% CI for the output generated by some parameter estimation function, such as intercepts in lmer. As a special feature, it bootstraps individual subjects and for each subject generates bootstrapped samples of data points for this subject.
a = data_set
s = (# of bootstrap iterations, e.g. 1000)
n = (# of subjects)

% main loop over bootstrap iterations
for x = 1:s

    % bootstrap over subjects

    % sample with replacement from your subjects (just collect n indices)
    z = random_sample_with_replacement(1:n)

    % loop over bootstrap selection of subjects
    % to bootstrap sample individual data points within subject
    for y = 1:length(z):
        % for each subject selected for resampling, draw from their data points with replacement
        for w = 1:length(a(z(y)))
            within_subj_boot(w) = random_sample_with_replacement(a(z(y)))
        end
        bootsample(y) = within_subj_boot
    end

    % perform the respective calculation (e.g., lme4) for the bootstrap sample
    % and store the relevant parameter you want a CI for
    output(x) = parameter_estimation_function(bootsample)

% check the relevant percentiles of your bootstrapped parameter estimates
CI = percentile(output,[5,95])

Most languages will have some wrapper function for something equivalent to this (but a lot less inefficient), I think for R it might be the Coin package?
Comment: With any bootstrapping technique the simulations get processed just like the real data. With non-parametric bootstrapping (what you described) you resample your original data. With parametric bootstrapping you simulate a new sample based on the original model you fitted. Non-parametric btsp. makes less assumptions but usually has more variance. Parametric btsp. assumes that the model you fit is "correct", so it makes more assumptions, but it usually has less variance. Param. btsp. also eliminate issues regarding the resampling. (Cont.)
Comment: Given the fact you are making parametric assumptions to start with, when you fit your original model you might as well use them and get a better estimate (ie. if you don't believe the model why bootstrap it anyway). You have the correct idea; I just want to highlight though that there is a trade-off between the non-parametric bootstrap you outlined and the parametric bootstrap that `lme4`'s native `bootMer()` function offers.
Comment: jona, your train of thought is correct but take notice two things: 1. What you described in $non$-parametric bootstrap, not "simple" bootstrap; there is an inherent bias-variance trade-off between the two. 2. You need to be a bit careful how you resample your sample. You may accidentally end up missing a grouping especially if you have a lot of clusters. That is not "the end of the world" and would asymptotically "not happen" but this might mess-up your calculation procedures slightly.
Comment: Regarding 2, I agree - it's just an example that would need to be adapted to the individual model. (You might get by simply sampling from the grouping variables too.) Regarding 1 - I don't understand, can you elaborate?
Comment: @jona: Thanks! And thanks for taking the time to explain this as well. I am comfortable with bootstrapping (much more than with mixed effects models anyway) and I usually use the **boot** package in R. And thanks to user11852, now I know that I can also use bootMer() as well. Thanks both!


When a complex equation has no solutions?

Question: I have to find $a,b,c$ that $az^2 + bz + c = 0$ where $z,a,b,c \in \mathbb{C}$ has no solution. But I don't know how! Would you please help?
Comment: Why don't you know how? You could just try a little bit, e.g., with $a=b=0$ and $c=1$?
Answer: The equation has no solution in $z$ if and only if $a=b=0\land c\ne0$.
If $a\ne 0$, then the equation has solutions $z=\frac{-b-\rho}{2a}\lor z=\frac{-b+\rho}{2a}$, where $\rho$ is any complex number such that $\rho^2=b^2-4ac$.
If $a=0\land b\ne 0$, then the equation has solution $z=-\frac cb$.
Of course, if $a=b=c=0$, then any $z\in\Bbb C$ satisfies the equation.
Answer: This was proved to be false. A polynomial will always have at least one complex solution.
Otherwise, the only scenario where you have no solutions is when
$$ a=b=0, c\ne 0$$
since you get $c=0$, but $c \ne 0$


Determining whether the mean of a set of non - independent values is statistically different from zero

Question: There are some areas of statistics that I am fairly confident with, and others, that are probably very simple that I am fairly clueless about. Only one way to go but up though.
I have the dataset below, that contains 100 rows
<code>X
0.285
-0.397
0.371
-0.794
0.814
0.384
-0.11
0
0
0.271
-0.572
0.419
...
</code>
I am working on bacterial genetic divergence. To do this I generate two datasets, with divergence data of paired bacterial species.
Example: species X with species Y, using species X site frequency spectrum, and species X with species Y using species Y site frequency spectrum.
From these dataframes I select a number of random genes with replacement 100 times. The number of genes taken is as equal to the length of the original dataframes. Once processed I end up with two sets of adaptive coefficients known as omegaA1 and omegaA2, ideally these should be equal to one another. I subtract them to create the 100 values I've alluded to. In doing so I can present the differences between OmegaA1 and OmegaA2. From here I need to determine if these values are statistically different to 0. As such I believe my results are not independent, as they're derived from the same source. Correct me if I am wrong though, this would make my life a lot easier.
I need to determine whether the mean of these values are statistically different from zero or not in either Python of R. In python I have determined, the 95% confidence interval, with the lower 2.5% boundary being: -0.971, and the upper 95% boundary being: 0.95. As such, I know that zero falls within the 95% confidence interval.
However, I don't know how to determine whether the mean of these values are statistically significantly different from zero, with a p-value. Whilst I don't particularly like p-values, I've been told it is necessary.
I initially thought of using a one-sample t-test, which would be simple enough, however I realised that I could not as the values in the dataset are not independent of one another, as they are derived from bootstraps of a previous dataframe. As such does anyone know a suitable test or procedure to get a p-value signifying whether this dataset is statistically different from zero.
Any help would be greatly appreciated, thanks in advance. If I've missed a question just like this, please by all means, just post a link. If it helps, I'll mark it as answered. I apologise if this isn't very clear. Please ask questions for the sake of clarity, writing is a struggle of mine.
James
Comment: By successively deleting previous versions of this question, you have removed useful comments placed there by others.  Please don't do that: instead, when you want to modify or improve a post, *just edit it.*  See our [help] for more information about how this site works.
Comment: Previous answers, presented flaws in my question, and I had the option to delete it and rewrite my question taking the criticism onboard. The other comment told me that these values are independent, when my own supervisor tells me they aren't. I intend to discuss this with him, but for now I intend to work, based on the assumption that he is correct, and seek to find an answer to my initial question. If I later find out that he has changed his mind, then this isn't an issue, as I know how to deal with that. Ultimately, it doesn't hurt anyone for me to pose the above question.
Answer: I am not really sure exactly how you obtain your data, your experiment was not really clear to me. However some remarks:

How do you obtain the confidence interval ? It is as hard to make confidence interval as it is to find a p-value, there is a sort of duality tests-confidence interval if you can do one, you can do both in most cases. And hence, I wonder how you did your confidence interval with non-independent data ?

If I understand right, you want to test whether $\Omega_1$ and $\Omega_2$ are close to $0$, knowing that they are not independent ? Maybe you can do the following test:
$$H_0 : \Omega_1 =\Omega_2 = 0 \quad \text{vs}\quad  H_1: \Omega_1 \neq 0 \text{ or } \Omega_2 \neq 0 $$
and this can be done for example if your data is Gaussian (jointly Gaussian, they do not need to be independent) using Wald test where the matrix $R$ is the identity matrix. Then, the p-value would be obtained using the chi-square quantile function (this can be easily codded in R).
Comment: Specifically I want to know whether my final dataframe which is: Ω1 - Ω2 is close to zero
Comment: In that case, you can use Wald test with $R$ equal the line vector $(1,-1)$ (cf wikipedia link I gave to see what is the R vector I speak about).
Comment: Would the wald.test function in R be a suitable way for executing your suggestion? Then if I use the chi-squared function all this can be done in a single loop. I have 20 of these dataframes. Each one is irrelevant to one another, so I just have to repeat the process 20 times, and record which ones are suitable for further analysis and which ones aren't
Comment: I imagine it wald.test can be used but I don't know exactly what it does, I always did my Wald tests by hand using the pchisq R function to get the p-value. But indeed, wald.test can be used to get the p-value according to R manual but I don't understand exactly the parameters of this function so I can't tell you exactly the command you need.
Comment: This has all been really helpful, if it works then excellent, and if it doesn't then I've learn't something new and hopefully I'll get another clue on where to go next. So either way i'm grateful, thanks!


Survival curves, counter-intuitive results for customer churn -- lower risk of churn for users who've previously churned?

Question: I'm trying to work out some explanation for a result I'm seeing where I have the Kaplan-Meier plots for monthly customer churn risk. In aggregate, it looks fine, but I've broken it down into subgroups based on whether the user has previously churned before, i.e. canceled and resubscribed.
A couple things that might be impacting this -- I'm looking at a shorter time horizon than I'd like (~3 years relative to maybe about 10 years of data). More customers are likely to have not ever churned before, so the other curves represent smaller numbers in total, but still >50k.
Leaving aside the fact that recurrent event analysis is probably the better approach if I had access to the full data, I'd love any insights if anyone's seen something like this before. It does also appear in the duration distribution comparison, with non-churners having a very different distribution.
My main hypothesis to explain this is that this plot suggests that customers will, more or less, inevitably churn, so customers who have already done so in the past are less at risk now. Similarly that customers who give the service a second (or third, etc.) chance are more likely to stick with it?
And then there's the idea that a user who has already churned >= 1 time will probabilistically, in aggregate, have shorter durations -- given this, I'm wondering how I can correct for this effect?
It's not a particularly satisfying answer to me so far. I just wish I had a more quantitative way of demonstrating this.
Comment: *"My main hypothesis to explain this is "* explain what? *"anyone's seen something like this before"* seen what?
Comment: If this question is about 'why do customers churn less fast after each time that they have churned before?' then it is about some domain specific theories and not about statistics.
Answer: This is not counterintuitive at all.
Customers who churned before and resubscribed had to have a reason to do so. The range of reasons depends on your service but a typical one is that they tried a competitor and decided that your service is better after all.
Resubscribers have more conviction about your service because they have more experience with the landscape.
Don't confuse the conditional probability of staying longer given resubscription with the probability of resubscription.
Do you have any data about why your customers churn? We ask them on the cancellation form.