What does a professional workflow creating a databse using Hibernate in Eclipse?

Question: I am not sure what's the "modern" way of creating a large MySQL database from scratch with Hibernate.
You would not use assembly to write a modern UI Application - that I know - so do I write .hbm.xml files for Hibernate by hand if I don't have to? Anyway I would prefer to use Java Annotations (e.g. @Entity, @OneToMany, etc.) before using XML but is that the level to start?
MySQL Workbench offers a quite straight forward way to create MySQL schemes, so what I do at the moment is that I create my schema in MySQL Workbench and reverse engineer it with Hibernate Tools. That way I have created my database and I have my annotated Java files which are hopefully correct.
But it feels strange to use MySQL Workbench to create a database for me that I reverse engineer just to have my Java files.
So you see what I am looking for is a practical way to organize my creation process that should also consider later migration processes that might be necessary.
What does an elaborate workflow for Hibernate look like?
Comment: My professional workflow is: carefully craft your database DDL by hand, in the form of FlywayDB or Liquibase migrations; carefully craft the JPA entities by hand, adding all the necessary documentation, methods, etc. Entities are the heart and soul of your application. They should just not contain getters and setters. They should be documented. Field names should be chosen carefully. Accessors should sometimes be absent, or return read-only views, etc. cascade options, lazy fetching, should also be configured with care.
Comment: You could generate the DDL files from the entities. Bit it would still lack things like comments, tablespaces, maybe some indexes, etc. Let's assume all is perfect. You go into production with version 1.0, and users put 10 GB of data in the database. You develop version 1.1, which needs to make various changes in the schema. Do you drop the 10 GB of data and restart from scratch? That's where tools like FlywayDB and Liquibase become extremely useful.
Comment: @JBNizet Hi! So, writing every entity by hand is not "*2000 and late*" you'd basically recommend it here? Your argument sounds good to me. But do I need a DDL file? Can't I just write my annotated Java files? "*Entities are the heart and soul of your application.*" - I agree, I wouldn't want to mess this very fundamental thing up right at the beginning! :)
Comment: @JBNizet Okay just to make sure I'm getting this right: 1) Craft the database by hand (in my case I am using MySQL): All entities, relations, constraints, views, etc. using FlywayDB/Liquibase 2) "*Carefully craft the JPA entities by hand*" - would that mean to translate the MySQL code into Java? 3) Document everything.
Comment: @StefanFalk keep in mind specific hibernate limitations like views and defining m-n mappings.
Comment: @Hannes Afaik Hibernate does have views and m:n mappings are not a problem as well - what exactly do you mean with *limitations*?
Comment: Haveing a n-m mapping with other attributes in the mapping table is a pain. Having an identifying primary key (where the primary key is a foreign key of another table's primary key) needs special treatment too. Views can be mapped to entities but it's really something you want to avoid. In fact the more you go into sql and understand the personality of each dbms, the less appealing hibernate gets.
Comment: @Hannes Yes indeed, m:n relations with attributes are quite hard to implement.. but what would I use to access my database once I got my DDL? Should I use Hibernate and just write every SQL statement by hand like `session.query("SELECT * FROM person");`? I really understand your arguments against Hibernate but is there at least a little bit of abstraction that Hibernate or Spring can offer? Writing every single SQL statement feels like writing assembly to me - but I don't mind doing it if it's necessary.
Comment: @JBNizet What are you using once your database is "up and running"? Are you then using Hibernate to access and modify your data (if that's even possible)?
Comment: That's the whole point of Hibernate: reading and writing data from/to a database. I don't get your question. If your question is "what do you use to migrate the database schema from version A to version B?", the answer is FlywayDB or Liquibase.
Comment: @JBNizet Well my question targets the problem that writing the DDL script does not create my Java-`@Entity`-annotated-POJOs for Hibernate. So how would I access this data? I'd again have to write all my SQL statements by hand. Is that what I want? I'm currently reading something about [EmpireDB](https://empire-db.apache.org/empiredb/hibernate.htm) which states a few negative sides of Hibernate. I'm sorry I realize my question turns out to be quite extensive but it's just such a fundamental question to me and I'm still not sure about if I already know the answer to it.
Comment: I'm not following. My first comment said: you design your DDL by hand, and you design the entities by hand. So, you have a database schema, and you have entitites, and you're thus ready to use Hibernate/JPA.
Comment: @StefanFalk spring's `JDBCTemplate`, `JOOQ`, .. If the company's policy is to use hibernate you start using `hql` a lot for reporting and aggregations.
Comment: @Hannes `JOOQ` appears to be a very good choice. I've compared now a few but from the looks of it `JOOQ` does a good job.
Comment: @JBNizet Okay, sorry I didn't realize how you meant that. It sounds strange to write the database by hand and then create Java Hibernate copies. I don't think I want to use Hibernate anymore after reading a few things that speak against it - though I can't say if all of that I was reading is still true. But thank you for your help!
Answer: There is not the way (TM) to do it. But from 5 years of hibernate experience I start with modeling, then hand writing the DDL. I recommend against letting hibernate create your tables because hibernate cannot create indexes and decent constraints and normally you need a db init script for test, integration and production environment. Migrating this way is also easier.
When the tables are all set up I let the entities be generated by the IDE. I always get confused by the inverse relationships...
After the development is done I normally analyze the model again to add missing indices.
With hibernate you cannot define primary keys like GENERATE ALWAYS, constrains like id > 0. Hibernate will also use as default one sequence ant will not add sequences per table. The newer oracle and SQL server features are not supported.
I read once that hibernate should be used after the model is implemented but it must have been 3.x and I guess hibernate 4.x learned some new tricks.
Comment: Wow, this one strikes me. So you would not recommend to e.g. write all `@Entity` objects in Java and let Hibernate create those for me? You say "*hibernate should be used after the moddel is implemented*" would that mean that I for example reverse engineer the whole database in order to get hands on my Java files?
Comment: Eclipse has a neet plugin that analyses a database schema and generates all enities.
Comment: What's the name of the plugin?
Comment: EclipseLink plugin for jpa projects. I normally let the entities generated for eclipselink and copy them to the hibernate project. At work we use intellij a lot.
Comment: Alright! Just one more thing. You said "*I recommend against letting hibernate create your tables because*" .. my problem here is that I am not really experience with DDL - in my case MySQL - but do you know e.g. if "MySQL Workbench" can be used to replace Hibernate at the beginning? I could design my database there and create all tables first. And.. how can I use Hibernate "*after the model is implemented*"? Would that mean to "tranlate" the DDL code into Hibernate-Java code?
Comment: Mysql workbench is indeed a good starting point, helping a lot to get things right if you are just starting your db journey.


How do you jump around the piano?

Question: I'm not asking for the physical how, maybe just hints or tips.
Do you just have to know how far to leap? For example, C4 to A2 is 10 white keys. Do you just have to know that via muscle memory?
Do you need to preserve positions (like start from C and change to G position)? Or is it as long as you're comfortable?
For example, from this:

Jump to this:
Comment: Sure, it's muscle memory. Have you ever seen gymnasts salto around a floor mat or a balance beam? They have no marks at all, and people have to hit exactly the right spot anyway. So it's obviously possible, and professional pianists would miss an opportunity of they didn't exploit that capability.
Comment: Practice, practice, practice.  Slowly at first.
Comment: From the question and the diagrams, I'm assuming you are a beginner. Really, this is a "non-question" - it only *seems* like a problem you have to solve, because you are still learning how to use all your fingers independently to play adjacent keys. As you progress you will find that your hands and arms are moving (though not necessarily "jumping") *all the time* as you play.  Almost any Youtube video of keyboard playing will show that.
Comment: Doing it a lot. I noticed that my hands just start being there after playing a song for a while. It's sub-conscience.
Answer: It is indeed muscle memory but there is a technique to it.  If you can't nail the leap every time, you are doing something wrong, it is not necessarily a "practice makes perfect" method but more of a - what kind of bad habits have you perfectly practiced and are now part of your technical inability.
The first thing pianists do wrong is when they are departing a note, they twist the wrist in the direction they are going (ulnar deviation, radial deviation).  This is bad for many reasons and hinders accuracy for many reasons.
The second thing they do wrong is they try to grab or stab or reach for the note.  The finger or hand doesn't play it but rather, the arm does.  Your hand can't drag the arm behind it but the arm can very rapidly place the fingers where they need to be.
The third thing pianists do wrong is they think horizontal.  The arm needs to have a shape.  A circular one to be exact.  If you reach for the note you will most likely miss it so a rounded shape of the arm gives it accuracy and power. This leads to the next issue . . .
Strike the note from the top.  Singers hear this all the time.  Slightly over-reach the note then come down on it.  This is because your body naturally wants to contract.  As you reach for it, the tendency is to then give up and the pianist falls short.
A good lesson to keep in mind is what THE KARATE KID was taught:  Wax on, wax off.  Play the piano as if you are writing on a chalk board.  The fingers and wrist don't lead, the arm places the fingers where they need to be.
There are a few other things such as forearm rotation and dual muscular pulls but that is for another day.
Answer: Yes, it is muscle memory. Which means it's time to practice!
I can't recall intentionally setting out to develop this particular skill, but I know it developed as I became more familiar with the instrument. It's still not perfect - I've jumped a tone too high or low more times than I care to remember, but I don't spend all my time looking down at my hands any more.
There's some value in retaining your hands in the 'correct' position; the trick is deciding what that position is. A teacher can be really helpful here, to ensure you're not developing bad habits. That being said, the 'correct' position is often debatable, and it should result in the easiest and most comfortable fingering anyway.
I'd choose a song which you like, which features some of these jumps, and start there. Get familiar with the notes, so that you stop thinking too much about them. As you practice, you should find yourself automatically moving your hands as required. Then, work on different pieces. Over time, you should develop that muscle memory.
Also, don't be too worried about using your eyes to help, especially for difficult bits. For some parts of a piece, I will be looking at my left hand, or my right hand, or sometimes even the music.
Answer: For me it's mainly muscle memory.
However, I think it's worth mentioning a few details:

one time I noticed that before jumps, if there is time, I subconsciously position my hands using the 2+3 pattern of black keys;
if there is no time and there is a lot going on, I might need to practice some jumps to be able to hit them accurately without looking;
when doing sight-reading or awaiting a visual cue from another musician, etc., I use peripheral vision and steal glances to increase accuracy (even when not sight-reading I might stare at the middle if both hands need to jump at the very same time).

I don't remember learning it, it just happened, arrived with lots of hours of playing time (mainly practice, but not only that).
Answer: It's all muscle memory, of course, but there's also a process of "coarse adjustment" and "fine adjustment", based on the configurations of the black keys.  (dtldarek mentions this in his answer as well.)
Say you have your 3rd finger on C4, and want to next play A2 with 5. You reach out towards the gap between Bb2 and C#3 with your 4th finger, and when you find it, you can easily locate A2 with your 5th from there.
If you watch someone sight reading, or singing and playing stride figures in the left hand at the same time, or whatever, you'll notice that they often feel their way around the piano in this way. As for teaching, any of my teachers who taught sight reading mentioned this, although they also said something to the effect of "the only way to learn sight reading is to sight read."
All that said, there are times when you just have to do it.  Beethoven was said to be adept at leaps on the piano, and there are places in his sonatas that bear this out.  Here's a snippet from his Sonata No. 4, Op. 7:

The tempo is allegro, and you have all you can do to just fly up to the F from the A.
And then we have this from our friend Liszt (from "La Campanella"):

And no, you can't go feeling around the black keys here, either.  :)  You have to develop the same level of precision in your arms and elbows as you have in your fingers and wrists, and move your hand back and forth rapidly from the elbow.  (Not that I can do it very well...)
Answer: For your second question about preserving positions: You should do so if you find it helpful.
As a beginner, thinking in terms of positions is a good way to manage how your fingers sit over the keys. e.g. You don't need to know where E4's absolute position is, you just have to remember that it's under your 3rd finger.
As you start playing music with leaps, it may be helpful to think about moving your hands to a new position (and I've seen studies that have been composed with this intent). I would only suggest that you do this if it feels comfortable to you and works for the piece you're playing: do not constrain yourself to thinking about the keyboard in this way.
As you become more comfortable with the keyboard under your hands, you will (at least, I imagine most keyboard players do) subconsciously develop a "set of positions" that you will use to this effect without even thinking about it. In other words, you can place you hand anywhere on the piano and instantly know which keys are under which fingers.
As for your first question about muscle memory: Yes, you will develop muscle memory when you practice leaps. For some large gaps, you might want to (if you have the time) feel around to make sure you have the right key(s) before you play it.
Also, there's no rule that says you can't look at the keyboard.
Answer: So a technique to practice this I found useful is to consciously stop just before you play in the new position and look at your hand and adjust before you play it. This forces you to be very conscious about the new position. In the end you can reduce the gap down to nothing. I found this helped me get the muscle memory quicker.

How do you jump around the piano?


Is each of the PCA or PLS components just one of the original variables?

Question: I am confused about what a component is in PCA and PLS.
Are the components just the original variables but not necessarily in the same order?
For example, in PCA, if I had 8 variables in my data, would PC1 correspond to one of the 8 variables? And in PLSR (PLS regression), if I were to use 4 components, does this mean that I will be using 4 out of 8 variables to build a model?
Comment: Please see [this highly rated page](http://stats.stackexchange.com/q/2691/28500) to help clarify, and edit your question if issues are still not clear. Principal components, for example, are new predictors formed by linear combinations of the original predictor variables, with each combination orthogonal (generalization of perpendicular) to each of the others. They are not particular subsets of the original variables. Each principal component may include contributions from all of the original variables.
Comment: Yes I think I know PLSR and PCA are two different thing. However as far as I understand both method is to reduce dimension of data(usually when you have small sample size but relatively large factors?). And I am confused in both situation. PCA you pull out principal components that are less than number of factors. In PLSR you use number of components that are less than number of factors. So I guess my question is in PLSR if I were to decide to use 4 components in model out of 8 possible compoents, is this equivalent to say that I am using 4 factors out of 8. If I am wrong, please redirect me.
Comment: To make my question clear, lets say I want to perform pls. For example, my data is 8 factors and 25 samples. I want to reduce number of factors in my model. I used plsr in R and I get 8 models, model with 1 comp, 2comps and so on. Max comp I can use is 8. I thought it is because I only have 8 factors. This leads me to think that component and factor are euquivalent term.
Comment: Kane, when you say that your data "is 8 factors and 25 samples", you mean that there is 8 measured variables? If so, you shouldn't use the word "factor" for it; "factor" usually means an "underlying factor", estimated e.g. via PCA or factor analysis (FA). So if you have 8 *variables*, you might do PCA/FA and then conclude that you have e.g. 2 or 3 *factors*. Does this make sense? This was probably the source of my confusion! Your question makes sense if I replace the word "factor" with the word "variable" everywhere :)
Comment: Yea I think you are right. I have 8 measurements per sample. I simply said each measurement as factor. Then am I thinking right that components in the model is subset of total variables?
Comment: @EdM, consider posting your comment as an answer. Another related question is http://stats.stackexchange.com/questions/137100 (Kane, note on terminology: "feature" means the same as "variable").
Comment: @amoeba Answer posted
Answer: The possible confusion here, as @amoeba points out in a comment, is the difference between variable selection and dimensionality reduction.
Both PCA and PLS are intended to reduce the dimensionality of the problem. If you have measured 8 variables on each of your cases (and you have more than 8 cases) then the original dimension is 8. PCA and PLS help you choose a lower number of dimensions that will work well enough.
But these procedures do not work by selecting subsets from your original 8 variables. Rather, they construct linear combinations of the 8 variables to make new sets of 8 predictors, then decide how many of these new combinations need to be included in the final model. For either PCA or PLS, these new predictors are designed to be orthogonal (multi-dimensional equivalent of perpendicular) to each other. If there are correlations among predictors, all 8 of your original variables are thus likely to be included to some extent even if you end up with a final dimension of, say, 4. So you are not typically performing all-or-none selection among your original variables. You just get rid of some less-important combinations of them.
PCA simply examines the predictors themselves, finding first the combination that captures the most variance in the predictors, then the (orthogonal) combination that captures the next most, and so on. Several superb explanations of how this works are on this highly rated page.
PLS includes in this type of scheme the relations of predictors to the outcome variable. At each step it finds the combination of predictors, orthogonal to all prior combinations, that maximizes the product of the variance of the predictors times the square of the correlation to the outcome variable. (See ESLII, eq. 3.64, page 81). For the first step, this is a linear combination weighted by each variable's individual correlation to outcome (unlike standard multiple regression, where all variables are considered together). PLS also gives a set of orthogonal predictors, made of linear combinations of the original variables, although different from those provided by PCA.
In either procedure, a decision is made about how many of these new predictors to include, determining the final dimensionality. In either case, if you include all the new predictors, you just get back the original multiple regression.
Also, please note that the above assumes that the predictor variables were first standardized so that differences in scales of the variables do not matter.
Comment: +1. However, the explanation of PLS is somewhat torn. You have not explained how comes that residuals can be further predicted again by a new, orthogonal combination; in other words - what conditions make PLS possible and different from usual multiple regression.
Comment: @ttnphns I've edited to make the description of PLS a bit more precise, I hope without losing clarity.
Comment: +1. Here is one link for further reading about PLS regression (cc @ttnphns): http://stats.stackexchange.com/questions/179733.


How to load fields by target type?

Question: I'm having a content type with referenced fields of paragraph type. How to get referenced fields in hook_form_alter?
Here are my fields:
<code>[field_media_audio] => Drupal\field\Entity\FieldConfig Object
        (
            [deleted:protected] =>
            [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
                (
                    [id:protected] => node.field_media_audio
                    [field_name:protected] => field_media_audio
                    [entity_type:protected] => node
                    [type:protected] => entity_reference_revisions
                    [module:protected] => entity_reference_revisions
                    [settings:protected] => Array
                        (
                            [target_type] => paragraph
                        )

                    [cardinality:protected] => -1
                    [translatable:protected] => 1
                    [locked:protected] =>
                    [persist_with_no_fields:protected] =>
                    [custom_storage] =>
                    [indexes:protected] => Array
                        (
                        )

                    [deleted:protected] =>
                    [schema:protected] =>
                    [propertyDefinitions:protected] => Array
                        (
                            [target_id] => Drupal\Core\TypedData\DataReferenceTargetDefinition Object
                                (
                                    [definition:protected] => Array
                                        (
                                            [type] => integer
                                            [label] => Drupal\Core\StringTranslation\TranslatableMarkup Object
</code>
Answer: By what you can see in this var dump the field can hold any paragraph type, so you don't know which fields it may contain.
When you have restricted the field to one paragraph type, then load the field defintions for this type:
<code>$fields_paragraph = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('paragraph', 'my_paragraph_type');
</code>
Comment: Above line is giving error. Error: Call to a member function getEntity() on null.. "paragraph is not an entity".
Comment: It is, if you have installed the module. See http://cgit.drupalcode.org/paragraphs/tree/src/Entity/Paragraph.php?h=8.x-1.x

How to load fields by target type?


Cannot see objectClass from custom schema

Question: I added new schema to my ldap server but when I trey to create an entry with custom objectClass an custom attributes, it doesn't see my custom stuff. It's just experimental so OID's are not important.
My custom.schema.ldif file
dn: cn=deployment,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: deployment

olcAttributeTypes: ( 1000.1.1.1 NAME ( 'user' )
    DESC 'Username of the deployer'
    EQUALITY caseExactMatch
    SUBSTR caseExactSubstringsMatch
    SYNTAX 220.127.116.11.4.1.1418.104.22.168.15 )

olcAttributeTypes: ( 1000.1.1.2 NAME ( 'app' )
    DESC 'Application name'
    EQUALITY caseExactMatch
    SUBSTR caseExactSubstringsMatch
    SYNTAX 126.96.36.199.4.1.14220.127.116.11.15 )

olcAttributeTypes: ( 1000.1.1.3 NAME ( 'port' )
    DESC 'Port of the application'
    EQUALITY integerMatch
    ORDERING integerOrderingMatch
    SYNTAX 18.104.22.168.4.1.14220.127.116.11.27 )

olcAttributeTypes: ( 1000.1.1.4 NAME  'available'
    DESC 'App is available'
    SYNTAX 220.127.116.11.4.1.14126.96.36.199.7 )

olcObjectClasses: ( 1000.2.1.1 NAME 'deploymentClass'
    DESC 'Deployment class'
    MUST ( user $ app $ port $ available )
    STRUCTURAL )

Then I added it with:
ldapadd -w123 -x -D "cn=admin,cn=config" -f custom.schema.ldif

After restarting server I tried to create entries with this ldif:
dn: ou=deployment,dc=las,dc=com
objectClass: organizationalUnit
ou: deployment

dn: cn=app1_user1,ou=deployment,dc=las,dc=com
objectClass: deploymentClass
cn: app1_user1
user: user1
app: app1
port: 8888
available: 0

After trying to add this:
ldapadd -x -D "cn=admin,dc=las,dc=com" -w123 -f deployment.base.ldif -c

I get:
adding new entry "cn=app1_user1,ou=deployment,dc=las,dc=com"
ldap_add: Invalid syntax (21)
    additional info: objectClass: value #0 invalid per syntax

After trying to explore LDAP directory with LDAP browser (JXplorer) I couldn't find any attributes or object class that I defined. Can someone help me?
Answer: It looks like you're trying to a cn value to your ldap entry, when none of the objectClasses you've given that entry support using cn.
You can either attempt to alter your schema, or you can alter the entry itself.
dn: app=app1+user=user1,ou=deployment,dc=las,dc=com
objectClass: deploymentClass
user: user1
app: app1
port: 8888
available: 0

Alternatively, if you're using core.schema, the memberOf overlay and either nis.schema or rfc2307bis.schema you could brew something up with no additional schema.
dn: cn=app1+uid=user1,ou=deployment,dc=las,dc=com
objectClass: ipService
objectClass: uidObect
uid: user1
cn: app1
ipServicePort: 8888
ipServiceProtocol: TCP

dn: cn=available-deployments,ou=deployment,dc=las,dc=com
objectClass: groupOfNames
cn: available-deployments
member: cn=app1+uid=user1,ou=deployment,dc=las,dc=com


Div uma em cima da outra

Question: Tenho uma sequencia de DIVs sendo geradas por um script.
Gostaria que elas ficassem uma em baixo da outra e quando atingisse a altura máxima da div pai, elas entrariam do lado .
Atualmente colocando-as para flutuar à esquerda ficam assim:
[ 0 ] [ 1 ]
[ 2 ] [ 3 ]
[ 4 ] [ 5 ]
[ 6 ] [ 7 ]
Mas gostaria que elas ficassem assim:
[ 0 ] [ 4 ]
[ 1 ] [ 5 ]
[ 2 ] [ 6 ]
[ 3 ] [ 7 ]
Código até o momento:

     <? for($x=0;$x<24;$x++){ ?>

<?=$x?>

     <? } ?>

JSFiddle: https://jsfiddle.net/zgveahjp/
Comment: Complemente com o código que você já tem.
Comment: Usando a propriedade flex-box do css3 consegui fazer oque você precisa, porem o width da div pai não acompanha os filhos, é fixo, talvez de para arrumar isto.

JSFiddle: https://jsfiddle.net/devgaspa/zgveahjp/2/

Referência: http://desenvolvimentoparaweb.com/css/flexbox/

Can i use?: http://caniuse.com/#feat=flexbox
Comment: Editado com o código !
Answer: Podes fazer isso da seguinte maneira com jQuery:
$(document).ready(function() {
    var divPai = $("#idPai");

    if (divPai.height() <= 200) {
        divPai.addClass("umaColuna").removeClass("duasColunas");
    } else {
        divPai.addClass("duasColunas").removeClass("umaColuna");
    }
});

Basicamente o que isto vai fazer é:
Se a div id="divPai" for menor ou igual a 400px de altura (ou seja lá qual for o valor que queiras que seja o valor máximo definido para a altura da div pai), vai adicionar uma classe chamada umaColuna ao #divPai:

e se o valor for maior, adiciona uma classe duasColunas:

Depois para fazermos a modificação e transação para dividirmos o conteúdo dentro do #divPai para que ele fique com uma ou duas colunas dependendo desta mudança de classes acima, basta criarmos o código CSS referente para as classes da seguinte forma:
/* Personaliza o espaçamento entre as colunas */
#idPai {
    -webkit-column-gap: 10px;
    -moz-column-gap: 10px;
    column-gap: 15px;
}

/* Divide o conteúdo dentro da #divPai em uma coluna */
.umaColuna {
    -webkit-column-count: 1;
    -moz-column-count: 1;
    column-count: 1;
}

/* Divide o conteúdo dentro da #divPai em duas colunas */
.duasColunas {
    -webkit-column-count: 2;
    -moz-column-count: 2;
    column-count: 2;
}

.classFilho {
    display: inline-block;
    width: 100%;
    height: 100px;
    background-color: #DDD;
    margin: 0 2px 15px 2px;
/* O código abaixo evita problemas de posicionamento das divs filhos */
    -webkit-column-break-inside: avoid;
    -moz-column-break-inside: avoid;
    page-break-inside: avoid;
    break-inside: avoid;
}

E o código HTML será algo como:

0

1

2

3

Aqui tens um exemplo online no jsFiddle: http://jsfiddle.net/6sqmsLvv/
Clica no botão Adicionar nova div Filho no link do exemplo, para adicionar novas divs filho.
Answer: RESOLVIDO !
De acordo com o comentário do devgaspa.
Achei mais simples e como resolveu, nem testei outros métodos.
OBRIGADO

Usando a propriedade flex-box do css3 consegui fazer oque você
  precisa, porem o width da div pai não acompanha os filhos, é fixo,
  talvez de para arrumar isto. JSFiddle:
  jsfiddle.net/devgaspa/zgveahjp/2 Referência:
  desenvolvimentoparaweb.com/css/flexbox Can i use?:
  caniuse.com/#feat=flexbox – devgaspa

.pai {
    background: orange;

    display: flex;

    flex-direction: column;
    flex-wrap: wrap;

    height: 500px;
    width: 0px;
}

.filhos {
    border: 1px solid lightgray;
    box-sizing: border-box;
   height: 100px;
    width: 100px;
}

0

1

2

3

4

5

6

7

8

9

10

Answer: pra ele não passar de 300px coloque a tag
 max-height: 300px;

Comment: Realmente. Mas isso não soluciona o problema que estou enfrentando.

Div uma em cima da outra


Excel - How to ignore rows with formulas that equate to nothing?

Question: I'm working with Microsft Office Interop API. My question pertains to Excel.
I wrote a program using Interop API to format Excel documents and then send them to the printer. The problem though is that we occasionally run across files in which people have created a column that spans 65,000+ rows, and all it contains is a formula. The formula only creates output for the first 100 or so rows, and then the remaining appear blank. But, when sent to the printer, it tries to print like 10,000 pages or something because of those formulas.
I first looked for ways to tell Excel to simply not print those ranges. I couldn't find any setting to ignore those. Second, I thought about ways to do this programatically, but that logic would be pretty round-about and might cause issues with "regular" files that don't contain formulas like this.
Does anyone know of a good way to have Excel ignore these formulas that equate to nothing?
I'm using Delphi and Office 2007 Interop API.
Answer: Nope. As far as Excel is concerned a cell is filled if it contains a formula, regardless of the result of that formula.
Typing [end] and then [down] in a cell with a value takes you to the last filled cell before the first blank one in that column starting from your current position. Typing End-Down in the columns with the formulas should therefore take you all the way down to the bottom.
The option you do have is to tell Excel exactly what range to print before issuing the print command. You do that by using the method that corresponds to the Print | Set Range menu option (sorry, don't have the com interfaces available at the moment).
To find the range to print you need the right most column and the bottom most row of your data range. Assuming your first row containes column captions, simply iterate over the cell values of the first row and stop when you get a blank value.
To find the bottom most row of your data range, you need a column that doesn't have formulas, but "normal" values, and has no blank values in any of the rows within your data range. If your data always contains such a column, you can iterate over that to find the last filled row and thus the bottom bound of your print range.
Comment: @Ryan: yeah, I know the feeling... :} Oh, to be a bit more general, you could also check all columns with "captions" (value in first row) and stop at the row where the only filled cells are ones containing formulas... At least formulas always start with a "=".
Comment: Programmatically, though, that logic is difficult to safely apply to "every" Excel file. The program I've written is intended to run somewhat on its own without any user defined print range, etc. It seems a little unreliable to iterate over every row and check the column cells for formulas, and then come up with an algorithm that allows for some degree of blank cells in between itself and future cells being checked. It's ... just ... argggh. :(
Comment: yeah, that might be the best option. loop through each column in the given "used range" and count the number of trailing rows that contain only formulas. if that count becomes more than like 100, or so, begin removing the remaining rows from that column. This is only tricky because 100 rows of formulas isn't bad, neither is 5,000 rows of formulas. But, it's bad if those formulas are all blank!
Answer: I don't know Delphi, but I created a macro to get the last active column by using
With ActiveSheet
    row = .Cells(.Rows.Count, "B").End(xlUp).row
End With

Then with having the row you could try to print the columns you need.
ActiveSheet.Range("A1:" & "D" row).Select
Selection.PrintOut Copies:=1, Collate:=True

Hope that helps!
Comment: I'm not familiar with that 'with' syntax, so it's a little confusing to me, but I don't understand how that first code snippet gets the last active column. It looks to me like it's getting the last row with a hardcoded column for "B", or "D"? Does this logic ignore cells containing formulas that have no visible result?
Comment: @Ryan: the syntax is VB. No it won't ignore cells containing formulas that have no visible result. The macro is basically doing the End-Down, or in this case End-Up "trick" to find the next filled cell (after a couple of blank ones) starting from the last row going  in the xlUp direction.
Comment: @Ryan: The first snippet is returning the row number of the last active cell in the column "B" by counting up from the bottom of the Excel sheet. Unfortunately I don't know Delphi otherwise I would give a better example.


Pegar um valor de vários arrays dentro de um array

Question: Tenho uma duvida em relação a um array, tenho um array que guarda vários arrays dentro, esse é o resultado:
Array (
   [0] => Array (
       [membro_id] => 1465
       [membro_nome] => Gustavo Silva de Oliveira
       [membro_estado] => 4
       [membro_cidade] => Humaití
       [membro_status] => 1
       [membro_validade] => 31/07/2018
       [estado_id] => 4
       [estado_codigouf] => 13
       [estado_nome] => Amazonas
       [estado_uf] => AM
       [estado_regiao] => 1
       [status_id] => 1
       [status_nome] => Ativo
   )
   [1] => Array (
       [membro_id] => 1581
       [membro_nome] => Ânio Neves de Souza
       [membro_estado] => 4
       [membro_cidade] => Manaus
       [membro_status] => 1
       [membro_validade] => 31/07/2019
       [estado_id] => 4
       [estado_codigouf] => 13
       [estado_nome] => Amazonas
       [estado_uf] => AM
       [estado_regiao] => 1
       [status_id] => 1
       [status_nome] => Ativo
   )
)

Quero pegar o campo  [membro_status] => 1 de cada resultado, fiz o seguinte $membros[0]['membro_status'], porém só retorna o primeiro array, alguém poderia dar um help?
Answer: Victor, tudo bem?
Use a função foreach do php.
foreach($nome_da_variavel as $nome_individual){
    var_dump($nome_individual);
}

Segue link do Manual PHP.
http://php.net/manual/pt_BR/control-structures.foreach.php
Comment: Por favor, informe que a sua pergunta foi respondida.
Comment: Caso tenha dificuldade na confecção do código só pedir.
Comment: Na mosca man, obrigado!
Comment: @VictorHugo coloque a resposta como certa. Fica abaixo da do lugar da pontuação. Só você tem esse poder.
Answer: Use o foreach
foreach($arrays as $array) {
  $status = $array["membro_status"];
}

Answer: Simples.
$novoArray = array_column($seuArray,'membro_id');
print_r($novoArray);

Pode ser interessante usando o terceiro parâmetro em que o array é retornado com a chave=>valor. Exemplo:
$novoArray = array_column($seuArray,'membro_status', 'membro_nome');
print_r($novoArray);

Onde chave é a coluna informada como terceiro parâmetro e value o segundo parâmetro.


Do you have to completely master each Pumping Nylon exercises thoroughly?

Question: Presently I am working on Pumping Nylon exercises, but I cannot play as fast as the exercise asks me to.
Do I have to completely master each piece or can I just move on after playing through it moderately fine?
Comment: I think this question applies to many technique training books and video tutorials. I'd go as far as to say, _most_ students initially face the same problem. What does this book itself say?
Answer: Is the course guaranteeing that once completed perfectly you'll become a concert guitarist? I doubt it!
So, use each exercise as just that. An exercise. Do it to the best of your ability, move on to another. It may well be that after a period of time - a couple of weeks - several years - that you'll be capable of playing it at the recommended tempo. But until then, there are many other fish to fry. Speed is only one consideration when playing. Probably not the most important.
Learning to get a better tone, playing with more feeling, understanding what you're actually doing, come higher up my list. The tempi suggested are ideas (ideals?) from the author, and thus are subjective, not necessarily objective. As long as you can play each without error, at your maximum speed, that's sufficient. Good luck!
Answer: Unless the book itself tells you it's necessary, then no. Take each exercise as far as you can, but then return to them periodically. Tempos are an ideal given by the author, but any guitarist might max out at a slower or higher tempo. But in general, exercises that you played at a certain top speed earlier, will become faster as you grow overall.
Returning periodically to any material is a good idea in music generally, with the understanding that "periodically" could mean months or even years. I once knew a pianist who at 98 was still studying pieces he learned at 20, and he was still finding new things in them.


Are different dynamics for different hands on piano permissible?

Question: Is it a normal practice for a piano part to have different dynamics for the left and for the right hand?
And if it's not common, what will happen if I specify different dynamics for the left and for the right hand? Will a professional pianist not be able to play, say, pp on the left and mf on the right hand?
Answer: Yes, of course!! Each and every note on a piano - upright, grand, and most electronics these days, are separate entities, with their own dynamics.
There are some pieces which need the l.h. to play the melody, while the r.h. plays an accompaniment, so yes, not only is it possible, it's obligatory!
It's even necessary in some pieces for an individual hand to play notes (with different fingers) at different volumes, and certainly, concert pianists, and even those at grade V and above, will be able to achieve this. The same goes for staccato/legato notes. Go ahead and indicate what dynamics each hand must use, individually. We pianists are quite used to being directed thus!
In fact, years ago, when a lot of electronic pianos were not touch sensitive, I found it very difficult to play 'properly' - just because every note came out at the same volume, both hands. Thank goodness they've advanced!
Comment: ... but as a composer, just because you can doesn't mean you should. If the overall dynamic is marked the middle of the staff, a competent pianist can use her judgment to balance the melody and accompaniment without the "micromanagement" of marking the LH as mf and RH as f, etc.
Answer: The whole point of a pianoforte keyboard is to produce dynamics per note rather than per instrument.  Players are expected to be able to produce different dynamics and different articulations on both hands.  Classical concert pianists are even expected to articulate voices distinctly that happen to use the same hand.
Note that "professional pianist" covers a wide range of skills and genres and audiences since it just means "playing piano for a living".
Comment: "Classical concert pianists are even expected to articulate voices distinctly that happen to use the same hand" - WOW! Thank you. I didn't know that.
Comment: @brilliant It doesn't need to be as amazing or as difficult as it sounds. The Piano Collection version of Dearly Beloved has a slow background melody on the right hand alongside the main melody. It's just played much slower so it's only one quarter note for every half note on the main melody. https://youtu.be/37nowT5JTUA?si=VGDfMGQUlEeK_Lrg&t=35
Comment: @brilliant one nice example of this that comes to my mind the 2nd movement of Prokofiev's 6th piano sonata: https://youtu.be/jTk7lP9ScVI?si=R3YItH30kyZwoRea (in the first section, all staccato except some top notes in right hand are held for IMO very "fun" effect. Throughout, the RH and LH have such different textures, really a marvel!) Contrapuntal works (https://en.wikipedia.org/wiki/Counterpoint), having different lines be played with different dynamics and textures is necessary to bring out the multilayered sound.
Answer: "Is it a normal practice for a piano part to have different dynamics for the left and for the right hand?"
Yes, perfectly normal, for players well short of 'professional' skills!
And asking different fingers of the SAME hand to simultaneously play different volumes is not a terribly advanced technique.


Solve $x^2+x+1\equiv0\pmod5$

Question:
Solve:
$$x^2+x+1\equiv0\pmod5$$

My attempt:
Our proffesor told us that if we have $ax^2+bx+c\equiv\pmod p$ we need to multiply by $4a$, to get form of $(\text{ something})^2\equiv D\pmod p$.
$p$ is a prime and $\gcd(4a,p)=1$, so I tried to do that here:
$$4x^2+4x+4\equiv 0 \pmod 5$$
But now
$$(2x+1)^2+3\equiv 0 \pmod 5$$
$$(2x+1)^2\equiv -3 \pmod 5$$
Comment: Well $-3\equiv 2 \pmod 5$, and as lab says $2$ is not a square mod $5$
Comment: That's an elegant way of solving this problem, multiplying by 4. One generally thinks of brute force.
Answer: For any integer $a,$
$$a\equiv0,\pm1,\pm2\pmod5\implies a^2\equiv0,1,4\pmod5\not\equiv-3$$
Comment: So, there is no solution?
Comment: @Error404,  Exactly.
Answer: The usual formula $$x = \frac{-1\pm \sqrt{1^2 - 4\cdot 1 \cdot 1}}{2}$$ still works for integers modulo a prime, you just have to interpret the square root and the division differently. And in this case $\sqrt{-3}$ doesn't exist in the integers modulo $5$, so there are no roots.
Answer: More generally, there's this trick for solving quadratic congruences: if $\gcd(n,2a)=1$, then:
$$ax^2+bx+c\equiv 0\pmod{n}$$
$$\stackrel{\cdot 4a}\iff (2ax+b)^2\equiv b^2-4ac\pmod{n}$$
In this case,
$$x^2+x+1\equiv 0\pmod{5}$$
$$\stackrel{\cdot 4}\iff (2x+1)^2\equiv -3\equiv 2\pmod{5},$$
contradiction, because $2$ is not a quadratic residue mod $5$ (to see this, notice $(5k\pm 1)^2\equiv 1\pmod{5}$, $(5k\pm 2)^2\equiv 4\pmod{5}$, $(5k)^2\equiv 0\pmod{5}$).
Answer: In this specific case, there is yet another way:
Since $(x-1)(x^2+x+1)=x^3-1,$ we find that a solution to the equation must also satisfy $x^3-1\equiv0\pmod5.$
But if $x^3\equiv1\pmod5,$ then clearly $x^4\equiv x\pmod5.$ Also, Fermat's little theorem says that $x^4\equiv1\pmod5$ if $5\not\mid x.$ Thus the solution is either $x\equiv0\pmod5$ or $x\equiv x^4\equiv1\pmod5,$ while these two cases can easily be seen not to satisfy the equation in question. Therefore there are no solutions.
Hope this helps.

Solve $x^2+x+1\equiv0\pmod5$


Kruskal Algorithm proof

Question: I was reading the proof of Kruskal Algorithm Reference.
What I am not understanding is why we assume that Kruskal always chooses the smallest edges? Maybe it did not choose one of the smallest edges because it could form a cycle? So in the proof here (and actually in many other ones)Reference, at the end of the proof, they conclude that $w(e_i) = w(e_0)$ since Kruskal chose $e_i$  which implies $w(e_i) \leq w(e_0)$, but maybe Kruskal didn't choose $e_0$ because it could form a cycle even though $w(e_0) \leq w(e_i)$?
Comment: The algorithm, by definition, chooses the smallest edge that does not form a cycle with any of the previously chosen edges.
Comment: Yes, I know but why in the proof, we say that $w(e_i) \leq w(e_0)$. Maybe it is not the case.
Comment: Thank you for quickly clarifying your question I understand now what you are asking I think.
Comment: For more clarity, here is my intuition behind the question:  For example, we have a set of edges with the following values: 1,2,3,4,5,6,20,21. Let's say the algorithm will choose 1 but after choosing 1, it saw it cannot choose 2,3,4,5,6 (it is exagerated) because they cause a cycle, so, it will choose 20,21. However, if we started by the edge 4, we could choose 5,6. I know this example is not applicable, but the idea is the following: maybe choosing a smaller edge at an earlier stage would have a negative impact at later stage
Comment: I answered your question and you do not seem to take a look at my answer
Comment: I apologize for this misunderstanding but I saw your answer but until now I haven't understood it. I need some time to grasp the correctness of this algorithm.
Comment: What didn't you understand about my answer?
Comment: This part:with strict smaller weight than $e_i$  which contradict the definition of $e_i$
.
Comment: After several readings, I read a proof based on cut property which I found it logical compared to the other ones:
https://www.cs.princeton.edu/courses/archive/spr07/cos226/lectures/mst

What I understood at the end is that the second property of the algorithm (choosign an edge that does not form a cycle) plays an essential part in making this greedy algorithm an optimal one
Answer: If $w(e_0)< w(e_i)$ and $e_0$ was not chosen then it means that it created a cycle with a subtree of $T$. This means that you will find an edge in $T$ that is not in $T_0$ and with strict smaller weight than $e_i$ which contradict the definition of $e_i$.
Answer: The idea is, you've made a forest $F$ out of your chosen edges.
By induction assume there exists $T$ a minimum spanning tree containing those edges and none of the rejected edges.
Then the algorithm chooses $e_1$ ($e_i$ in your link).
If $e_1$ is in $T$ then the inductive conclusion is established.
Otherwise, $T + e_1$ contains a cycle $C$.
$C$ contains an edge $e_2$ ($e_0$ in your link), distinct from $e_1$, not in $F$.  Because otherwise $F+e_1$ would have a cycle.
$e_2$ cannot be smaller than $e_1$, because it would have been previously chosen by the algorithm.  I think this is the part you are asking about.  Adding $e_2$ to $F$ can't form a cycle because $T$ is a supergraph of $F$ and $T$ without $e_1$ doesn't form a cycle.
$e_2$ cannot be larger than $e_1$, because then $T + e_1 - e_2$ is a smaller spanning tree than $T$, violating the induction assumption.
So $T + e_1 - e_2$ is a minimum spanning tree containing $F+e_1$ and the inductive conclusion is satisfied.
Comment: Thank you for your response. But my intuition say, maybe in the future while building the MST we cannot choose an edge because it could form a cycle and the next small edge is very big so it could transform the MST into a non MST. To clarify my point here is an example:
Comment: I don't know if this example could apply but I am stating it just to explain my idea: For example, we have a set of edges with the following values: 1,2,3,4,5,6,20,21. Let's say the algorithm will choose 1 but after choosing 1, it saw it cannot choose 2,3,4,5,6 (it is exagerated) because they cause a cycle, so, it will choose 20,21. However, if we started by the edge 4, we could choose 5,6. I know this example is not applicable, but the idea is the following: maybe choosing a smaller edge at an earlier stage would have a negative impact at later stage
Answer: In the linked proof $T$ is a spanning tree produced by Kruskal's algorithm and $T_0$ is a minimum spanning tree. Also $e_1, e_2, \ldots, e_{i-1}$ are all edges of both $T$ and $T_0$, and $e_i$ is an edge of $T$ but not one of $T_0$.
The edge $e_0$ is chosen to be an edge of the cycle $C$ in $G_0$, but not an edge of $T$. The edges of $G_0$ are the edges of $T_0$ together with $e_i$, which is an edge of $T$, so $e_0$ must be an edge of $T_0$.
Hence $e_1, e_2, \ldots, e_{i-1}$ and $e_0$ are all edges of the tree $T_0$ and trees don't contain cycles, so in Kruskal's algorithm choosing $e_0$ rather than $e_i$ as the next edge would not make a cycle.

Kruskal Algorithm proof


Prove that that a map in $C^N$ in the metric topology is continuous to the Zariski topology, but that the map is not a homeomorphism.

Question: Prove that that a map in $C^N$ in the metric topology is continuous to the Zariski topology, but that the map is not a homeomorphism.
My Work:
I plan to use the fact that the metric topology is a Hausdorff space, whereas the Zariski topology in $C^N$ is not a Hausdorff, but then wouldn't the map not be continuous?
Answer: If I interpret your question, you want to show that the identity map of $(C^n,d)\rightarrow (C^n,Zar)$ is continuous, which also means that the Zariski topology is weaker than the metric topology. This is a consequence of the fact that a Zariski open subset is also open for the metric topology.
On the other hand $Id:(C^n,Zar)\rightarrow (C^n,d)$ is not continuous, since there exists open subsets of $(C^n,d)$ like the open ball $B(0,1)$ which are not Zariski open, so their inverse image by the identity is not Zariski open.


What fraction of repeat experiments will have an effect size within the 95% confidence interval of the first experiment?

Question: Let's stick to an ideal situation with random sampling, Gaussian populations, equal variances, no P-hacking, etc.
Step 1. You run an experiment say comparing two sample means, and compute a 95% confidence interval for the difference between the two population means.
Step 2. You run many more experiments (thousands). The difference between means will vary from experiment to experiment due to random sampling.
Question: What fraction of the difference between means from the collection of experiments in step 2 will lie within the confidence interval of step 1?
That can't be answered. It all depends on what happened in step 1. If that step 1 experiment was very atypical, the answer to the question might be very low.
So imagine that both steps are repeated many times (with step 2 repeated many more times). Now it ought to be possible, I would think, to come up with an expectation for what fraction of repeat experiments, on average, have an effect size within the 95% confidence interval of the first experiment.
It seems that the answer to these questions need to be understood to evaluate reproducibility of studies, a very hot area now.
Comment: For each original (step 1) experiment $i$, define $x_i$ as the fraction of subsequent (step 2) results that produce findings within the original result's confidence interval. You want to compute the empirical distribution of $x$?
Comment: Yes, you understand what I am asking
Comment: @MatthewGunn asked if you wanted the empirical distribution of the "capture fraction" for future observations. Your post asked *"...it ought to be possible, I would think, to come up with an expectation for what fraction of repeat experiments, on average, have an effect size within the 95% confidence interval of the first experiment"*. This is not a distribution but an expected value (average).
Comment: Whuber's analysis is great, but if you need a citation then here is a paper that discusses exactly this question in great detail: [Cumming & Maillardet, 2006, Confidence Intervals and Replication: Where Will the Next Mean Fall?](http://psych.colorado.edu/~willcutt/pdfs/Cumming_2006.pdf). They call it *capture percentage* of a confidence interval.
Answer: Analysis
Because this is a conceptual question, for simplicity let's consider the situation in which a $1-\alpha$ confidence interval $$\left[\bar x^{(1)} + Z_{\alpha/2} s^{(1)}/\sqrt{n}, \bar x^{(1)} + Z_{1-\alpha/2} s^{(1)}/\sqrt{n}\right]$$ is constructed for a mean $\mu$ using a random sample $x^{(1)}$ of size $n$ and a second random sample $x^{(2)}$ is taken of size $m$, all from the same Normal$(\mu,\sigma^2)$ distribution.  (If you like you may replace the $Z$s by values from the Student $t$ distribution of $n-1$ degrees of freedom; the following analysis will not change.)
The chance that the mean of the second sample lies within the CI determined by the first is
$$\Pr\left(\bar x^{(1)} + \frac{Z_{\alpha/2}}{\sqrt{n}} s^{(1)} \le \bar x^{(2)} \le \bar x^{(1)} + \frac{Z_{1-\alpha/2}}{\sqrt{n}} s^{(1)}\right) =\Pr\left(\frac{Z_{\alpha/2}}{\sqrt{n}} s^{(1)} \le \bar x^{(2)}-\bar x^{(1)} \le  \frac{Z_{1-\alpha/2}}{\sqrt{n}} s^{(1)}\right).$$
Because the first sample mean $\bar x^{(1)}$ is independent of the first sample standard deviation $s^{(1)}$ (this requires normality) and the second sample is independent of the first, the difference in sample means $U = \bar x^{(2)} - \bar x^{(1)}$ is independent of $s^{(1)}$.  Moreover, for this symmetric interval $Z_{\alpha/2}=-Z_{1-\alpha/2}$.  Therefore, writing $S$ for the random variable $s^{(1)}$ and squaring both inequalities, the probability in question is the same as
$$\Pr\left(U^2 \le \left(\frac{Z_{1-\alpha/2}}{\sqrt{n}}\right)^2 S^2\right)= \Pr\left(\frac{U^2}{S^2} \le \left(\frac{Z_{1-\alpha/2}}{\sqrt{n}}\right)^2\right).$$
The laws of expectation imply $U$ has a mean of $0$ and a variance of
$$\operatorname{Var}(U) = \operatorname{Var}\left(\bar x^{(2)} - \bar x^{(1)}\right) = \sigma^2\left(\frac{1}{m} + \frac{1}{n}\right).$$
Since $U$ is a linear combination of Normal variables, it also has a Normal distribution.  Therefore $U^2$ is $\sigma^2\left(\frac{1}{n} + \frac{1}{m}\right)$ times a $\chi^2(1)$ variable.  We already knew that $S^2$ is $\sigma^2/n$ times a $\chi^2(n-1)$ variable.  Consequently, $U^2/S^2$ is $1/n + 1/m$ times a variable with an $F(1,n-1)$ distribution.  The required probability  is given by the F distribution as
$$F_{1,n-1}\left(\frac{Z_{1-\alpha/2}^2}{1 + n/m}\right).\tag{1}$$

Discussion
An interesting case is when the second sample is the same size as the first, so that $n/m=1$ and only $n$ and $\alpha$ determine the probability.  Here are the values of $(1)$ plotted against $\alpha$ for $n=2,5,20,50$.

The graphs rise to a limiting value at each $\alpha$ as $n$ increases.  The traditional test size $\alpha=0.05$ is marked by a vertical gray line.  For largish values of $n=m$, the limiting chance for $\alpha=0.05$ is around $85\%$.
By understanding this limit, we will peer past the details of small sample sizes and better understand the crux of the matter.  As $n=m$ grows large, the $F$ distribution approaches a $\chi^2(1)$ distribution.  In terms of the standard Normal distribution $\Phi$, the probability $(1)$ then approximates
$$\Phi\left(\frac{Z_{1-\alpha/2}}{\sqrt{2}}\right) - \Phi\left(\frac{Z_{\alpha/2}}{\sqrt{2}}\right) = 1 - 2\Phi\left(\frac{Z_{\alpha/2}}{\sqrt{2}}\right) .$$
For instance, with $\alpha=0.05$, $Z_{\alpha/2}/\sqrt{2} \approx -1.96/1.41 \approx -1.386$ and $\Phi(-1.386) \approx 0.083$. Consequently the limiting value attained by the curves at $\alpha=0.05$ as $n$ increases will be $1 - 2(0.083) = 1 - 0.166=0.834$.  You can see it has almost been reached for $n=50$ (where the chance is $0.8383\ldots$.)
For small $\alpha$, the relationship between $\alpha$ and the complementary probability--the risk that the CI does not cover the second mean--is almost perfectly a power law.  Another way to express this is that the log complementary probability is almost a linear function of $\log\alpha$.  The limiting relationship is approximately
$$\log\left(2\Phi\left(\frac{Z_{\alpha/2}}{\sqrt{2}}\right)\right) \approx -1.79712 + 0.557203\log(20 \alpha) + 0.00657704 (\log(20 \alpha))^2 + \cdots$$
In other words, for large $n=m$ and $\alpha$ anywhere near the traditional value of $0.05$, $(1)$ will be close to
$$1 - 0.166 (20\alpha)^{0.557}.$$
(This reminds me very much of the analysis of overlapping confidence intervals I posted at https://stats.stackexchange.com/a/18259/919.  Indeed, the magic power there, $1.91$, is very nearly the reciprocal of the magic power here, $0.557$.  At this point you should be able to re-interpret that analysis in terms of reproducibility of experiments.)

Experimental results
These results are confirmed with a straightforwward simulation.  The following R code returns the frequency of coverage, the chance as computed with $(1)$, and a Z-score to assess how much they differ.  The Z-scores are typically less than $2$ in size, regardless of $n, m, \mu, \sigma, \alpha$ (or even whether a $Z$ or $t$ CI is computed), indicating the correctness of formula $(1)$.
n <- 3      # First sample size
m <- 2      # Second sample size
sigma <- 2
mu <- -4
alpha <- 0.05
n.sim <- 1e4
#
# Compute the multiplier.
#
Z <- qnorm(alpha/2)
#Z <- qt(alpha/2, df=n-1) # Use this for a Student t C.I. instead.
#
# Draw the first sample and compute the CI as [l.1, u.1].
#
x.1 <- matrix(rnorm(n*n.sim, mu, sigma), nrow=n)
x.1.bar <- colMeans(x.1)
s.1 <- apply(x.1, 2, sd)
l.1 <- x.1.bar + Z * s.1 / sqrt(n)
u.1 <- x.1.bar - Z * s.1 / sqrt(n)
#
# Draw the second sample and compute the mean as x.2.
#
x.2 <- colMeans(matrix(rnorm(m*n.sim, mu, sigma), nrow=m))
#
# Compare the second sample means to the CIs.
#
covers <- l.1 <= x.2 & x.2 <= u.1
#
# Compute the theoretical chance and compare it to the simulated frequency.
#
f <- pf(Z^2 / ((n * (1/n + 1/m))), 1, n-1)
m.covers <- mean(covers)
(c(Simulated=m.covers, Theoretical=f, Z=(m.covers - f)/sd(covers) * sqrt(length(covers))))

Comment: +1. This is a great analysis (and your answer has way too few upvotes for what it is). I just came across a paper that discusses this very question in great detail and I thought you might be interested: [Cumming & Maillardet, 2006, Confidence Intervals and Replication: Where Will the Next Mean Fall?](http://psych.colorado.edu/~willcutt/pdfs/Cumming_2006.pdf). They call it *capture percentage* of a confidence interval.
Comment: Update: Thanks to the ongoing discussion in the sister thread, I now believe my reasoning in the above comment was *not* correct. 95% CIs have 83% "replication-capture", but this is a statement about repeated sampling and cannot be interpreted as giving a probability conditioned on one particular confidence interval, at least not without further assumptions. (Perhaps both this and previous comments should better be deleted in order not to confuse further readers.)
Comment: You say that using t instead of z won't make much difference. I believe you but haven't checked yet.  With small sample size, the two critical values can differ a lot and the t distribution is the correct way to compute the CI. Why do you prefer to use z??
Comment: It's purely illustrative and $Z$ is simpler. When you use $t$ it is interesting that the curves in the figure start high and descend to their limit. In particular, the chance of reproducing a significant result is then much higher for small samples than for large! Note that there's nothing to check, because you are free to interpret $Z_{\alpha}$ as a percentage point of the appropriate Student t distribution (or of any other distribution you might care to name). Nothing changes in the analysis. If you do want to see the particular effects, uncomment the `qt` line in the code.
Comment: @Amoeba Thank you for the reference.  I especially appreciate one general conclusion therein: "Replication is central to the
scientific method, and researchers should not turn a blind
eye to it just because it makes salient the inherent uncertainty
of a single study."
Comment: One surprising corollary of this analysis that came to my mind now is that if we do an experiment and obtain $p\approx 0.05$ (meaning that 95% CI is just about touching zero), then the replication will yield an effect *in the opposite direction* with probability $(1-0.83)/2 \approx 0.08$ (unless $n$ is very small), and this result does not depend on the population effect size or statistical power or anything else. For $p=0.01$ it's around 3%. Is my reasoning correct?
Answer: [Edited to fix the bug WHuber pointed out.]
I altered @Whuber's R code to use the t distribution, and plot coverage as a function of sample size. The results are below. At high sample size, the results match WHuber's of course.

And here is the adapted R code, run twice with alpha set to either 0.01 or 0.05.
sigma <- 2
mu <- -4
alpha <- 0.01
n.sim <- 1e5
#
# Compute the multiplier.

for (n in c(3,5,7,10,15,20,30,50,100,250,500,1000))
{
   T <- qt(alpha/2, df=n-1)
# Draw the first sample and compute the CI as [l.1, u.1].
#
x.1 <- matrix(rnorm(n*n.sim, mu, sigma), nrow=n)
x.1.bar <- colMeans(x.1)
s.1 <- apply(x.1, 2, sd)
l.1 <- x.1.bar + T * s.1 / sqrt(n)
u.1 <- x.1.bar - T * s.1 / sqrt(n)
#
# Draw the second sample and compute the mean as x.2.
#
x.2 <- colMeans(matrix(rnorm(n*n.sim, mu, sigma), nrow=n))
#
# Compare the second sample means to the CIs.
#
covers <- l.1 <= x.2 & x.2 <= u.1
#
Coverage=mean(covers)

print (Coverage)

}

And here is the GraphPad Prism file that made the graph.
Comment: @whuber. Yikes! Of course you are right. Embarrassing. I've fixed it. As you pointed out the coverage is higher with tiny sample sizes.  (I fixed the simulations, and didn't try your theoretical function.)
Comment: I believe your plots do *not* use the *t* distribution, due to a bug: you set the value of `T` outside the loop! If you would like to see the correct curves, just plot them directly using the theoretical result in my answer, as given at the end of my `R` code (rather than relying on the simulated results): `curve(pf(qt(.975, x-1)^2 / ((x * (1/x + 1/x))), 1, x-1), 2, 1000, log="x", ylim=c(.8,1), col="Blue");
curve(pf(qt(.995, x-1)^2 / ((x * (1/x + 1/x))), 1, x-1), add=TRUE, col="Red")`
Comment: I am glad you fixed it, because it is very interesting how high the coverage is for small sample sizes.  We could also invert your question and use the formula to determine what value of $Z_{\alpha/2}$ to use if we wished to assure (before doing any experiments), with probability $p=0.95$ (say), that the mean of the second experiment would lie within the two-sided $1-\alpha$ confidence interval determined from the second.  Doing so, as a routine practice, could be one intriguing way of addressing some criticism of NHST.
Comment: @whuber  I think the next step is to look at the distribution of coverage. So far, we have the average coverage (average of many first experiments, with average of many second experiments each). But depending on what the first experiment is, in some cases the average coverage will be poor. It would be interesting to see the distribution. I'm trying to learn R well enough to find out.
Comment: Regarding the distributions, see the paper I linked to in the comments above.


UDP Protocol - ICMP Error Generation

Question: I know that UDP has no real error control facilties outside of silent discard of packets failing checksums.
Am I correct in thinking that a UDP packet with a TTL=1 reaching a router will generate an ICMP Time Exceeded message, and a UDP packet arriving with an unused port # (54823 or something) at an end host will be rejected, causing an ICMP Port Unreachable message - and that both of those ICMP messages would be sent back to the originator of the message?
I'm pretty sure that's how it works, but I wanted to make sure I wasn't confusing myself somehow
Answer: Yes, you're right. That is also how traceroute does it.
Answer: That's right, but if you want to receive those messages in your app you have to use connect for the socket.

UDP Protocol - ICMP Error Generation


ASIHttpRequest responseStatusCode = 200. But not getting right responseData from server

Question: All
This is a problem which happens rarely. In fact I had to spend a lot of time to reproduce it but here it is anyways.
I am using ASIHTTPRequest to get some data from my server. I throw error for anything apart from those having responseStatusCode == 200. My server returns some messages.
What I noticed is, that sometimes, depending on my wireless connection (on laptop simulator usage), the ones which needs authentication, ASIHttpRequest returns response of 200, but the responseData is something like the following instead of the messages from my server
<TITLE>Cisco Systems Inc. Web Authentication Redirect</TITLE><META http-equiv="Cache-control" content="no-cache"><META http-equiv="Pragma" content="no-cache"><META http-equiv="Expires" content="-1"><META http-equiv="refresh" content="1; URL=https://webauth-redirect.oracle.com/login.html?redirect=184.108.40.206/scripts_dummy/messagesx.php">

Is this correct? If the message from the server was not received should not the responseStatusCode be something other than 200
How do I go about handling this kind of situation? meaning after checking responseStatusCode == 200 does not seem to be good enough. This was just an example. In other wireless regions, different garbage is printed out.
UPDATE
Not sure if this has any role to play but I have
request.shouldUseRFC2616RedirectBehaviour = YES; // where request is ASIHTTPRequest

Answer: That's not ASIHTTPRequest or your client code's fault. That's the server expecting the client to be a web browser and sending it a a meta refresh redirect (that is, an HTML page with a redirect embedded in it) rather than an HTTP 30x, which ASIHTTP would have handled for you.
This is an excellent example of how meta refresh has been abused: it was meant to refresh the current page, but people started using it to send the client somewhere else, which was what HTTP 30x was already designed for. Googling for "meta refresh vs 301 redirect" will give you plenty of blog posts making the arguments.
In your case, unless you can get your server to behave friendlier to non-browser clients, you'll need to check for this condition yourself when response code is 200, parse out the redirect and re-issue the request yourself.
Comment: thanks a lot for your response. When you say "you'll need to check for this condition yourself", would you happen to have any idea how I can use ASIHTTPRequest to do that?
Comment: The result of the request (as you probably know) is in `request.responseString` - you'll need to search that string for the `http-equiv="refresh"` and make a new ASIHTTPRequest to the destination in `URL=`.
Comment: Ok I didn't really like that solution. Looked like a hack. What I am thinking is to send a special key/value pair from the server in the response header. Say  header('My App:' . 'success'); And then check for the presence of that key/value pair in the responseHeaders from ASIhttpRequest. This way I should be always safe?
Comment: If *you* have control of the server, just send a 301! If you don't have control of the server, not sure I'm following you.
Answer: After thinking about this for a few, I've come up with an alternate strategy. Content type will be preserved and should not be muddled with.
You should be able to use the content type as a flag that you are receiving a proxy injected page. Set a content type parameter then have your app key off that parameter. Any responses that don't have the parameter are invalid.
$content_type = 'text/html; FooCorp-MyApp=true'

BTW: why are you using a content type of text/html if you don't properly support HTML processing. Meta refresh should be a part of any HTML engine. If you don't need HTML, you may want do consider using a data specific content type like XML, YAML, or JSON.

The question has been raised, "is that valid?"
From RFC 2616: 3.7 Media Types

The type, subtype, and parameter attribute names are case- insensitive. Parameter values might or might not be case-sensitive, depending on the semantics of the parameter name. Linear white space (LWS) MUST NOT be used between the type and subtype, nor between an attribute and its value. The presence or absence of a parameter might be significant to the processing of a media-type, depending on its definition within the media type registry.
Note that some older HTTP applications do not recognize media type parameters. When sending data to older HTTP applications, implementations SHOULD only use media type parameters when they are required by that type/subtype definition.

To me, the takeaway from that is don't send non-standard parameters to older clients. In context, it means you're safe if you are sending it to any client made since 2000.
Comment: Thanks for the response. Now I get a chance to upvote and mark this right. You deserved it based on your comments earlier as well. You were right that I should have set the content type as "application/json" because thats what I am expecting. So now as a final solution I will do both the $content_type = 'application/json; FooCorp-MyApp=true' and the custome header thingy and do a OR check. That way I should be the safest. One question though...is it ok to put non-registered FooCorp-MyApp=true in the content type?
Comment: I updated my answer. BTW: just checking for 'application/json' should be good enough. The proxy would be a real bastard if it sent an HTML document with a Content-Type of 'application/json'.
Answer: I ended up passing a special key/value pair in my response header to make sure the client understands the response is from my server and not from some intermediary redirection.
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
   $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
   header($status_header);
   header('Content-type: ' . $content_type);
   $value = 'success';
   header('myApp:' . $value); // --> I will always check in my client that the key myApp has the value success

echo $body;
}

Comment: This solution could cause you problems in the future. Some proxies filter out unknown headers. Unless you have tight control over the network environment, you can't always rely on custom headers.
Comment: In addition, you should always begin non-standard headers with 'x-'. Something like 'x-MyApp:'. $value would do nicely.
Comment: True. Is there a cleaner alternative you can propose?
Comment: Also the X- is deprecated. See http://stackoverflow.com/questions/3561381/custom-http-headers-naming-conventions
Comment: WTF: [draft-ietf-appsawg-xdash-05](http://tools.ietf.org/html/draft-ietf-appsawg-xdash-05) is a nightmare. Their answer is to pollute the global namespace because of piss poor implementations. Appendix B points out the silliness. I guess I would still follow the recommendation and use 'FooCorp-MyApp' (where FooCorp is your company name).


If condition combination in batch file

Question: The following if condition acts as IF NOT DEFINED PARAM_INSERT_DATE_US AND IF NOT DEFINED PARAM_UPDATE_DATE_US GOTO END
IF NOT DEFINED PARAM_INSERT_DATE_US IF NOT DEFINED PARAM_UPDATE_DATE_US GOTO END

Where PARAM_INSERT_DATE_US and PARAM_UPDATE_DATE_US are two variables set at the beginning of batch file.
But I want something similar to this:
IF NOT DEFINED PARAM_INSERT_DATE_US OR IF NOT DEFINED PARAM_UPDATE_DATE_US GOTO END

Is there a way to achieve it concisely?
Obviously I can break the if statements into 2 to achieve that behavior but I was looking for a concise format as I need to check for 4 variables or more.
I will appreciate any help.
Thanks.
Comment: Thanks @NPE. But seems like there's no combined way to do what I was looking for :/ .
Answer: :elsewhere

...

if defined PARAM_INSERT_DATE_US IF DEFINED PARAM_UPDATE_DATE_US goto elsewhere
:end

would do the job - arranging the batch that way may be a game...
Answer: This will work for the situation you have described.
for %%a in (PARAM_INSERT_DATE_US PARAM_UPDATE_DATE_US) do if not defined %%a goto :END

If condition combination in batch file


Nginx ssl - SSL: error:0906D06C:PEM routines:PEM_read_bio:no start line

Question: I am trying to enable ssl on a server using a certificate from 123-reg but I keep getting this error:
nginx: [emerg] SSL_CTX_use_certificate_chain_file("/opt/nginx/conf/cleantechlms.crt") failed (SSL: error:0906D06C:PEM routines:PEM_read_bio:no start line error:140DC009:SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib)

This is my nginx config:
server {
  listen 443;
  server_name a-fake-url.com;
  root /file/path/public;
  passenger_enabled on;

  ssl on;
  ssl_certificate /opt/nginx/conf/cleantechlms.crt;
  ssl_certificate_key /opt/nginx/conf/cleantechlms.key;
 }

I have tried setting my crt and key to full file permissions but there is no difference.
My crt file is the crt I was issued concatenated with the ca crt.
Update
I have tried copying both the keys in sperate files and then running 'cat mykey.crt >> ca.cert'
Also I tried manually copying the keys into the same file.
Any ideas?
Comment: Your `/opt/nginx/conf/cleantechlms.crt` is broken somehow. How did you create it? Could you post all steps you did?
Comment: In `cleantechlms.crt` you want to have only your public certificate without key and chain certificates from your ca. If you open it in text editor you should see just --BEGIN-CERTIFICATE-- blocks..
Answer: Thanks for your help, this is how I solved it:

Copy the certificates into a text editor to ensure there is no whitespace (I had already done this)
Ensure the beginning and end certificate statements are on there own line and have the same number of '-' at each end.
Ensure each line has 64 chars (except the last line)
Comment: I also got the error when the .cer file contained only the top level cert and not the entire bundled / chain of certs (intermediate and root ca)
Answer: I ended up with same exception and got it fixed by adding private key(x.509 + privatekey at the end) in the same pem file (pem format). I think its because I used to have the same format and validating the config with "nignx -t".
Hope it helps.


How to allow integer and decimal fields with default values to be saved as empty.

Question: If I set a default value on a decimal or integer field, the user cannot delete the default value and save the node.
They can set the value to another value including zero, and that is saved correctly.
But if the contents of the field is deleted, on save, the field is automatically populated with the default value again.
This doesn't seem right.  I guess I could intercept the empty field and set it to zero, but surely that's not necessary?  Am I missing something?
Answer: This is a bug in D7. Checkout https://www.drupal.org/node/1253820. I checked it works while editing content but not while creating. This has been fixed in D8. For D7, you can write custom code to handle this.
Comment: THANK YOU!  I have worked around it, but I thought I must have done something idiotic to cause the problem and had added a messy kludge to fix.  Feel much better now I know it's not me!  :-D


Drupal 7.12 : views filters

Question: i have a mark as checkbox field with two options - published and unpublished.
i want articles marked as 'published' to appear on a view page and those marked as 'unpublished' to appear after the published items as an attachment to the view. the unpublished articles will only be visible to the author. How can i go about achieving this? I have tried using the filter but to no avail. i chose the field name and selected 'is one of' then selected publish, but this did not work. Any suggestions?
Answer: Drupal contains a published/unpublished feature by default, which can be filtered in views using the Content: Published filter.
If you want to use a custom field though it should be as simple as you described. Assuming the published field is a taxonomy reference, you should be able to apply a filter to that field and select 'is one of' and the appropriate term (published). I tried this and it works.
As for the second part, you can clone the view and change the field filter to unpublished. Then add a Content: Author relationship and a User: Current (Yes) filter to filter it to content that the current user has authored (you might also want to put some access restrictions on this view). This view can then be added to the 'Footer' section of the first view.
Comment: thanks for the reply. I used cck field. I will try taxonomy reference and see how it goes. thanks again
Comment: It worked, thanks. I used an attachment to display the unpublished articles. However, the title of the attachment is not appearing. I override the title in the contextual filter. the title is showing in the view preview but not on the actual page. Is there anything am missing?

Drupal 7.12 : views filters


Scheduling msbuild task build Nightly

Question: I am using MSBuild for building our test project from command prompt which inturn uses nunit and gives the results. I want to schedule it nightly so that it automatically runs the msbuild and get the results. Is there any way I can do that?
Comment: Using batch files - but if you have access to a Team Foundation Server look into its building capabilities, they do what you want and much more.
Comment: right now i am not allowed to use TFS. Is there any other way to do this.
Answer: I would recommend using a Continuous integration server for this. You can set up your continuous integration server to schedule builds and a number of other tasks. Personally, I use Team City from Jetbrains, but there are other options available, such as Cruise Control.net and Hudson.
What exactly do you want to do with the results? If you just need to run your build script, a simple scheduled task should do it.
Comment: i want to have the results of the test to have it an xml and i need to pull out the xml data.
Comment: Xml test reporting is bundled with Team City as of 4.5, i'm not sure about CC and Hudson.
Answer: The way my company solved the problem was to use Powershell. We have a scheduled task that executes a powershell script that completely automates the process using MSBuild and devenv.exe.
We've been able to do away with the expense of many other continuous integration tools with this process. We have even connected it to our svn server so that it can checkout the latest revision, build it, send out an email if there was a build error and send the output of the screen as a result log.
I realize this might not be simple answer you're looking for, but Powershell was really easy for me to learn, exceedingly customizable, and very powerful. I had doubts when my Director said we were moving this way, but it's been a delight.

Scheduling msbuild task build Nightly


Dimension of $End(V)$ with $V$ countable dimension irreducible module over a complex algebra

Question: Let $A$ be a $\mathbb{C}$-algebra and $V$ be an irreducible $A$-module with countable dimension. What is the dimension of $End(V)$ as $A$-module? Note that every endomorphism must be injective and surjective, because of the irreducibility of $V$. My claim (or at least my hope) is that $End(V)$ has countable dimension, but I can't see a proof of this fact.
Comment: What is "dimension" "as $A$-module"? Also, what is "countable" - infinite or not necessarily?
Comment: How is $End(V)$ an $A$-module?
Comment: Without loss of generality you can assume $V$ is a faithful $A$ module and think about right primitive rings and apply the Jacobson density theorem.
Comment: I made some mistakes I've just edited; however I mean irreducible module, that is a module with no bilateral submodules except himself and $(0)$.
Comment: It is much clearer now, thanks for the edits.
Comment: Can you please explain the proof with more details in an answer? Thank you very much.
Comment: Every $R$ module $M$ is a faithful $R/Ann(M)$ module: it's a good exercise.
Comment: Ok, but even assuming that I can't see the way to conclude.
Comment: I didn't say that it gives you your answer, I just meant you could reduce the problem to something with a good structure theorem.
Comment: A good question @Dap. When composing my answer I assumed "countably infinite" for some reason :-). Deleting the misguided answer.
Comment: Well, for countable finite my claim is true and the proof is not difficult; for infinite I'm in trouble. Dimension is the largest cardinality of a set of linearly indipendent elements over A.
Comment: What does it mean by $\operatorname{End}V$?  Is it $\operatorname{End}_\Bbb{C}V$ or is it $\operatorname{End}_AV$?
Answer: I have tried to interpret the question as asking about dimension over $\mathbb{C}$ , as it is not clear what $A$-module structure $End_A(V)$ has.
If $V$ is a left $A$-module which is irreducible in the sense that it has no proper nontrivial left $A$-modules, then $\dim_{\mathbb{C}} End_A(V) \leq \dim_{\mathbb C} V$. For if $v \in V \setminus \{0\}$, then $V = Av$, and thus the $\mathbb{C}$-linear map
\begin{align*} End_A(V) &\to V  \\ \varphi &\mapsto \varphi(v) \end{align*}
is injective.
Schur's Lemma tells us that every nonzero endomorphism in $End_A(V)$ is in fact invertible, that is, that $End_A(V)$ is a division algebra over $\mathbb{C}$ of countable dimension. While it is well known that the only finite-dimensional division algebra over $\mathbb{C}$ is $\mathbb{C}$ itself, the same result is true of division algebras $D$ of countable dimension, as can be seen by examining for $a \in D \setminus \mathbb{C}$ the set $\{z \in \mathbb{C}: a - z \text{ is not invertible}\}$.


Why is real exponentiation continuous in the base?

Question: I know that real exponentiation is continuous in the exponent ($f(x)=a^x$ is continuous), but how do we know real exponentation is continuous in the base?
What I mean is, if $r$ is an arbitrary real number, why is the function $f(x):(0,\infty)\to\mathbb{R}$ given by $f(x)=x^r$ continuous? I define
$$
x^r=\lim_{n\to\infty} x^{q_n}
$$
where $(q_n)$ is any sequence of rationals converging to $r$.
I noticed that $\lim_{x\to 1}x^n=1$ for any integer $n$, by repeated use of the fact that the limit of a product of continuous functions is the product of the limit of each function. If $n$ is negative, the same thing follows by taking the limit of $1/x^{-n}$.
If $r$ is real, there exists integers $n,m$ such that $n\leq r\leq m$. By the Squeeze Lemma,
$$
1=\lim_{x\to 1}x^n\leq\lim_{x\to 1}x^r\leq\lim_{x\to 1}x^m=1.
$$
So I think $\lim_{x\to 1}x^r=1$ for any real number $r$. Can this be manipulated to show $f$ is continuous on all of $(0,\infty)$?
Please assume I don't know any calculus or about $e$ or logarithms, only rudimentary results of limits in analysis. I'm trying to avoid anything like "since $x^r$ is differentiable, it is continuous, QED." Thank you.
Comment: $a^x=\exp(x\ln a)$. How do you define $a^x$?
Comment: How are you defining $x^r$?
Comment: @julien You might even say $a^x:=\exp(x\ln a)$.
Comment: @AndresCaicedo I've now included my definition of exponentiation.
Answer: If (by whatever definition of $a^b$ you have, provided it gives you the usual laws) you know $\lim_{x\to 1} x^b=1$ then $$\lim_{x\to a} x^b=\lim_{x\to 1} (ax)^b=\lim_{x\to 1} a^bx^b=a^b\lim_{x\to 1} x^b=a^b.$$
Comment: Thanks Hagen von Eitzen, I hadn't thought to change limits like that.


Drupal 7 Views Change the Query String

Question: I have a complex View that needs to utilize multiple contextual filters. Currently to access the filters I need to separate the values with a "/". I'm attempting to code a solution that passes arguments to a View (via URL) and it would be ideal to have the query string look like this:
http://www.example.com/query?nid=1450&tid=543
vs (the current way)
http://www.example.com/query/1450/543
so that I can better parse this. How can I get a View to accept parameters like this?
Comment: Interesting, usually all requests of this sort are to do exactly the opposite (i.e. convert _to_ clean URLs, not away from them). Not questioning your decisions, but is there a technical reason you'd want to do this? If the page is a Views page I wonder why you need to parse the parameters, when Views already does that for you
Comment: In my case the parameters need to be shared with an external system. Would there be a better way for me to parse the parameters than parse_url?
Answer: What you're actually saying is that you don't want contextual filters, contextual means that you want an argument based on the context of the site which is usually separated out by the url.
The quickest way to do what you want is this.

move your contextual filters into the filters section of views,
making sure that you expose them to visitors.
Under the more setting of each filter is where you set the filter
identifier and change the advanced options to label the filter as you
require such as "nid" then your url would be
mywebsite.com/page?nid=xxx
Then under the exposed form settings, change the setting to "expose
form as block" to yes to make the exposed filters disappear.
Comment: Sometimes the easiest solutions are the correct ones! Thanks!
Answer: You need the module Views Contextual Filter Query.
From the module page:

Allows url query values to be used as contextual filter arguments.
  This module is an answer to the many stackoverflow topics where the
  solution is to fetch query parameters by using the default PHP
  argument filter in Views (yucks!).

Drupal 7 Views Change the Query String


R multilevel analysis: my sample size (gender) is unequal

Question: i'm currently working on a mutlilevel anaylsis for my assignment. I am new to R and hope that someone can help me out. I did a survey to collect the data I need. I have 184 participants, where approximately 59 are men and 125 women. It has to be a multilevel analysis because its a diary study (it happens that one ID appears 5times for 5 Days).
I tested some models and the results are always show that women are more emotional than men. So my question is; is that because I have more women in my survey than men, or does R weight them on his own without me having to do anything?
I think the problem is not that the classes are imbalanced per se, its more that there may not be sufficient patterns belonging to the minority class to adequately represent its distribution....
Do unequal sample sizes play a role for multilevel analysis? If so, can anybody help me out with this problem?
Comment: In addition to Peter Flom's answer, I might add that might want to look into the concept of least-squared means, which are treatment "means" adjusted for the effect of other terms in the model.  These are useful to look at or report when observations are unbalanced.  I don't know if they will be useful in your case. A simple example is here: [Webpage](http://rcompanion.org/handbook/G_05.html).  R has a package `lsmeans` but you will need to check to see if the package will handle well the model you are using.
Answer: Multilevel models (like regression models) can deal appropriately with unequal sample sizes. It is very common that the independent variables are not evenly distributed.
I don't know what

I think the problem is not that the classes are imbalanced per se, its
  more that there may not be sufficient patterns belonging to the
  minority class to adequately represent its distribution....

means.
Comment: I think that the answer to the second problem is that anything which relies on the main effect of sex and its interaction with time (which i suspect is what is meant here by pattern) is going to be imprecisely estimated as the number f men goes down.
Comment: yes. How can I tell R that the gender variable is imbalanced (more men than women) or does R know that?
Comment: R knows.  You don't have to explicitly tell it.


What is Swift.AnyClass?

Question: I was looking into UITableView class and I found:
open func register(_ cellClass: Swift.AnyClass?, forCellReuseIdentifier identifier: String)

Reading here I know AnyClass is actualy a typealias.
typealias AnyClass = AnyObject.Type

What I don't understand is what is: Swift.AnyClass What does the Swift do?
I already know that the parameter it takes is something like CustomTableViewCell.self
Comment: See [Swift's standard library and name collision](http://stackoverflow.com/q/25231650/2976878) – the `Swift.` prefix means you're referring to something in the `Swift` module. This isn't explicitly needed though (unless in order to disambiguate) as Swift has implicit top-level namespacing.
Comment: I'm gonna take a stab that it's a superclass to all other classes. Something of type `AnyClass` can be of any type. The `Swift` part is probably a namespace for language related stuff.
Comment: @Carcigenicate *The Swift part is probably a namespace for language related stuff* <--Contrast as into what? Contrast to what other syntax?
Comment: Contrasted to often used classes/aliases. They probably figured most people won't be using `AnyType` very often, so it wasn't worth including it in the global namespace.
Comment: @Hamish Thanks...So does this mean there was a namespace conflict somewhere and Apple had to use this? Also see [how to use namespaces in Swift](http://stackoverflow.com/questions/24002821/how-to-use-namespaces-in-swift/24293236#24293236)
Comment: @Honey It's most likely just to be how the Swift header for `UITableView` is auto-generated.
Answer: Some more information to add on to the accepted answer:
First of all Swift.AnyClass is type alias for AnyObject.Type. That means that it's a metatype which can hold any 'classtype', therefore the name AnyClass in first place.
class A {}
class B {}

var anyClass: AnyClass? = nil /* could be ': AnyObject.Type' */
anyClass = A.self
anyClass = B.self

var anyInstanceOfAClass: AnyObject? = nil
anyInstanceOfAClass = A()
anyInstanceOfAClass = B()

Swift is the actual module name for the standard library. You can use it yourself if you need a way to disambiguate things. For Instance you can do something like this:
struct Array<T> {
   private var array: Swift.Array<T> { ... }
}

Answer: Just to clear this out, as someone already said, Swift is the name of the virtual module for the runtime, every object, type and builtin defined in the language will also be accessible from this namespace.
In this case, why the type is declared as Swift.AnyClass instead of simply AnyClass?
I don't think that it was required to avoid name-clashing with some type defined in UITableView scope this time. This could be related to the fact that UIKit is still written in Objective-C.
They likely implemented a "workaround" to use the better-looking AnyClass type in that function prototype, that being defined in the Swift runtime would not normally be available in Objective-C as a global typedef.
My guess is that they manually imported the Swift module (or a smaller mockup module with just a few definitions) in UIKit and what you see there is the result of that.

What is Swift.AnyClass?


How to find and remove the string from string using ruby?

Question: I want to find & remove a string from string. See the examples below,
Input1:

a = 'mangalore'

Input2

b = 'mc'

Outputs
b values should not present in a for output1 #angalore
a values should not present in b for output2 #c
Solutions: converting string a,b to array then doing a-b & b-a
it will give results. How to implement using string in ruby.
Helps appreciated!
Comment: _"i need to give the solutions"_ – sounds as if you are supposed to find the solution yourself.
Comment: When asked for a clarification of the question, please edit the question rather than elaborating in comments. Questions are intended to stand on their own. That is, readers should not to be expected to read all the comments to understand the question.
Comment: There is already a solution to this problem in your question. What is actually your question?
Comment: I think they're asking how to perform the subtraction without converting to an array first
Comment: yes. without array i need to give the solutions.
Comment: yes, i want the result in better way. now got it
Comment: Please read [ask]. We'd like to see your attempt to solve the problem, along with relevant input and expected output data, and any errors you're receiving. Without those it looks like you didn't try and want us to write the code for you.
Answer: Use String#tr:
main > 'mangalore'.tr 'mc', '#'
#⇒ "#angalore"
main > 'mc'.tr 'mangalore', '#'
#⇒ "#c"

Comment: @steenslag because I have carefully read the OP requirements.
Comment: Why not `delete` ?
Comment: I must be missing something.
Comment: @steenslag _"[...] for output1 `#angalore`"_ :) the code above produces the output requested.


Generating points that follow an arbitrary probability distibution function on the surface of a sphere

Question: I want to generate an array of coordinates, (x,y,z), such that they:
$\bf{1)}$ All lie on the surface of a sphere, centered on the origin.
$\bf2)$ Follow the density function $1+sin(\theta)^2$, where $\theta$ is measured from the z-axis. (i.e that the number of points per unit area, on the sphere's surface, is proportional to $1+sin(\theta)^2$.
$\bf{If}$ the input values of $\theta$ are selected uniformly over the interval $(0, \pi)$ (and a point placed at each of these theta value) then
I am aware that, because of the way that the solid angle ($d\Omega$) varies over the surface of the sphere, the density of points will naturally vary as $\frac{1}{\sin(\theta)}$.
On this page http://mathworld.wolfram.com/SpherePointPicking.html it is shown how an even distribution of points on the sphere can be reached by playing with the input values of $\theta$ (specifically if $\theta = \arccos(2v-1)$ where $v$ is uniformly distributed over the interval (0,1).
My question is how do I find the relationship between the required input values, $\theta$, and the uniform variable $v$ for an $\bf{arbitrary}$ density distribution,  in this case $1+sin(\theta)^2$  ??
Answer: I assume that the density should be uniform wrt the other angle. And that the density $1+sin(\theta)^2$ lacks the normalization factor.
Suppose we generate the points in this way: First generate ($t,z$) where $z$ follows some density $f_z(z)$ in $[-1,1]$  and $t$ is uniform in $[0,2 \pi]$. The interpret this a a cilynder and project it onto the sphere:
$$(x,y,z) = ( \sqrt{1-z^2}\cos t,\sqrt{1-z^2}\sin t,z)$$
Now, the relation between $z = \cos \theta $ and $\theta$ is:
$$ f_z(z)=\frac{f_\theta(\theta)}{|\sin(\theta))|}\bigg\rvert_{\theta = \operatorname{acos} (z)}=\alpha \frac{2-z^2}{\sqrt{1-z^2}}=\frac{2}{3\pi} \frac{2-z^2}{\sqrt{1-z^2}}$$
and
$$F_z(z)=\frac{6\operatorname{asin}(z)+2z\,\sqrt{1-{{z}^{2}}}+3{\pi} }{6{\pi} }$$
Sadly, the inverse of this cumulative distribution cannot be expressed in closed form, so the usual random generation procedure cannot be used directly...


Caching of blocks for anonymous user

Question: I have a little probleme with my cache block.
This is my build function :
return [
  '#markup' => time(),
  '#cache' => [
    'max-age' => 10
  ]
];

I found this specification for block cache.
  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 20;
  }

Because in parent class we have $max_age = Cache::PERMANENT;
So, when I'm connected my rendered cache refresh each 10 seconds.
But when I'm a anonymous user my rendered block never change.
I don't find the solution.
Big pipe isn't install, I have aggregations css and js but I don't have max age in admin/config/development/performance.
Finnaly I want a block without cache because this block will rendered message with close button. When the user click on the close button, I set a cookie for return an empty bluid in my block.
Do you have an idea ?
Thank you
Comment: In your custom block template, are you rendering the `{{ content }}` variable in full? If not, cache tags may not be bubbling up.
Comment: I havn't custom block template for moment. I rendered also #markup with #cache key
Answer: You don't have to worry about the values which are set for cache max-age in other places, because when these are merged the lower time that you have set wins.
But you can't control with max-age the page cache for anonymous users. You have to use \Drupal::service('page_cache_kill_switch')->trigger(); in the block build method to disable the page cache or you can simply uninstall the module Internal Page Cache if you plan to use the block on all pages.

but I don't have max age in admin/config/development/performance

You should set this to the same max-age to control the browser cache and proxies.
Comment: I'm convinced you're a wizard.
Comment: See https://www.drupal.org/node/2352009 for the core issue that is trying to change this.
Answer: Cache Control Override plugin intends to solve the problem with an anonymous user cache control.
After installation, both methods will work:
return array(
  '#markup' => date("Y-m-d H:i:s"),
  '#cache' => array('max-age' => 10).
);

or
public function getCacheMaxAge() {
    return 10;
}

Caching of blocks for anonymous user


Is this book excerpt an accurate statistical analysis of project risk?

Question: I found this passage on the odds of a project succeeding in a book on risk management.  I know this is open-ended, but is the author's math and logical reasoning correct here?
Answer: Problem 1: The calculation only holds if the 6 steps are stochastically independent. Otherwise, the calculation is not accurate. (I.e., all 6 events must be drawn from independent distributions.) As a result, the success probability might be much lower. E.g., suppose that success of task one induces and 80% failure of task 5 because of resource allocations that are necessary to accomplish task 1 or any other reason.
Problem 2: How can the firm be certain about the estimted confidence intervals? (I know it's kind of a stickler thing to bring up, but the book is about risk management. Why not bother with managing the risk that you carry whilst managing risks?)