Has the age at which we teach Mathematics changed over the last two centuries?

Question: My experience of learning Advanced Trigonometry and Calculus is that it was done to 17 and 18 year olds (School Curriculum in Australia). I assumed that it was similar in the UK, US and Europe.
In the book Master and Commander we see the main character Jack Albury tell of his childhood learning mathematics. It appears he learned Cotangents and Integration at age 12.
Now I'm not saying this is not possible, and that there are probably 12-year-olds out there with untapped potential. I'm trying to understand what Mathematics would have been taught at this point in time (to sailors for navigation). Is it likely that they learned a rote formula for navigation, and understanding the stresses on a ship, or would they have learned first-principles?
Now this novel is set in the period of English History [1800-1815] and is generally regarded to be meticulously researched historical fiction.
My question is: Has the age at which we teach Mathematics changed over the last two centuries?
Comment: Hello, I added the tag "soft-question" so that this nice question can more likely be prevented from being closed or anything else we do not want to see. :)
Comment: I am no expert, but I feel like an increasingly common facet of modern education (at least in America and the UK) is an increasing element of standardization. I have no clue if this existed in the 1800's, but I doubt it. It seems likely that in that period it was more acceptable to start learning at various ages and learn at different rates than it was today. I'll let someone more knowledgeable of the history answer the question  properly though.
Comment: i think that now we learn these things much more earlier than we used to do
Comment: The emergence of personal computers and internet may play a non-negligible role; knowledge disseminated much more faster than ever for both scholars and students. Another reason I think about is that, because some mathematics have finally been understood thoroughly so that the great masters can make those math. easy such that they can be "explained" to the first person one meets on the street.
Comment: @hawkeye It's true that many fields have their students study certain topics much later (and sometimes much longer) than their ancestors did. Some classic scientists, physicians, and lawyers of high acclaim were in their late teens and early twenties during their practice. Consider also that there has been a significant increase in the amount of things we know about the world between now and then. I'd say, though, that this point has a lot more to do with university studies than secondary schools. I feel that the secondary school system is very flawed in their methodology of teaching maths.
Comment: The failure of the education movement in the 1960s to 'modernise' the maths taught in schools (SMP/Nuffield in the UK, New Maths in the US, the Lichnerowicz Commission in France) suggests that you need quite a bit of time between the discovery of new mathematics and it's introduction into schools. Interestingly the topics that stayed from SMP (like co-ordinate geometry) are the more established ones. I'm surprised that calculus hadn't entered the curriculum earlier as the method of exhaustion has been around for a long time.
Comment: What you are still taught around age 12 or earlier these days is basic physics, for which Calculus was invented and applied to understand better. So you get to learn acceleration and velocity without learning how it was these things came to be understood until much later.
Answer: Well It depends on what you think about mathematics. Generally, Through history we all learn mathematics from a very young age because We learn counting.
Now Isaac newton didn't learn calculus in University because he is the one who came up with calculus in the first place and therefore, Nowadays, The mathematical curriculum for university involves way more advanced mathematics compared to 100 years back. Now we have graph theory , combinatorics , Modern Algebra , Number theory and topology. This is way more math than they did 100 years ago, I would say even Einstein didn't do a lot of math compared to People doing research now.
In the future, I think people will learn more about modular arithmetic and number theory earlier than they do nowadays.


Parent and Child

Question: I'm trying to solve a particular business question and I'm not sure how it translates into drupal sematics, so please excuse me if this has been asked before.
I want to use a series of content types to capture user feedback on different engineering aspects of a project: the structure is pretty much
-> project
--> milestone
---> current technology set used
---> precieved highest risks
because the cardinality of the children is always >1, I think I need to use a separate content type for each.
Can anyone tell me how I add links to create a child object when viewing the parent, ie. create a new milestone for this project....  I can't seem to find a starting point in the documentation.
Answer: You can try one of these modules

References
Relation

Relations are entities and can therefore have fields. This makes
  Relation the most flexible and powerful relation model out there.

Entity reference

Provides a field type that can reference arbitrary entities:

If youre looking for some Project management tools try these
Project Management
Open Atrium

Parent and Child


Dúvida no funcionamento do Migration automático com MigrateDatabaseToLatestVersion

Question: Com migration automático o banco de dados é atualizado também quando houver exclusão de alguma propriedade da minha classe modelo? Ou seja, além de ele incluir um novo atributo se for acrescentado algo a minha classe, ele também remove? Como o exemplo abaixo, estou tentando fazer com que ele remova o campo CEP que foi acrescentando e está vazio, mas isso não está acontecendo. Retorna uma exceção AutomaticDataLossException
Início
static void Main(string[] args)
{
    Aluno aluno = new Aluno
    {
        AlunoId = 1,
        Nome = "Cláudia",
        Email = "email@example.com"
    };

    using (var db = new DBContexto())
    {
        db.Aluno.Add(aluno);
        db.SaveChanges();
    }
}

Model Class
public class Aluno
{
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
    //public string Cep { get; set; }
}

Contexto
public class DBContexto : DbContext
{
    public DBContexto()
        : base(@"data source=(local); initial catalog=DbAluno; integrated security=true;")
    {
        Database.SetInitializer<DBContexto>(new MigrateDatabaseToLatestVersion<DBContexto, Configuration>());
    }
    public DbSet<Aluno> Aluno { get; set; }
}

Configuration
public class Configuration : DbMigrationsConfiguration<ConsoleApplication1.DBContexto>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(ConsoleApplication1.DBContexto context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

Answer:
Com migration automático o banco de dados é atualizado também quando houver exclusão de alguma propriedade da minha classe modelo? Ou seja, além de ele incluir um novo atributo se for acrescentado algo a minha classe, ele também remove?

Sim. A coluna é excluída.

Como o exemplo abaixo, estou tentando fazer com que ele remova o campo CEP que foi acrescentando e está vazio, mas isso não está acontecendo. Retorna uma exceção AutomaticDataLossException.

Sim, isto é uma proteção do Entity Framework para que dados importantes não sejam perdidos. É ligado por padrão.
Como você está num ambiente de desenvolvimento, pode incluir o seguinte na configuração de Migrations para evitar essa verificação:
internal sealed class Configuration : DbMigrationsConfiguration<MeuProjetoContext>
{
    public Configuration()
    {
        AutomaticMigrationDataLossAllowed = true;
    }

    ...
}

Comment: Deu certo. Obrigada!


How do you determine intervals? Is it based on major and minor keys?

Question: If we say C to E, we say it's a major third since it is belongs to the major scale. If we say C to E♭, we say it's a minor third since it belongs to a minor scale.
What about C to D, F, or G? These intervals are same both in major and minor scales. Do you consider the bass note as the basis for the major scale?  (So here we'd consider it C major.)
Comment: No, a major third is 4 semitones, and a minor third is 3 semitones. This has nothing to do with major and minor scales. The other intervals are defined the same way.
Comment: @alephzero - you only told part of the story. Yes, a major third *is* 4 semitones, but also so is a diminished 4th. A minor third *is* 3 semitones, but also so is an augmented second. Being an interval of x semitones *doesn't* mean we know what interval it is. Every gap od x semitones has two different names - so using 'how many semitones' isn't going to tell us what ant interval is.
Comment: Welcome to Music.SE! I'm having trouble understanding your question. You've asked why I would consider a bass note to be a major scale. I don't consider a single bass note to be a major scale. A major scale is (by definition) a particular *collection* of many notes. If given a C scale and the notes C, D, F, and G, we cannot identify this as a C major scale or a C minor scale. More information would be needed.
Comment: Also, it sounds to me like you're suggesting the following: a C **minor** scale contains an Eb *because* the interval from a C to an Eb is a **minor** third.* That's incorrect reasoning. Every diatonic scale contains two notes that are separated by a minor third and two notes that are separated by a major third. The key fact when defining a minor scale is that the third degree of the scale is flat.
Comment: The interval names are not necessarily based on the scale names. E to G is a minor third even though it's part of the C major scale. It's also part of the A minor, G major, E minor, and other scales. It's always a minor third no matter what scale is being used.
Comment: When you say 'bass note' do you actually mean the lower, or root, note?  As in 'does the lower note get considered as the root note of a scale, and we try to find the upper note in that scale in order to work out its interval'?
Comment: @jdjazz - re. your second comment: diatonic here means only the major and natural minor heptonic scales, I guess. If the OP tries to reason using the other minors, it'll be confusing! Also see my last comment re. translating the question.
Comment: @Tim, I was referring to the modes to illustrate a larger point: the presence of a major third interval within a scale does not immediately qualify the scale as a major scale. I was trying to illustrate that flaw in reasoning, and one counterexample (natural minor scale) is sufficient for that purpose. The other modes provide additional counterexamples. (E.g., "B locrian contains a major third interval but is not a major scale.")
Answer: The word "minor" does not mean the same thing when used to refer to scales and intervals.
A minor interval is a 2nd, 3rd, 6th, or 7th in which the upper note is one semitone lower than its major equivalent. It does not necessarily mean it is part of the minor scale.
In your example of C to Eb, the interval is minor not because Eb is part of the C minor scale, but because Eb is one semitone lower than the major equivalent E.
When finding interval quality, you use the bass note as the root of the major scale, and find what note the top note would be in that scale. Then you find how many semitones lower or higher it is to find its quality. You always find the difference from the major scale.
Comment: Sometimes the quality is from semitones *higher* than the major note. Think augmented.
Answer: You're confused - and rightly so! It would appear that your assumption is correct, in that C>E is a maj3, found in a major scale, and C>Eb is min3, found in a minor scale. It just happens that way. 2nds, 3rds, 6ths and 7ths all have 4 different flavours. dim., min., maj., and aug. The 4ths and 5ths have 3 flavours, dim., perfect and aug.
A second, C>D is called a maj.2, a third, C>E is a maj.3rd. make those intervals smaller by a semitone, they're minor, smaller by a tone and they're diminished. Make the major interval bigger by a semitone, it's augmented.
The 5ths can only be a semitone smaller (dim.) or a semitone bigger (aug.)
Intervals are found initially by the name of the two notes, counting from the lower. Thus - C>E=maj3; C>Eb=min3; C>Ebb=dim3; C>E#=aug3. Finally, if you take C>F, it's a perfect 4, but if that F note is actually technically E#, then the interval is aug3, not P4. So, we don't, and can't, use no. of semitones as an absolute criterion.
...And another thing! Intervals couldn't be realated to scale notes per se. There are three minor scales, so for instance, the 'seventh' in the natural minor is m7, while the 'seventh' in harmonic is major 7. How could those facts relate to whether a scale is major or minor...
And yet another! To help understand intervals, try inverting them. Majors become minors, and vice versa, while augs become dims, and vice versa. Perfects stay perfect. The 'rule of 9' applies. So, inverse of m3 = M6. inverse of M7 is m2. Inverse of P5 =P4. Give it a try, it may help make sense, where logic sometimes isn't the best.
Answer: First, I will answer the question in your title: can you find an interval and define it [based on the scale in which the interval occurs]? The answer is definitively "no." The names of intervals do not always match the names of the scale in which those intervals occur.
To illustrate this, let's compare a few different C scales:
C Lydian:         C  D  E  F# G  A  B
                  1  2  3  #4 5  6  7

C major:          C  D  E  F  G  A  B
                  1  2  3  4  5  6  7

C Mixolydian:     C  D  E  F  G  A  Bb
                  1  2  3  4  5  6  b7

C Dorian minor:   C  D  Eb F  G  A  Bb
                  1  2  b3 4  5  6  b7

C natural minor:  C  D  Eb F  G  Ab Bb
                  1  2  b3 4  5  b6 b7

C Phrygian:       C  Db Eb F  G  Ab Bb
                  1  b2 b3 4  5  b6 b7

C Locrian:        C  Db Eb F  Gb Ab Bb
                  1  b2 b3 4  b5 b6 b7

C harmonic minor: C  D  Eb F  G  Ab B
                  1  2  b3 4  5  b6 7

C melodic minor:  C  D  Eb F  G  A  B
                  1  2  b3 4  5  6  7

These are just some of the scales we could write down. When we consider all of these different scales, something becomes clear: it doesn't make sense to define an interval based on the scale in which the interval is found, because there's simply too much overlap. We cannot require a minor scale to contain only minor or diminished intervals--this would produce an altogether different scale from what we know as minor. Indeed, this overlap is easy to see. For example, a major second interval (C to D) is found in all of these scales: major scale, minor scale (all three types), Lydian scale, and Mixolydian scale. We don't call this a "Lydian second" or a "Mixolydian second." We simply call it a major second (as opposed to giving it multiple different names).
You might be wondering "what is the convention for naming intervals?" This would be a different answer altogether and might be worth asking in a separate question.
Answer: You've got it half right!  Yes, the major and perfect intervals may be defined as the notes of the major scale that starts on the lower note. But we can't be as glib about minor intervals.
Forget about minor scales for now.  We name intervals according to their relationship to the notes in the major scale starting on the lower note.
One basic concept.  Semitone (or Fret) counting won't do.  This is part of the language of notation and harmony and, in a language, spelling matters!
Another basic concept, KNOW YOUR MAJOR SCALES.
Consider the major scale starting on the lower note of the interval:
Is the upper note in the scale?  If so, the interval is called Major (for 2nds, 3rds, 6ths and 7ths) or Perfect (for 4th's, 5ths and Octaves/Unisons).
Is it one semitone up from there?  It's called Augmented.
One semitone down?  If it's one of the 'major' bunch it's called Minor.  If it's from the Perfect bunch it's called Diminished.
Two semitones down?  There's a step below Minor called Diminished.  Nothing for 4ths 5ths and Octaves/Unisons.  They go straight from Perfect to Diminished. There's no special name for the interval two semitones smaller than a Perfect 4th, 5th or Octave. (Well, none that's of any practical use.  I suppose you could invent something like 'double-diminished.)
THE SPELLING MATTERS.  The note 3 semitones higher than C might be spelled Eb, it might be spelled D#.  The former is a Minor 3rd above C, the latter am Augmented 2nd.
And that's about it.
Answer: In a broader musical context, minor and Major can mean different things. When we speak of scales we can say a Major or minor scale. When we speak of chords we have a Major chord which is a set of notes a Major Third and a perfect fifth from the root note.
In this case, we have to do with intervals. A Major interval is a space between two notes where both notes fit in the Major scale of the root. C - E is a Major third because C major has an E natural for the third note of the scale.
This is just the short hand for how we teach people to get to the interval. This does not mean that this interval has all that much to do with the scale we are in.
C-E remains a Major third regardless of the scale. It is the interval in C Major, it is the interval in F Major and the interval in G Major. You could say that the intervals are key agnostic.
Comment: You can say 'key agnostic', but for beginners, it's probably easier to assume the lower note is the root from its key, and calculate the interval to the upper note using that as a datum point. As it happens, M2, M3, M6 and M7 *are* all part of a major scale based on its root note.
Comment: Yeah but C to E is still a Major Third even in a minor.
Comment: The point is missed. For beginners, using C as the 'key root' note, makes C>E= M3, especially if they think in key C. There's little point in thinking C>E in the key of Am, Em, Dm, F, G, how would that help anyone, let alone a greenhorn?
Answer:
...is it based on major and minor keys?

No. To clear up this part of the question consider this. C and E also belong to A minor, but we don't call the interval a major third.

If we say C to E♭, we say it's a minor third since it belongs to a
  minor scale.

No. You could also say C and Eb also belong the B flat major, but we don't call the interval a major third.
How do we do it?
We don't get the interval name by its relation to a scale, key, or chord. Instead, we get the interval only by comparing the two notes in a a two step process.
First the interval is measured in steps of the staff letters A to G. In this example C is one (or a unison), D is the second, and E is the third. Our basic interval is a third.
Next we determine the quality of the interval by measuring in semitones. Thirds that are 4 semitones apart are major thirds. C natural to E natural is 4 semitones apart and so is a major third. C to Eb is 3 semitones apart and so is a minor third.
Wikipedia has a good, full description in its article on intervals.
Correct interval naming really involves reading from a score or understanding conventions about key signatures and harmony. It can also be confusing when dealing with enharmonic equivalents. Be prepared to grapple with those issues if you dig in deeper.
Answer: You are confusing the concept of scale qualities and intervals.
C to E is not called a major third because it is from the major scale. By definition a major third is 4 half steps from any note to any note regardless of scale.
In E minor there is a major third between C and E even though it belongs to the minor scale... in fact a C major chord C E G belongs to F major, C  major, G major, D minor, A minor and E minor.
To answer your question:
C to D is a Major 2nd
C to F is a Perfect 4th
C to G is a Perfect 5th
C to A is a Major 6th
C to B is a Major 7th
So you're wondering why you see no minor intervals in the major scale? You do.
E to G - minor third... or how about A to C... D to F... all minor thirds. Just depends what note you start from.
Let's breakdown all the intervals
NOTE: a semi-tone is the same as half-step)
Credit goes to westrowanmusictheory.weebly.com for this picture
Comment: That thing is all sorts of wrong. You cannot do intervals just by counting semitones. C-C# is an augmented unison, C-D# is an augmented second, C-G# is an augmented fifth and C-A# is an augmented sixth, enharmonic equivalents change the interval.
Comment: I must agree with @NeilMeyer, this chart is a problem. C-D# is not a minor third. It's an augmented second. This chart will add to the OP's confusion.
Comment: I can't credit Guitar Player world with this - it's inaccurate.C>C#, C>D#, C>G#, C>A# all wrong. So many guitar sites seem to eschew the fact that flats exist for guitarists. haven't worked out why yet, but that got you a downvote.
Comment: @NeilMeyer That's an issue of spelling. I'll try to add something explaining that, but I think that is mostly going to confuse him.


Emacs find-file-other-window command splits buffer vertically

Question: I am just setting up Emacs on a new machine and I am running into trouble with the command find-file-other-window. The way I typically like to work is with the frame split horizontally into two windows. I'd like to be able to run said command and have it open the file in the other window, but instead most of the time it splits the current window into 2 new windows horizontally. How do I get it to stop doing this? Thanks.
EDIT: Also want to point out that this only happens when I scale the frame to a large enough size.
Comment: can't replicate. `Mx-find-file-other-window` opens a file in a new window if there's ony one, In the adjacent window if there are two or more. It doesn't split into a new window. What system and version are you using?
Comment: In the window where you wanted the file/buffer displayed, but it didn't happen there, you may want to try evaluating `(window-dedicated-p)` to see if it is dedicated.  If it is dedicated, then display-buffer family of functions will try to preserve that dedication.  After doing all that, you can make a decision whether to prevent that window from being dedicated in the future or look for ways to override the dedication.
Comment: @manandearth Emacs 26.1, High Sierra.
Answer: Normally this action is performed by the function
split-window-sensibly, and controlled by two variables,
split-height-threshold and split-width-threshold. Per the
documentation

If 'split-height-threshold' specifies an integer, WINDOW is at least
  'split-height-threshold' lines tall and can be split vertically, split
  WINDOW into two windows one above the other and return the lower
  window.  Otherwise, if 'split-width-threshold' specifies an integer,
  WINDOW is at least 'split-width-threshold' columns wide and can be
  split horizontally, split WINDOW into two windows side by side and
  return the window on the right.  If this can't be done either and
  WINDOW is the only window on its frame, try to split WINDOW vertically
  disregarding any value specified by 'split-height-threshold'.  If that
  succeeds, return the lower window.  Return nil otherwise.

On my system the default value for split-height-threshold is 80 and split-width-threshold is 160. I think you could get the effect you want by setting split-width-threshold to something lower. Alternatively you could set split-height-threshold to nil, preventing it from ever splitting vertically, or set the variable split-window-preferred-function to a different function. Any of these would affect, not just find-file-in-other-window, but all the functions that split the screen.


how to parse some mails from html code

Question: I want to build a little bash script to detect some mails in a HTML-code.
currently, I am not sure how can I build the right regex to auto-detect emails from HTML.
I tried this regex with curl:
egrep -o "\S*@.*\.\S*"

But this includes all non-alpha characters until the first space.
For a little example:

Email
<a href="mailto:email@example.com" style="color: rgb(255, 255, 255);"

Now I want to auto-detect only this part: email@example.com
Does somebody have any idea?
cheers
Answer: When you just want to get whatever comes between the "mailto: and the ", then this would do the trick:
grep -oP '(?<="mailto:)[^"]+(?=")'

It uses positive lookbehind and positive lookahead which is supported by the Perl regex syntax (-P flag).
If you need additional validation of the address, you might want to look into expressions like the ones discussed here: https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression
UPDATE:
If you don't want to fall back to overly complex expressions, this should do the job:
grep -oP $'[^\'",<>:\\s]+@[^\'",<>:\\s]+'

You can easily add additional delimiting characters within the square brackets.
UPDATE 2:
If you also want to match something like this: regex @ example.com
grep -oP $'[^\'",<>:\\s]+\\s*@\\s*[^\'",<>:\\s]+'

Comment: thanks. the line above firstname.lastname@example.com< style="color: rgb(255, 255, 255);"

i think i need a regex that include all alpha characters until the first non-alpha like "<,>,;," etc."

because the developer places the mail between different symbolic.
Comment: Ah, I see. I updated my answer with a more robust version that should handle most cases.
Comment: Many thanks. It works out. I've added the symbol ";"

grep -oP $'[^\'";,<>:\\s]+@[^\'",<>:\\s]+'

how to parse some mails from html code


Hazard ratio with time-varying covariates

Question: I am confused about time-varying covariates in Cox models. I believe this refers to the fact that in the normal situation, you can calculate a hazard ratio for $X$, assuming $X$ for an individual is not going to change over time. But with time varying covariates you can also take into account that $X$ may change over time.
I don't understand how you interpret hazard ratios in that case. Do you still interpret this as "An individual A with $X=2$ has 4 times the hazard of an individual B with $X=1$", but knowing that later on those individuals will have changes in $X$? What if individual B has $X=2$ at the next time point and individual $A$ has $X=1$? It seems that you can't make an overall statement about the hazard of one person vs another, but rather just at one time point.
Answer: Fitting a Cox model only uses covariate values that are in place at the event time being evaluated as the modeling proceeds from event time to event time. With time-varying covariates, values prior to the event time being evaluated don't matter any more. Values after the event time being evaluated obviously can't enter into the model without violating causality.
Thus you can say things like "An individual A with $X=2$ has 4 times the hazard of an individual B with $X=1$" at any specific time. You are correct that "you can't make an overall statement about the hazard of one person vs another," just about the hazards associated with sets of covariate values.
Under the proportional hazards assumption, those relative hazards between sets of covariate values hold over all time. But if individuals' covariate values change over time you can't translate that into hazards between individuals.


SQLServer em repositórios

Question: Tenho que enviar um projeto de uma aplicação por um repositório GitHub, consegui fazer a aplicação funcionar perfeitamente front-End, Back-End e o banco de dados LOCAL, minha duvida é:
Tem como exportar o SQLServer para um repositório? Ou terei que colocar ele em algum servidor para a aplicação só ser baixada e executada?
Comment: Você quer enviar o banco? Por que não enviar as suas estruturas (tabelas e _views_) e programação (gatilhos, funções e procedimentos)? Ou você quer enviar dados também? O melhor dos mundos é você, para esse tipo de distribuição e manutenção, ter os scripts sql de criação dos objetos e de inserção dos dados no projeto
Comment: Gostaria que quem baixe-se minha aplicação só executasse a solução e pronto, no momento se eu executá-la em outro computador ela roda mas sem fazer os GET, POST, etc no SQLServer.
Comment: E acabei não respondendo a pergunta... Gostaria que já fosse uns dados sim, mas não é algo tão fundamental. Vou dar uma pesquisada sobre scripts SQL, se você tiver alguma documentação ficarei agradecido.
Answer: Tem várias formas, depende da forma como você está trabalhando.
Quando trabalha-se com Code First + Migrations seu banco de dados vai ser criado automaticamente, o migrations gera os scripts e controla as versões do banco de dados.
Acredito que você não esteja usando os recursos citados acima, mas fica a dica pros próximos projetos :)
Pro seu projeto atual, a melhor forma é gerar os scripts e fazer esse controle de criação manualmente.
Pra gerar os scripts no SQL Server Management Studio clique com o botão direito no banco de dados > Tarefas > Gerar Scripts, selecione todas as tabelas e o local pra exportação.
Após isso, coloca esse script numa classe do seu projeto e quando iniciar sua conexão com o banco faça uma verificação ou um tratamento de exceção pra validar se o banco não existe (cada modelo de connectionstring pede uma abordagem diferente, se tiver o nome do banco na sua connectionstring vai ter que tratar a exceção), então se não existir o banco de dados, roda o script de criação do banco de dados.
Crie também uma classe com os scripts de inserção pra rodar logo após a criação do banco de dados.
Comment: Sobre colocar o script em classes, eu não sou favorável. Prefiro deixar em um _asset_ separado, mas creio que isso dependa do gosto de cada um.

SQLServer em repositórios


unable to load template in python

Question: Flask is giving template not found exception on render_template() method

.
routes.py
from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', title='Home', user='user')
    # return render_template('index.html')

index.html

        <title>{{ title }} </title>

Hello, {{ user }}!

init.py
from flask import Flask
app=Flask(__name__)
from app import routes

bot.py
from app import app

error log I am getting
[2018-10-11 15:00:25,349] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "D:\Bot\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Bot\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\Bot\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Bot\venv\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "D:\Bot\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Bot\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\Bot\app\routes.py", line 8, in index
    return render_template('index.html')
  File "D:\Bot\venv\lib\site-packages\flask\templating.py", line 134, in render_template
    return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
  File "D:\Bot\venv\lib\site-packages\jinja2\environment.py", line 869, in get_or_select_template
    return self.get_template(template_name_or_list, parent, globals)
  File "D:\Bot\venv\lib\site-packages\jinja2\environment.py", line 830, in get_template
    return self._load_template(name, self.make_globals(globals))
  File "D:\Bot\venv\lib\site-packages\jinja2\environment.py", line 804, in _load_template
    template = self.loader.load(self, name, globals)
  File "D:\Bot\venv\lib\site-packages\jinja2\loaders.py", line 113, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "D:\Bot\venv\lib\site-packages\flask\templating.py", line 58, in get_source
    return self._get_source_fast(environment, template)
  File "D:\Bot\venv\lib\site-packages\flask\templating.py", line 86, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: index.html
127.0.0.1 - - [11/Oct/2018 15:00:25] "GET / HTTP/1.1" 500 -

I have already tried answer of this question, but still not working.
Somebody help me with this,  Thank you...
Comment: templates folder and routes.py should be in same folder. paste you templates folder in you app folder
Comment: Thanks man...! That worked. Since I am new to python, I dindn't know about such a thing. Thanks again.
Answer: you need the templates directory move to the app directory.
why?
because templates directory and the file where the app(the instance of Flask) is located in the same directory.

app = Flask(__name__)

inside the Flask, the jinja2 environment rely on the __name__ parameter to load your templates.

unable to load template in python


Difficulty understanding 3rd dimension in MATLAB 'cat' command

Question: I am reading matlab online documentation for fliplr command and there i came across a command 'cat'
It is used for concatenation.
First argument of cat command specifies dimension along which concatenation will occur. example if first argument is 1 ,matrices are concatenated along columns and if first argument is 2, matrices will be concatenated along rows. But what if first argument is 3 as in this scenario.
I am confused how it is acting as shown in current scenario in attached photo. What will be contents of A after assignment or execution of cat command? and  what is the meaning of highlighted lines? Does '3' means third dimension?If yes,how can be that possible?Will it be in form of pages with first matrix[1 2;3 4] on first page and second matrix [5 6;7 8] on second page
(Please correct me if i am wrong)
cat command query
Comment: Yes, you get a 3-dimensional array.
Comment: Hi engr! Welcome to Stack Overflow. Please don't use screenshots to include textual data. Just copy and paste it into a code block in your question. Or if you must use a screenshot, drag and drop it onto your question so it's displayed inline, instead of as a link.
Comment: @AndrewJanke ok sir,got it
Answer: Yep, it's a 3-dimensional array. Matlab supports N-dimensional arrays. See the Matlab documentation for Multidimensional Arrays.

What will be contents of A after assignment or execution of cat command?

A 3-dimensional array, with the inputs arranged in "pages" along the 3rd dimension.

what is the meaning of highlighted lines?

The array is 3-dimensional, but your computer screen is only 2-dimensional, so Matlab has to come up with some other way of displaying 3-D arrays in 2 dimensions. Here, it breaks it into the 2-D slices that are along each index of the higher dimensions.
A(:,:,1) =

  1    2
  3    4

A(:,:,2) =

The :s mean "all indexes along this dimension". The 1 in (:,:,1) means it's the first index along dimension 3. The 2 in (:,:,2) means it's the second index along dimension 3.

Does '3' means third dimension?

Yes.

If yes,how can be that possible?

You can fold however many dimensions you want into the single dimension of memory address by doing index transformations. It's an extension of how you can have a 2-D array in the first place, when they layout of computer memory is 1-dimensional. See the Matlab doco.

Will it be in form of pages with first matrix[1 2;3 4] on first page and second matrix [5 6;7 8] on second page?

Yes.


Spring Batch: Using executions.ftl for my custom controller

Question: I am working with Spring Batch, and I have added a new functionality to filter job executions. What I've done is create a new Controller:
@Slf4j
@Controller
public class FilteredJobExecutionResource {

    @Autowired
    @Qualifier("filteredJobExecutionService")
    @Getter
    @Setter
    private FilteredJobExecutionService filteredJobExecutionService;

    private TimeZone timeZone = TimeZone.getDefault();

    public FilteredJobExecutionResource() {
        super();
    }

    @RequestMapping(value = { "/jobs/executions.*/filter/{filter}" }, method = RequestMethod.GET, produces = "application/json")
    public @ModelAttribute("jobExecutions")
    Collection<JobExecutionInfo> list(ModelMap model, @PathVariable("filter") String filter,
                                      @RequestParam(defaultValue = "0") int startJobExecution,
                                      @RequestParam(defaultValue = "20") int pageSize) throws Exception {

        int total = filteredJobExecutionService.countJobExecutions(filter);
        TableUtils.addPagination(model, total, startJobExecution, pageSize, "JobExecution");

        Collection<JobExecutionInfo> result = new ArrayList<>();
        for (JobExecution jobExecution : filteredJobExecutionService.listJobExecutionsByFilter(filter, startJobExecution, pageSize)) {
            result.add(new JobExecutionInfo(jobExecution, timeZone));
        }

        return result;
    }

}

This class, is very similar to Spring Batch JobExecutionController, but adding a PathVariable, filter. The problem I am facing is that I want my controller to use the existing json/executions.ftl like JobExecutionController does, but I am getting the following error:

Could not resolve view with name 'jobs/executions.json/filter/662' in
  servlet with name 'RESTServlet'

Any idea how could I resolve this issue?
Thanks
Comment: I found a partial solution:

`

/manager/jobs/json/executions.ftl

`

But it only works for a request which filter value is 662. Any way to do it for any value?
Answer: I found a solution adding this to my application context:
<bean name="jobs/executions.json/filter" parent="standard.json">
    <property name="attributes">
        <props merge="true">
            <prop key="body">/manager/jobs/json/executions.ftl</prop>
        </props>
    </property>
</bean>

But, I had to change the @PathVariable filter to @RequestParam:
@RequestMapping(value = { "/jobs/executions.*/filter" }, method = RequestMethod.GET)
    public @ModelAttribute("jobExecutions")
    Collection<JobExecutionInfo> list(ModelMap model, @RequestParam("value") String value,@RequestParam(defaultValue = "0") int startJobExecution,@RequestParam(defaultValue = "20") int pageSize)

Any idea how to get this working setting filter as a @PathVariable?


Can't access all values of array

Question: I am getting a row from mysql into an array using node-mariasql.
When I print this array out using my Winston logger, I get this:
steamid=76561198053558238, tradePartnerId=93292510, tradeToken=T3dZTnlq, autoSendWinnings=1, profilePrivacy=0, earnings=0.00, lastKnownName=jdK jdK, avatar=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c.jpg, avatarLarge=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c_full.jpg

If I print out the value for "steamid", I get this as a return:
    76561198053558238
However, if I print out the value for "autoSendWinnnings" or "profilePrivacy", I get "undefined" as a return.
Why is that? What am I doing wrong? I don't think it is a MySQL related issue, because if I print out the whole array, I obviously get all values.
Still, I'll append the relevant code here.
statements['get_user'] = sql.prepare('SELECT * FROM `users` WHERE steamid=:steamid');
function getUser(steamid, callback) {
    sql.query(statements.get_user({ steamid: steamid }), { useArray: true }, function(err, rows) {
        if(err)
            logger.error('A MySQL error occured: ' + err);

        callback(rows);
    });
}

getUser('76561198053558238' function(user) {
    logger.debug(user); // I get the whole array here
    logger.debug(user.steamid); // I get the value for steamid here
    logger.debug(user.autoSendWinnings); // I get undefined here
});

Thanks in advance,
I hope someone can help me.
Comment: Btw providing the debug outputs would've been super.
Comment: I'd bet your `steamid` string gets converted to a number at some point and since 76561198053558238 cannot be represented exactly by a double, you get 76561198053558240. Though it'd be weird that the `logger.debug(user.steamid);` would still display the correct id, if that is the case.
Comment: Also, show us your definition for the table.
Comment: I'm gonna go out on a limb here and guess that autoSendWinnings has a spelling mistake, and profilePrivacy actually is undefined but the logger can figure that out and print it as 0 by using the object definition.
Comment: @Ilja that has got nothing to do with my actual problem, lol. There's no issue with the value of "steamid". Just that I can't get the values for some other keys...
this is the table structure: http://prntscr.com/agdnvo
Comment: @chugadie Nope, I cannot identify any spelling mistake.
Also, If I set profilePrivacy to 1, it displays it correctly in the array, so it's not actually undefined.
Comment: @LuucDev What Node SQL library are you using?
Comment: Also, will `sql.query` automatically return the row itself, if only a single row is found? `callback(rows);` seems like it'd pass a set of rows, which then would naturally not have a `.autoSendWinnings` attribute.
Comment: @Ilja if it wouldn't I shouldn't be able to get the steamid either, should I?
Comment: @LuucDev that we can't now, if we don't know the library in use and what it does. It could construct some "ResultSet" or what have you object to store results. It might then for example store used predicates in that. But that's not likely, I admit, and also `console.log(user)` would (likely) display `[object ...]` or something.
Comment: Actually: `logger.debug(user); //` **I get the whole array here** is all we need to know. an Array will not have a property autoSendWinnings. Members of said array will.
Answer: Your callback receives an Array of result rows. For reasons unknown said Array has a property steamid.
Try
getUser('76561198053558238', function(users) {
    logger.debug(users);
    logger.debug(users[0].steamid);
    logger.debug(users[0].autoSendWinnings);
});

Comment: Yeah, nevermind, that was the problem.
I thought, as long as there is only one row returned, I don't need to specify the row... Thanks :)

Can't access all values of array


how to access radio button selected value in Django

Question: I am trying to access radio button selected value in my django view but it returns on instead of selected value.
Template form
<form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data">
          {% csrf_token %}

        Select File

        <input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe">

         Enforce Timeout

             <input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds

             <input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds

             <input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds

         Select Machine:

                <input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP

                <input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7

      <button type="submit" class="btn btn-primary">Submit</button>
</form>

views.py
in my views i am using ModelForm but not in my HTML and the reason behind that is i copied and pasted the htmlcode generated by the ModelForm. Reason is because i need to collect two more items that are not in my data MODEL so that why.

def upload(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            file = request.FILES['sample']
            form = SampleForm(request.POST, request.FILES)
            if form.is_valid():
                new_sample = form.save(commit=False)
                new_sample.file_name = file.name
                new_sample.user = request.user
                print(request.POST)
                TimeOut = request.POST.get('timeoptions')
                machine = request.POST.get('machineoptions')

                print(TimeOut)
                print(machine)

                form.save()
                return redirect('reports')
            else:
                messages.info(request,'Invalid Form')
        else:
            form = SampleForm()
        if request.method == 'GET':
            return render(request, 'upload2.html', {'form': form})
    else:
        return redirect(reverse('login'))

Print output
<QueryDict: {'csrfmiddlewaretoken': ['VvAqdOp8RrpKOgwxLD2dpGartPvUrTHTg9AUbqsX6vphxdojTJqn7tsvLCkneWOm'], 'timeoptions': ['on'], 'machineoptions': ['on']}>
on
on

I am just trying to access the selected button value.
Answer: I guess this is mostly because you are enclosing the <input> tag inside the  tag.Also you must give the for attribute for and put the input element's id in the  tag
Try like this:
60 seconds
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60">

You can do this for all the radio buttons.Then in your view you can access with TimeOut = request.POST.get('timeoptions')
Comment: Hi Sammy. I am getting the word "ON". Do I access the value of the selected button?


How to make a list covariant :- scala

Question: Consider SubFoo extends Foo . I have a construct like this
trait SomeTrait
{

def someFun(a : List[Foo], ...) -> List[Foo]
.
.
.
}

Now in my code I would like to do y:List[SubFoo] = someFun(List(x),...) where x:SubFoo and y should be of type List[SubFoo]. But I get the error message expected List(SubFoo), actual: List(Foo): -
How do I do that with the following constraints:-

I don't want to add a type parameter to SomeTrait ( like SomeTrait[+A]) because SomeTrait is used widely in our codebase without passing any types.
I wouldn't like to change y:List[SubFoo] to List[Foo] . I am looking for a solution that does the required change where someFun is defined.
The most obvious : do not change someFun to someFun(a : List[SubFoo], ...) -> List[SubFoo] . Nada

Let me know if there is a solution respecting the constraints or which at-least satisfies constraint-1.
Thanks
Comment: `def someFun[T <: Foo](a: List[T]): List[T]`? Depends on what you want to do with your `someFun`.
Comment: Variance is not in your way. Lists *are* covariant. List[SubClass] is a subtype of List[SomeClass], if SubClass <: SomeClass. Your problem is that you're trying to forcefully cast a type to a more narrow type (that is, a subtype). Apple is a Fruit, but Fruit is not (necessarily) an Apple.
Answer: As mentioned in the comments, variance is not your way. Lists are covariant.
Without knowing more about your problem, it sounds like you're trying get a sublist of Some[Foo], where the sublist consists entirely of SubFoos.
So given
sealed trait Foo
case class SubFoo(baz: Int) extends Foo
case class OtherSubFoo(bam: String) extends Foo

it sounds like you would want a list of
List(SubFoo(1), SubFoo(2), OtherSubFoo("a"), SubFoo(25)): List[Foo]

to be converted to
List(SubFoo(1), SubFoo(2), SubFoo(25)): List[SubFoo]

Type signatures exist for a reason. If you're trying to convert a List[Foo] to a List[SubFoo], you need your conversion function type to reflect that. Here is something you could potentially do:
trait SomeTrait {

  def someFun(foos: List[Foo]): List[SubFoo] = {

    val listOfSubFoos = foos.map {
      case (sub: SubFoo) => Some(sub)
      case _ => None
    }

    // now you have a list of type List[Option[SubFoo]],
    // and want to flatten it to a List[SubFoo]
    listOfSubFoos.flatten
  }
}

There would be other ways to structure it, but the core idea here is that you'd need a function that reduces a List[Foo] to  a List[SubFoo]. You can't have a type List[Foo] and guarantee that every Foo is a SubFoo in the type system. If you need something like that, you'd most likely have to rethink your type hierarchy here.
Just remember the basic structure of inheritance. All SubFoos are Foos, but not all Foos are SubFoos.
Comment: `foos.collect { case sub: SubFoo => sub }`, but I seriously doubt it's what OP wants

How to make a list covariant :- scala


How do I link a JavaScript file to a HTML file?

Question: How do you properly link a JavaScript file to a HTML document?
Secondly, how do you use jQuery within a JavaScript file?
Comment: I prefer the answers here: [Where should I put
Comment: @Nathan with node.js it's a completely different story. [read this](https://stackoverflow.com/questions/10166324/how-to-include-nodejs-modules-in-html-files) hope it helps
Comment: @caramba But what if I need the JS to do something more complicated?  I'm trying to have it write a file so I call `const fs = require('fs');` from node.
Comment: I found a workaround, but I'm sure someone else will be glad for the link!
Answer: First you need to download the jQuery library from https://jquery.com/ then load the jQuery library the following way within your HTML head tags.
Then you can test whether jQuery is working by adding your jQuery code after the jQuery loading script.
<!DOCTYPE html>

If you want to use your jQuery scripts file separately, you must define the external .js file this way after the jQuery library loading.

Test in real time

<!DOCTYPE html>

Comment: Thank you SO MUCH.  This is exactly the answer that I finally figured out!  I know that the question was elementary but I thank you for taking the time to show me this!  What I was missing was placing the jQuery library before the javascript file!
Comment: Why can't we put the library after the script? I can place the js script after the HTML element I need to interact though
Comment: That's a great detailed explanation. Just would like to add that you should avoid this [Legacy JavaScript MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#textjavascript)
Answer: This is how you link a JS file in HTML

JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag.  You can also include Jquery from a content distribution network such as the one hosted by Google.

Answer: You can add script tags in your HTML document, ideally inside the  which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.

Then in your javascript file you can refer to jQuery either using $ sign or jQuery.
Example:
jQuery.each(arr, function(i) { console.log(i); });

Answer: Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.
You use jquery by $ charater. Put libraries (like jquery) in  tag - but your script put allways at the bottom of document ( tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

<!doctype html>

    <meta charset="utf-8">
    <title>Example</title>

Im the content

Answer: this is demo code but it will help

<!DOCTYPE html>

<title>APITABLE 3</title>

            Id

            Email

            Firstname

            Lastname


Prove that an analytic function with a constant imaginary part is constant itself

Question: I want to prove that if $f$ is an analytic function for which $\Im f$ is constant, this implies that $f$ itself is constant.
So to start off, it's not given that the function is entire or anything, ruling out Liouville. Rather, I'm guessing the maximum modulus theorem will prove useful here (?).
If I were to show using that the real part of $f$ was constant, proving the statement would be easy (just take the absolute value and investigate $e^f$), but in this case I'm none the wiser from that. Should I use the same parametrization $e^f$ and apply the Cauchy-Riemann equations somewhere? Any suggestions welcome.
Comment: If you want to pursue your own idea, look at $e^{if}$.
Answer: Hint: use the Cauchy-Riemann equations, $f(x,y)=g(x,y)+ih(x,y)$ if $h(x,y)$ is constant, $\partial_xg=\partial_yh=0$ and $\partial_yg=-\partial_xh=0$ thus $g$ is also constant. done.
Comment: I guess this is the simplest proof..
Answer: The image of $f$ will be a horizontal line in $\mathbb{C}$. Now, consider the open mapping theorem.
Comment: (Given that $f$ is defined on a "nice" domain, i.e. a simply connected region).


What is the point of this postgresql.service file?

Question: This "services" appears to run /bin/true, but why?  There is another postgresql@.service file as well, but why does this one exist at all?  Yes, this is the entire file.
# systemd service for managing all PostgreSQL clusters on the system. This
# service is actually a systemd target, but we are using a service since
# targets cannot be reloaded.

[Unit]
Description=PostgreSQL RDBMS

[Service]
Type=oneshot
ExecStart=/bin/true
ExecReload=/bin/true
RemainAfterExit=on

[Install]
WantedBy=multi-user.target

Answer: This is just a dummy service, a trigger that starts the actual PostgreSQL through service dependencies. The /bin/true just makes it to look like it has started successfully, without actually doing anything.
Comment: Can you elaborate on how this starts all of the instances on a machine?  Something I'm just missing here.  The `/bin/true` now makes sense, but just don't see how it launches all of the instances......
Answer: The comments at the top are clear and explain the use. Each cluster has its own unit file postgresql@version-cluster and they are all "PartOf=postgresql.service". Thus this unit allows one to start up all clusters with systemctl start postgresql and other services to depend on all clusters being in a particular state (e.g., started).


"You need to be logged in to view that page" alert for authenticated user

Question: I have created a page using hook_menu for "employee" role using the code below:
 $items['admin/employee'] = array(
    'title' => 'Dashboard - Employee',
    'page callback' => 'employee_page',
    'access arguments' => array('Access administration theme'),
    'type' => MENU_NORMAL_ITEM,
);

When this page is viewed by an employee this alert appears: "You need to be logged in to view that page".
I tried to rebuild cache etc.
PS. I don't have an issue to access this page as an admin. Maybe I should use different access arguments?
Answer: First off, checking access as user 1 or Administrator is not a test because no permission checks are done for user 1, and in most cases Administrators have all permissions.
Two, your permission is mixed case, change it to all lower case and clear the cache.
Three, in order to access anything under /admin, user will also need access administration pages permission as well - or whatever permission is assigned on that menu item (I think that's the one).


Erro ao incluir o somatorio de valores no rodapé de uma gridview

Question: Estou tentando incluir no rodapé de uma gridview o somatório de duas colunas, mas estou com dificuldades em criar o método que realiza esta função.
Já pus a propriedade ShowFooter como true, agora tenho que implementar o evento DataBound mas não esta funcionando. Alguém pode me ajudar?
 protected void gvcarteira_DataBound(object sender, EventArgs e)
    {
                    double val1 = 0;
        double val2 = 0;
       // foreach (GridViewRow row in gvcarteira.Rows)

        for (int i; gvcarteira.Rows.Count - 1; i++)
        {
            // converte o preco e a qtde para multiplicar e somar no total

            double qt = double.Parse(gvcarteira.Rows[i].Cells[3].Text);
            double qtd = double.Parse(gvcarteira.Rows[i].Cells[4].Text);

            val1 = val1 + qt;
            val2 = val2 + qtd;

        }
        gvcarteira.FooterRow.Cells[0].Text = "Valor das Ações";
        gvcarteira.FooterRow.Cells[1].Text = val1.ToString();

        gvcarteira.FooterRow.Cells[3].Text = "Valor Gasto";
        gvcarteira.FooterRow.Cells[4].Text = val2.ToString();
      }

Quero que fique mais ou  menos assim:
Comment: A maneira de definir valores está correta. O que exatamente está acontecendo com a `GridView`?
Comment: (gvcarteira.Rows[i].Cells[3].Text), como nesse caso não foi declarado o i da erro, mas se deixo vaio da erro.
Comment: O erro, então, acontece aqui: `double qt = double.Parse(gvcarteira.Rows[i].Cells[3].Text);`
Comment: É um dos casos dependendo do tipo de laço que eu implemente, se for o foreach o erro esta no i que não foi delclarado. se uso o for o erro da no gvcarteira.Rows.Count - 1 .
Comment: Mas ele foi declarado. Vou colocar uma resposta pra você.
Answer:
Exemplo:
GridView:
<asp:GridView ID="GridDados" AutoGenerateColumns="False" runat="server" ItemType="WebAppDiegoWebForms.Fulano" OnRowDataBound="GridDados_RowDataBound" ShowFooter="True">
    <Columns>
        <asp:BoundField DataField="Codigo" HeaderText="Código" DataFormatString="{0:0000}"/>
        <asp:BoundField DataField="Nome" HeaderText="Nome" />
        <asp:BoundField DataField="Data" DataFormatString="{0:d}" HeaderText="Data" />
        <asp:BoundField DataField="Quantidade" HeaderText="Quantidade" />
        <asp:BoundField DataField="Valor" DataFormatString="{0:N2}" HeaderText="Valor" />
        <asp:BoundField DataField="ValorParcial" DataFormatString="{0:N2}" HeaderText="Valor Parcial" />
    </Columns>
</asp:GridView>

Na sua GridDados tem a colunas Quantidade, Valor e ValorParcial e no Footer será somando todos os valores de ValorParcial.
Como:
Modelo de classe:
public class Fulano
{
    public int Codigo { get; set; }
    public string Nome { get; set; }
    public DateTime Data { get; set; }
    public Decimal Valor { get; set; }
    public int Quantidade { get; set; }
}

Código dessa WebForm
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var valores = (new Fulano[]
        {
            new Fulano { Codigo = 1,  Nome = "Fulano 1", Data = DateTime.Now, Valor = 100M, Quantidade = 2},
            new Fulano { Codigo = 2, Nome = "Fulano 2", Data = DateTime.Now, Valor = 200M, Quantidade = 1},
            new Fulano { Codigo = 3, Nome = "Fulano 3", Data = DateTime.Now, Valor = 100M, Quantidade = 1},
            new Fulano { Codigo = 4, Nome = "Fulano 4", Data = DateTime.Now, Valor = 150M, Quantidade = 1},
            new Fulano { Codigo = 5, Nome = "Fulano 5", Data = DateTime.Now, Valor = 300M, Quantidade = 1}
        })
        .Select(x => new
        {
            x.Codigo,
            x.Nome,
            x.Data,
            x.Valor,
            x.Quantidade,
            ValorParcial = (x.Valor * x.Quantidade)
        })
        .ToArray();

        GridDados.DataSource = valores;
        GridDados.DataBind();
    }
}

private decimal total = 0;
private decimal valor = 0;
protected void GridDados_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        valor = 0;
        if (decimal.TryParse(e.Row.Cells[5].Text, out valor)){
            total += valor;
        }

    } else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[4].Text = "Total:";
        e.Row.Cells[5].Text = total.ToString("N2");
        total = 0;
    }
}

O carregamento nesse exemplo é manual, mas, pode utilizar da sua maneira. A única pecularidade que antes de enviar para o GridView GridDados eu faço uma multiplicação ValorParcial = (x.Valor * x.Quantidade) e envio os dados para grid todos formatados.
No GridDados_RowDataBound eu faço as devidas operações de soma e no final mostro no Footer do GridView. Obs: as variáveis do tipo decimal total e valor são colocadas fora do método GridDados_RowDataBound.
Resultado:
Answer: O problema não é o footer em si. É a iteração do laço. Considere trocar o for por um foreach, que é mais seguro:
foreach (GridViewRow linha in gvcarteira.Rows)
{
    // converte o preco e a qtde para multiplicar e somar no total

    double qt = double.Parse(linha.Cells[3].Text);
    double qtd = double.Parse(linha.Cells[4].Text);

    val1 = val1 + qt;
    val2 = val2 + qtd;

}

Comment: O visual studio não esta reconhecendo Cells, esta me dando o erro abaixo: 'object' does not contain a definition for 'Cells' and no extension method 'Cells' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Comment: Ah, sim. Perdão. Editei. Veja agora.
Comment: tenho que adicionar algum  using?
Comment: `using System.Data`, se não houver.
Comment: Com esse using ele não reconhece o Cells, sem ele o vs não reconhece o DataRow. não seria row.Cells?
Comment: Certo. Modifiquei novamente.
Comment: ok agora aparece um erro de compilação: Referência de objeto não definida para uma instância de um objeto. não seria pelo fato de eu passar os dado por referencia para o gridview?
Comment: Não sei. Só conferindo por breakpoint agora.
Comment: só mais uma duvida esse código vai em qual evento ? no DataBound ou RowDataBound?
Comment: O ideal seria ir no `RowDataBound`, e você ir definindo o total a cada linha.
Comment: O total de cada linha eu já tenho estou tentando definir o total geral de uma coluna especifica.
Comment: Não, não. Eu disse, o total **a cada** linha, não **de cada** linha.


Get annotation from a pdf to add to another document

Question: I am using iTextSharp version 5.0.
For my projet, I need to copy my pdf document into another pdf document using pdfWriter. I can't use pdfCopy nor pdfStamper.
So all the annotations get lost during this operation.
To begin, I started to find how to get the annotations of the "pencil comment drawing markup" as shown below on adobe reader UI:

For my tests, I am using this pdf document with a drawing markup I added my self: https://easyupload.io/3c6i1g

I found how to get the annotation dictionary:
Dim pdfReader As New PdfReader(pdfPath)
Dim page As PdfDictionary = pdfReader.GetPageN(0)
Dim annots As PdfArray = page.GetAsArray(PdfName.ANNOTS)
If annots IsNot Nothing Then
    For i = 0 To annots.Size - 1
        Dim annotDict As PdfDictionary = annots.GetAsDict(i)
        Dim annotContents As PdfString = annotDict.GetAsString(PdfName.CONTENT)
        Dim annotSubtype As PdfString = annotDict.GetAsString(PdfName.SUBTYPE)
        Dim annotName As PdfString = annotDict.GetAsString(PdfName.T)

    Next
End If

When the loop is parsing my comment the annotName variable returns my name, so I am sure to parse the annotation I am looking for but the annotSubtype is equal Nothing, how is that possible? According to the pdf specification at section 12.5.2 table 1666 (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf), the subtype parameter is required, so wouldn't it means this should not be at nothing?
Also, how can I get the image related to this annotation? I thought it would be stored in the content of the annotation dictionary but this is also returning nothing in the code above...
about why I can't use pdfStamper at the first place : one of the page of my pdf document must be resized (downscaled) in order to add some text at the bottom of the page, so I must use pdfWriter for that.
Question: How can I get the drawn line of a comment annotation with iTextSharp 5.0?
Comment: Your URL https://easyupload.io/2rxh7a returns *FILE NOT FOUND*.
Comment: Hi mkl, thanks I edited it : https://easyupload.io/3c6i1g
Answer: There are a lot of single questions in your post...

When the loop is parsing my comment the annotName variable returns my name, so I am sure to parse the annotation I am looking for but the annotSubtype is equal Nothing, how is that possible?
According to the pdf specification at section 12.5.2 table 1666 (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf), the subtype parameter is required, so wouldn't it means this should not be at nothing?

According to table 164 in section 12.5.2 of ISO 32000-1, the Subtype entry indeed is required, but it also specified to be a name while you try to retrieve a string instead:
Dim annotSubtype As PdfString = annotDict.GetAsString(PdfName.SUBTYPE)

As the Subtype entry of that annotation in your PDF correctly is a name, GetAsString returns Nothing.
Thus, call GetAsName instead and expect a PdfName return type.

Also, how can I get the image related to this annotation? I thought it would be stored in the content of the annotation dictionary but this is also returning nothing in the code above...

The Contents entry is specified in the same table as above to be optional and (if present) to have a text string value containing a Text that shall be displayed for the annotation or, if this type of annotation does not display text, an alternate description of the annotation's contents in human-readable form. As the annotation merely is a scribble, what should the annotation have as Contents value?
As your annotation actually is an Ink annotation, you can find the representation of the scribble in the required InkList and optional BS entries of the annotation, see table 182 of section 188.8.131.52 of ISO 32000-1.
The value of InkList is An array of n arrays, each representing a stroked path. Each array shall be a series of alternating horizontal and vertical coordinates in default user space, specifying points along the path. When drawn, the points shall be connected by straight lines or curves in an implementation-dependent way.
The value of the BS (if present) is A border style dictionary (see Table 166) specifying the line width and dash pattern that shall be used in drawing the paths.
Beware, though: The annotation dictionary's AP entry, if present, takes precedence over the InkList and BS entries. And in your PDF the annotation has an appearance entry. So the actually displayed content is that of the Normal appearance stream which contains vector graphics instructions drawing your scribble.

about why I can't use pdfStamper at the first place : one of the page of my pdf document must be resized (downscaled) in order to add some text at the bottom of the page, so I must use pdfWriter for that.

First of all, this only means that you have to do something special to that special page, there is no need to damage all pages by copying them with a PdfWriter. You could manipulate that single page in a separate document, then use PdfCopy to copy the pages before that page from the original PDF, then that page from the separate PDF, and then all pages after that page from the original again.
Thus, you'd only have to fix the annotations of that special page, the annotations on the other pages could remain untouched.
Furthermore, you can even use the PdfStamper if you are ready to use low level iText routines. In particular before stamping you can apply the static PdfReader method GetPageContent to the page dictionary of the special page to retrieve the page content as byte array, build a new byte array from it in which you prepend an affine transformation which does the downscaling, and set the new byte array as content of the page in question using the SetPageContent method of the underlying PdfReader
Even in this scenario, though, you'd have to adjust the annotation coordinates (both of their rectangles and of other coordinates like the InkList in your case)...

Question: How can I get the drawn line of a comment annotation with iTextSharp 5.0?

See above, the annotation of the scribble is an Ink annotation and the drawn path is specified in the InkList and BS entries of its dictionary and additionally instantiated in its normal appearance stream.


How can I copy the html from one node to another programmatically?

Question: I have an angular app running in a drupal page. The app goes out and fetches item data from an API, and displays the formatted item data in the drupal page.
I have no way of searching the data returned by the angular app -- as far as drupal is concerned, the page is blank.
Is there a way to copy the html created by the angular app, from the page where it resides, to another page as raw html? That should make it visible to drupal.
Comment: Angular is JavaScript based, so without some smart parsing of data Drupal will not be able to see the content. (How to do this is out of the scope of this site and is better asked on stackoverflow.com) But fetching data through 3 different layers is not going to make it easy. You might have more luck loading the data directly into Drupal, as Joseph suggests.
Answer:
Is there a way to copy the html created by the angular app, from the page where it resides, to another page as raw html? That should make it visible to drupal.

You're approaching the problem from the wrong angle. The root of the problem is that Drupal does not have the data supplied by the API, and NOT because Drupal does not have the HTML from Angular. Consider syncing Drupal with your API endpoint instead.
One route is to use the Feeds module, together with Feeds Tamper for pre-processing and Feeds Ex to allow various data formats. Another approach is to use the Migrate module.


What is the difference between copyItemAtPath:toPath:error and copyItemAtURL:toURL:error: of NSFileManager?

Question: I want to copy a file at path A to path B, in case it exists at B I want it to be overwritten and I want to use one of the mentioned methods but which one is the one I should use?
I saw their documentation and they say pretty much the same.
I can make NSURL objects from strings so both do the same?
Answer: Cocoa is attempting to standardize on URLs.  Consistent use of URLs can in some cases improve performance, because an NSURL object can cache some information from the filesystem and avoid redundant IO in the case that the information is requested again.
However, in the context of just this one method by itself, it doesn't really make any difference.
Comment: Can you point out anywhere in the docs that document 1) Use of URLs can improve performance 2) Some NSURL information is cached 3) Use of URLs avoids redundant IO?


How to serve a web request using hbase

Question: I have about 3 million documents that are pdfs, docs and images. I have build a website and if user search from website interface, I have to serve those hbase stored documents as required.

How can I do it?
Is it good to use hbase for serving web documents (in future these
  documents will be further increased) ?

My hadoop version is 1.2.1 and hbase 0.94.
Comment: what hbase gives you over a regular filesystem in your use case? For sure it is slower, requires more disk space, set up, etc, etc.
Comment: Can regular filesystem can handle such big ammount of files ?
Comment: yes. search servers can handle more than this in a scalable fashion.
Answer: I prefer in this case to have a search server that index this data and the web will integrate with this search server api for example: Solr, is an open source search server.
Hope this helps.
Comment: Can we index images in solr and can be retrieved  from solr?
Comment: Solr is a search product that can index any document type including images.
Comment: Can you provide me some link or reference to some solr example like my case ?
Comment: This is the Apache Solr ref on how to configure and index content in Solr: https://cwiki.apache.org/confluence/display/solr/Indexing+and+Basic+Data+Operations . This reference is very useful to get started and setup solr and configure it, and ingest data and all the way to advanced settings. Hope this helps.
Comment: Also, if you have scanned images that has text, this reference helps you step by step how to configure Solr to extract text within images. https://hortonworks.com/hadoop-tutorial/indexing-and-searching-text-within-images-with-apache-solr/  -- Hope this helps.

How to serve a web request using hbase


fazer desaparecer um botão

Question: Tenho um código aonde ele cria um tabela caso tenha um registro no banco de dados. Nessa tabela, na última coluna tem um botão que ao clicar abre uma tela mais detalhada sobre aquela linha da tabela. Preciso fazer com que esse botão apareça apenas nas primeiras duas linhas da tabela, fazendo com que nas outras não apareça nenhum botão. Estou tentando de várias maneiras, mas até agora não consegui nenhum avanço. Meu código está em CodeIgniter.
View:

<?= $this->lang->line("view_laudo_wg_title"); ?>

            <?= $this->table->generate(); ?>

Controller:
public function index() {
        $tmpl = array('table_open' => '
');
        $this->table->set_template($tmpl);
        $this->table->set_heading('' . $this->lang->line("con_laudo_th_ti") . '', '' . $this->lang->line("con_laudo_th_dh") . '', '' . $this->lang->line("con_laudo_th_op") . '', '' . $this->lang->line("con_laudo_th_di") . '', '' . $this->lang->line("con_laudo_th_de") . '', '' . $this->lang->line("con_laudo_th_nr") . '', '' . $this->lang->line("con_laudo_th_pe") . '', '' . $this->lang->line("con_laudo_th_ac") . '');
        $data['caminho'] = 'ConLaudos/generateTable';

            $this->load->view('ViewLaudos', $data);

    }

    public function generateTable() {

            echo $this->ML->getLaudos($this->lang->line("con_laudo_tip_insp_v"), $this->lang->line("con_laudo_tip_insp_e"), $this->lang->line("con_laudo_per_insp_u"), $this->lang->line("con_laudo_per_insp_r"), $this->lang->line("con_laudo_acoes_insp"));

    }

Model:
public function getLaudos($vei, $est, $urb, $rur, $aca) {
        $this->datatables->select('ls.lau_id, ls.lau_tipo, ls.lau_data, usu.usr_nome, dispo.dsp_nome, ls.lau_densidade, ls.lau_nivel, ls.lau_zona, ls.lau_status');
        $this->datatables->from('ls');
        $this->datatables->join('usu', 'ls.usr_id = usu.usr_id');
        $this->datatables->join('dispo', 'ls.dsp_id = dispo.dsp_id');
        $this->datatables->join('empresa', 'empresa.emp_id = usu.emp_id');
        $this->datatables->where('usu.emp_id = ' . $this->session->userdata('emp_id') . ' AND usu.usr_nivel<>0');

        $this->datatables->unset_column('ls.lau_id');
        $this->datatables->unset_column('ls.lau_status');
        $this->datatables->add_column('Ações', '$1', 'get_buttons_ls(ls.lau_id, ls.lau_status, ls.lau_tipo,' . $aca . ')');
        $this->datatables->edit_column('ls.lau_tipo', '$1', 'trataLauTipo(ls.lau_tipo,' . $vei . ',' . $est . ')');
        $this->datatables->edit_column('ls.lau_data', '$1', 'tratarDataHora(ls.lau_data)');
        $this->datatables->edit_column('ls.lau_zona', '$1', 'trataLauPerimetro(ls.lau_zona,' . $urb . ',' . $rur . ')');
        $this->datatables->edit_column('ls.lau_status', '$1', 'trataLauStatus(ls.lau_status)');
        return $this->datatables->generate();
    }

Comment: Porque tantas repetições no nth-child? Além disso vocé pode fazer isso dessa forma:  childrens[number] = 'nth-child('+number+')'; $('td:'+childrens+',th:'+childrens).addClass('hidden-md hidden-sm hidden-xs')
Comment: @IvanFerrer esse código foi outra pessoa que fez, eu apenas estou arrumando ele, não sei exatamente o motivo de tanta repetições. Eu já tentei entrar em contato com o mesmo, mas não me responde. Desde já gradeço!
Answer: Altere seu código para isso:

Comment: coloquei esse código que você enviou, não mudou nada, aparece o botão em todos registros ainda, e não apenas nos dois primeiro. Obrigada!
Comment: @Ketlin, publica o método $this->table->generate(), esse que constrói a tabela, eu preciso ver como você está montando isso, ou construa a tabela para eu entender onde você quer esconder os 2 primeiros botões. Quantas colunas e linhas têm?
Comment: eu coloquei todo o código que eu tenho, não fui eu que fiz, eu tenho que arrumar ele apenas. Também não estou entendendo ele direito. Tudo que eu tenho relacionado a essa tabela é isso. Ela tem 8 colunas, sendo que na ultima vai esse botão. No controller no generateTable na parte $this->lang->line("con_laudo_acoes_insp")); é aonde está o nome do botão. Espero que tenho ajudado. Grata pela atenção
Comment: Eu fiz uma alteração, veja se funciona agora.
Comment: Também não funcionou, a tela fica com a mensagem que está carregando os dados e o botão também não desapareceu.
Comment: Eu pensei em fazer uma equação(todos os registros - todos os registros + 2 registros) entretanto não obtive sucesso em transformar em código.
Comment: Essa última coluna, como é a estrutura dela? Você pode ocultar o botão dentro do for. tipo: if (i > 2) { 'esconde elemento'; } e deixa os outros visíveis, no caso, vc pode também pode passar a clase eu acho que é algo como table:last-of-type
Comment: Agora acho que está certo
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/26152/discussion-between-ivan-ferrer-and-ketlin).
Comment: abri a discussão no chat. Grata

fazer desaparecer um botão


Why do I get EXC_BAD_ACCESS?

Question: I have following code, which executes on button press. At first it works as expected but second time onwards application hangs and I get EXC_BAD_ACCESS signal.
- (IBAction) comicDetailsPressed:(id)sender {
   static IssueProperties *props = nil;
    if (props == nil) {
        props = [ComicDataParser
         parseComicForUrl:@"http://dummy.com/Jan.xml"];
    }

    NSLog(@"%d", [props totalPages]);

    totalPages.text = [NSString stringWithFormat:@"%d", [props totalPages]];
}

Answer: You didn't say what line it's crashing on, which will mean answers will have to be speculative.
You have a static pointer to a IssueProperties object, but when you assign to it, you aren't using retain. You probably should.
This is assuming that the return value from parseComicForUrl: is a IssueProperties object or a subclass.
I'm assuming that the text property is an NSString set to copy and not retain. If not, it should be.
Comment: Your statement about the `text` property seems like overengineering. While you should copy string properties that could come from any client code, in this case we can only see the property being set by `+stringWithFormat:`, which returns an immutable string. Therefore copy is overkill unless you know something about Prashant's code that we don't.
Comment: @Graham Lee I don't understand how you see it as overengineering; you have to choose either `assign`, `retain` or `copy` for a property, and it's well-known the issues you get with `NSString` properties when you don't use `copy`... so why not avoid future issues and reduce risk if you can?
Comment: @Shaggy Frog: Ya Aint Gonna Need It. If you try to avoid all the future issues you can think of, you'll never ship 1.0.
Comment: @Graham Lee You're overstating your case about overengineering. As if mentioning the best practice of using `copy` with `NSString` properties is akin to telling the guy he'll never ship his app. Let's dial back the hyperbole a bit.
Answer: You need to retain the object you get back from +parseComicForUrl:. Also, why don't you use an instance variable for props?
Comment: making props as an instance variable is good idea, I was just trying some XML parsing thing in objective-c, so I did not think of it. Thanks
Answer: Without a lot more context, it is going to be impossible to answer for sure, but my first thought would be this:
your static IssueProperties *props would not be nil the second time around.  Instead, it would have the value that [ComicDataParser parseComicForUrl] returned.
My guess is that the ComicDataParser is autoreleaseing the response, and so the second time around you have a pointer that is not nil, but is now pointing to an already released object, which is invalid.
If I am right, you need a retain somewhere.
Comment: Thank you for quick response, problem is fixed after retaining `props`. I think I should go through Memory management guide again.

Why do I get EXC_BAD_ACCESS?


Find entity with unique id without knowing its type EF

Question: Is there any way to find an entity with its unique id without knowing its type ?
For example write
DataContext.Find(Id);

instead of
DataContext.Set<T>().Find(Id);

Thanks
Comment: Why do that? What problem are you trying to solve? BTW there's no such thing as a universal unique ID in a database. Each table has its own columns that define its primary key. You can't (actually, you **don't** want to) write a query that would search all tables in a database to find a row by ID. Such a query would be extremely slow, lock all tables and freeze any application that uses this database
Comment: @PanagiotisKanavos Thank for your help  . As a result , As this is impossible I should think of another way . Any way Thanks  ;)
Comment: Whatever you want to do, there are better ways to do it. What do you really want to do? What you posted is two wrong snippets - one that doesn't exist and one that shouldn't be used. A DbContext is neither a database model nor a database connection. It's a *Unit-of-Work* including *specific entities* that are used in *specific use cases only*. Not a way to expose all tables to the client
Comment: Another way to do what????? You haven't asked anything yet, just posted suspicious  code. It looks like you're using DbContext like a database model, or trying to build the repository *anti*pattern on top of the ORM
Comment: @PanagiotisKanavos Actually I wanna be able to save comment for every product . So I made an one to many relation between comments table and products table. The problem starts where I receive the comment text and info and i want to make a relation between that comment and product  but I don't know ow to find the product between other product tables
Comment: All you need is to create the proper tables and relations then. An ORM like EF can't do things that are impossible in SQL. If a comment can only apply to a single product, you need a 1:Many relation between Products and Comments. In the database that would be a single `ProductID` column in `Comments`. In EF, this would appear as a `Product` property in the `Comment` class
Answer: Id is unique only within the table. You can not give Id and ask, in which table is it used...You do not want to do it this way :)
Comment: This should be a comment


Prove or disprove that if y=x, then 0=0?

Question: I got this wrong on my exam. Where did I go wrong?
Disproof: suppose $y=x$. Then $y-x=x-x$ is true. Dividing both sides by $y-x$, $$\frac{y-x}{y-x}=\frac{x-x}{y-x}$$The right hand side simplifies down to $1$, while the left hand side simplifies down to $0$ since $x-x=0$. Thus $$1=0$$ which is a contradiction.
EDIT: Contrapositive. Suppose $0≠0$ (for example $0.0000000001 ≠ 0.00000000000000000002$). Then there exists $k \in R$ such that $0=0+k$.   Subtracting $x$ from both sides, $0-x=0-x+k$. Adding $y$ to both sides, $0-x+y=0-x+y+k$. Subtracting $0$ from both sides, $k-x+y=-x+y+k$. Subtracting $k$ from both sides, $-x+y=-x+y$. Thus $x=y$.
I'm at a loss as to how I should prove it...
Comment: Where's the contradiction in your edit? I'm pretty sure $0=0$ is true.
Comment: Couldn't really find one. I'll try to use the contrapositive approach.
Answer: You've divided by $0$.
Needless to say, this will give you garbage results.
Comment: What your professor is saying doesn't make a lick of sense to me, I'll admit.  What is the context?
Comment: It sounds like either your professor was sloppy or you didn't entirely understand the question he had asked, because outside looking in, those statements simply aren't true.  $0$ is a single, well-defined number.  Saying that for each $x>0$ there is $y$ such that $x>y>0$ is simply the statement that the real-numbers form a densely-ordered set.  But when someone writes $0$, they should mean the (single) number $0$.
Comment: I don't quite see where I've divided by 0. I think y and x are two distinct numbers?
Comment: You've assumed $x=y$.  They're definitely not distinct.  Subtracting $x$ on both sides yields $0=y-x$.
Comment: Thanks for pointing that out! Maybe I'll try to prove this using contradiction instead of disproof and get back to you.
Comment: I found that if we assume $y≠x$ for proof by contradiction, then $0=0$. Am I doing something wrong?
Comment: Looking back, I'm confused on what you're actually trying to show.  The way it reads now, you wish to show that the statement "$x=y$" implies the statement "$0=0$".  In that case, regardless of whether $x$ actually equals $y$ (or not), $0=0$ is still always true.  The implication $P \to 1$ is always true ($1$) regardless of the value $P$.
Comment: I'm trying to show that $x=y$ implies $0=0$. However, my professor told me that $0 \in R$ can have different meanings, that is, $0$ can be $0.000000001$ and $0$ can be $0.0000000000002$. Therefore, in that case, $0≠0$.
Comment: He made the point that there are different kinds of 0 $\in R$ - one 0 can be 0.00...01 and another can be 0.00...02. Both numbers are essentially 0, but they are not equal.
Comment: Also, consider the set $0=(0, 0.00000000000000000000000001]$. The professor asked what's the smallest element in such a set? The point is that if you pick a really small element, there will always be a smaller element (just add another 0 decimal place). Thus, no two elements in such a set are equal. I use the same argument here when trying to prove the contrapositive.
Comment: I guess if I assume that division by 0 is not allowed, then your answer makes sense. But we never proved that in class, so I don't think we're allowed to assume that...
Comment: In fact, the "proof" you gave in your original question is essentially a proof, since you end up with a contradiction at the end.  put without the x's and y's, we have $1\cdot 0 = 0\cdot 0 = 0$, so if division by $0$ were possible, we'd find $1=0$, a contradiction.
Answer: when $y=x$, $y-x=0$ and hence, you can not divide by $(y-x)$ as division by zero is not allowed.
Comment: I agree, but how do I prove this? How do I know that division by zero is not allowed?
Comment: @TomD1 Since when is division by zero allowed?


Prove the linearity of the following maps

Question: Let $f,g$ and $h$ be in $C^\infty$ on $\mathbb{R}^3$. Is the following statement true?
If $x^2+y^2+z^2=(f(x,y,z))^2+(g(x,y,z))^2+(h(x,y,z))^2$ then $F=(f,g,h)$ is linear
Maybe this could be a consecuence for some conformal map theorem for $\mathbb{R}^n$ with $n\geq 3$?
Many thanks!
Comment: Perhaps you should specify that f,g, and h are real valued. Otherwise it is false.
Comment: Suppose also that $f,g$ and $h$ are real valued. How could be the proof? I can write it
Comment: On the other hand, it is true that if $$(x-x')^2 + (y-y')^2 + (z-z')^2 = (f(x,y,z) - f(x',y',z'))^2 + (g(x,y,z) - g(x',y',z'))^2 + (h(x,y,z) - h(x',y',z'))^2$$
for all $x,y,z,x',y',z'$ and $f(0,0,0)=g(0,0,0)=h(0,0,0)=0$ then $F$ is linear.
Answer: No. For example, let $$f(x,y,z)=x\sin z-y\cos z$$$$g(x,y,z)=x\cos z+y\sin z$$ $$h(x,y,z)=z$$
Then, $F(1,1,\frac{\pi}{4})=(0,\sqrt2,\frac\pi4)$ and $F(2,2,\pi/2)=(2,2,\frac{\pi}{2})$. Hence $F(2,2,\frac{\pi}{2}) \neq2F(1,1,\frac{\pi}{4})$, which contradicts linearity of $F$.
Comment: You need to remove the $\frac{1}{\sqrt{2}}$ in $f$ and $g$
Comment: Oh yes, thanks :)
Comment: Don't forget to update the function values.


How to get value from a disabled text field when the value is not present in ID or in any attribute using Java in Selenium WebDriver

Question: I have a few disabled text field auto-populated with some values based on my previous input. I want to verify whether auto-populated values are as per my previous input. But I am unable to get the value from the text field using .getText() or .getAttribute() as the value is not present in the HTML code.
Below is the HTML code got using inspect element:

<input type="text" class="ProductList_Price" style="width:97px" ***disabled*** data-validation="mandatory"> == $0

The text is a field is auto-populated with value "100" as per my previous input. But how can I verify whether the auto-populated value is 100 in the disabled text box?
Comment: Where can be the `auto populated values` found if `the value is not present in the html code`? To retrieve the required attribute value those values need to be present in the DOM. Then only we can use  `.getText()` or `.getAttribute()`
Answer: The value attribute stores the content of a tag, does not matter whether it is disabled or not. So, you can do it like this:
driver.findElement(By.id("write_element_id_here")).getAttribute("value");

this will return you the value of the element and then you can proceed with the rest. Hope it helps..
Comment: Happy to help :)
Answer: In your case can help the following code:
value = driver.findElement(By.className("ProductList_Price")).getAttribute("value");

Hope it helps you!
Answer: It happens sometimes and in such cases, you can use element.getAttribute("innerHTML") and you can then process the output string.


Moving from subdirectory to root

Question: When I installed Drupal, I put it in a subfolder /drupal. Got everything set up and then moved everything into my root folder. When I went to the site I got this error:
Failed opening required '/home3/XXXX/public_html/drupal/modules/field/field.crud.inc'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home3/XXXX/public_html/drupal/modules/modules/field/field.module on line 20

Then I moved everything back to /drupal and still get the same error.
Can anyone tell me where I should be looking for the issue?
I looked in my settings.php file and didn't see anything about a directory listing. I looked in /sites/default/settings.php and couldn't find anything to do with directories.
Thanks for the help!
Comment: Are you sure you disabled APC and purged all cache* tables?
Comment: I got it fixed, I must have mistakenly moved a folder before hand. Thanks for the input!
Answer: for show the subdirectory site in the root I followed this guide.
I hope it could be usefull for you too ^^
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.

Moving from subdirectory to root


cannot see django server welcome page on firing up the server

Question: I am beginning to learn web development with Django, on windows 7. I have installed python 2.7 and django 1.10 for the purpose. I made a sample project from windows powershell, and when i start the django server, as shown below, starting django server from powershell
when i go to the IP 127.0.0.1:8000/, it does not show me a django welcome page like the one below django server welcome page
All i see is a blank page. I have tried restarting the server many times, but never once, did i see the welcome page. What could be the problem here?
Answer: Not sure if this is the cause of the issue but maybe you want to do the database migration step as the error message suggested. Just run
<code>python manage.py migrate
</code>


Two trigonometric eliminations

Question: I have a couple of trigonometric elimination questions for you...
$1) a \sin \theta = b \sin (2 \theta)$; $c \cos \theta = d \cos (2 \theta)$
*NOTE: the first equation was incorrect...I had $\cos 2 \theta$ and it should be $\sin 2 \theta$.
I was able to get the answer to $2(abc - a^2 d + 2b^2 d)=0$, but the actual answer is $(c^2 - d^2)(abc - a^2 d + 2b^2 d)=0$.  Where does the $(c^2 -d^2)$ come from?
UPDATE: I think I know $(c^2-d^2)$ comes from.  If $\theta$ =0, then cos $\theta$ = 1 and in turn cos 2 $\theta$ = 1; plugging these values into the first equation gives us $c = d$. (I already did the second condition where $\frac {a} {2b}$))  If we square the first condition and subtract, that gives us $(c^2-d^2)$; since this also equals $2(abc - a^2 d + 2b^2 d)=0$, we can multiply both sides by $(c^2-d^2)$ to get the final result.
UPDATE #2: Actually, the more I thought about it, this is correct.
$2) \displaystyle x \cos \theta + y \sin \theta = \cos (3 \theta)$; $x \sin \theta - y \cos \theta = 3 \sin (3 \theta)$
I'm not sure where to start...I've tried squaring both equations, multiplying, etc.  (The answer for this is $\displaystyle(x^2 + y^2)(x^2+y^2+18)+8x(x^2-3y^2) = 27$.)
UPDATE: I was able to get the following for x and y (thanks to the suggestion!)
$\displaystyle x= 2\cos 2 \theta - \cos 4 \theta$
$\displaystyle y = 2\sin 2 \theta + \sin 4 \theta$
UPDATE 2/16/14: BREAKTHROUGH!  Never mind...that answer bombed out.
UPDATE 2/17/14: Not giving up and using the advice below, I finally got $\displaystyle c = \frac {(x-1)^2 + (y^2-4)}{12}$...I'm going to plug this in to the equation for x and see how it goes.  If all works well, I should finally get the answer, save all the cleanup work.  Never mind.
UPDATE 4/8/17: I reposted question #2 to get a fresh perspective...see Trigonometric elimination (reprise from 2014). If it's a duplicate, my apologies!
Thanks for your help!
Comment: Congratulations on finding your solution! Please write it up in full as an answer here and accept it, so that your question doesn't remain in the Unanswered queue.
Answer: HINT:
$1)$ For the original version:
Divide to find $\tan\theta$
and  use $\displaystyle\cos2A=\frac{1-\tan^2A}{1+\tan^2A}$
either  $(i)$ in square one of the given equation
or $(ii)$ in $$\left(\frac{b\cos2\theta}b\right)^2+\left(\frac{d\cos2\theta}c\right)^2=\sin^2\theta+\cos^2\theta=\cdots$$
For the edited version
From the first relation, $\displaystyle\sin\theta(a-2b\cos\theta)=0$
If $\displaystyle\sin\theta=0,\cos\theta=\pm1,\cos2\theta=2\cos^2\theta-1=1$
Else $\displaystyle\cos\theta=\frac a{2b}$
Put the values of $\displaystyle\cos\theta,\cos2\theta$ in the second relation, $\displaystyle c\cos\theta=d\cos2\theta$

$2)$
Solving for $x,y$
$\displaystyle x=2\cos2\theta-\cos4\theta=2c-(2c^2-1)\iff 2c^2=2c-1-x\  \ \ \ (A)$ where $c=\cos2\theta$
$\displaystyle y=2\sin2\theta-\sin4\theta=2\sin2\theta(1-\cos2\theta)$
$\displaystyle\implies y^2=4(1-c^2)(1-c)^2\ \ \ \ (B)$
Put the value of $2c^2$ from $(A)$ in $(B)$ to find $c$ in terms of $y^2$
Then, put this value of $c$ in $(A)$
Answer: Here's a brute force approach to #2. For simplicity, I'll write $s$ and $c$ for $\sin\theta$ and $\cos\theta$.

Expand $\cos 3\theta$ and $\sin 3\theta$ $$\begin{align}
x c + y s &= c \; ( 4 c^2 - 3 ) \\
x s - y c &= s \; ( 4 c^2 - 1 )
\end{align}$$
Isolate $s$ terms, and square, so that we can re-write in terms of $c$. $$\begin{align}
(y s)^2 &= c^2 ( 4 c^2 - 3 - x )^2 \quad \to \quad y^2 ( 1 - c^2 ) - c^2 ( 4 c^2 - 3 - x )^2 = 0\\
(y c)^2 &= s^2 ( 4 c^2 - 1 - x )^2 \quad \to \quad y^2 c^2 - ( 1 - c^2 )( 4 c^2 - 1 - x )^2 = 0
\end{align}$$
Invoke one of my favorite tools ---the "method of resultants" (which I describe a bit in this answer)--- to eliminate $c$. Mathematica's (and/or WolframAlpha's) Resultant[] function makes it easy, yielding this polynomial equation: $$\begin{align}(\;x^4 - 4 y^4 + 3 x^2 y^2 + 8 x^3 - 18 x y^2 + 18 x^2  + 27 y^2 - 27 \;) & \\ \cdot\;(\;x^4 + y^4 + 2 x^2 y^2 + 8 x^3 - 24 x y^2 + 18 x^2 + 18 y^2 - 27 \;) &= 0\end{align}$$
The second factor corresponds to the answer you expect. Presumably, the first factor is extraneous in the current context (as is often the case with resultant results), but it's not obvious to me why that is.

The same process works for #1.
Comment: I tip my hat to you, Blue.  This was a problem from Durell & Robson's _Advanced Trigonometry_ and yours truly has been attempting to solve this for the last two months.  I'll try it with both 1 and 2 and let you know.  Thanks!
Comment: If the exercise is in a trig book (even an advanced one), chances are that you aren't expected to use stuff like resultants. (These days, I personally tend to hit most problems with the `Resultant[]` hammer first, and then look for more-elegant paths to the solution.)
Comment: For the record, I graduated with a BS in math 20 years ago!  We were never taught resultants, so this is a new thing for me.  You always learn something new!

Two trigonometric eliminations


Adaptec 5805 RAID 1: need more space

Question: We have a server with an Adaptec 5805 RAID 1 array, with two SAS 146GB disks. We need more space on this server.
Is it possible to hot-replace each 146GB HD with a 300GB HD, and let the controller reconstruct the array after each disk change? Is the new space left automatically visible after the second disk change?
Comment: Thou shalt not accept the wring answer.:)
Answer: You can definitely do this.
I replaced a faulting 1TB disk with a 2TB disk; it did rebuild the array, then I replaced the non-faulting 1TB disk with another 2TB disk. After the second rebuild, you need to go in and adjust the device size in the RAID manager software (which you can't do whilst the rebuilds are taking place).
The RAID manager software I used was "Adaptec Storage Manager" --> Actions "Expand or Change Logical Drive".  Then I increased the size and let it reconfigure the device.
The reconfiguring started at 50% and took a very long time, but it eventually finished.
After that, I had to increase the file system (NTFS on W2K8 server), but I had to rescan the disks first (diskmgmt.msc).  After increasing the NTFS size to take up all the extra space (which shows as unallocated space), the server was somewhat non-responsive, a reboot fixed this and everything is working fine now with the file system seeing the new full capacity.
Answer: Yes, it will be.
Adaptec doesn't care about disk size - it supports and works with partitioning (segments). Adaptec supports live migration and kernel can recognize block device size changes.
You should replace disks one-by-one and rebuild same size array, then expand array.
And that's all you need to do.
You will see kernel message after:
<code>[ 3996.863384] sdd: detected capacity change from 2003828736 to 6700382873
</code>
Answer: That won't work sorry - if you removed the first disk and replaced it with the larger one that disk would be setup by the controller as through it were a 146GB disk not a 300GB disk and the same would occur when you replaced the second smaller disk.
That controller does support RAID-level migration however so you could add one of the new disks as a third member of a RAID 5 array but it would still only add 146GB to that array.
Comment: absolutely wrong. adaptec has online capacity expansion. after first drive will be replaced, raid 1 array will be reconstructed, then same can be done with second drive, and finally, array will be expanded.
Comment: Exactly. That said - it does not expand the RAID array automatically, this is a manual process. But it is doable - so another one of those "Accepted but Wrong" answers, sadly.

Adaptec 5805 RAID 1: need more space