Foreign undergraduate study possibilities for a student in Southeastern Europe

Question: In the (non-EU) country I live in, the main problem with undergraduate education is that it's awfully constrained. I have only a minimal choice in choosing my courses, I cannot take graduate courses, and I have to take many applied and computational classes. My problem is that

I have already learned (or I plan to learn in the 9 months until university) a lot of the pure mathematics that I would learn at the undergraduate programme
I am not interested in applied or computational classes

I'm interested in:

Is there any undergraduate programme, affordable to an average but dedicated student with a modest budget, which either has very pure emphasis or freedom in choosing the classes? I'm ready to learn a new language if it is required.

Thank you for any help!
Comment: @Matt: That list is does not translate over to mathematics in my opinion.  For math, École Normale Superieur should be much closer to the top position.  Not decisive evidence, but worth noting, all 10 fields medalists from France were educated there, more then any other institution in the world.
Comment: @Lovre: I study at the ETH Zürich and I can tell you that it (for now) has the same fees for both local and foreign students. Also, at least for Germans, it is incredibly easy to apply. However, living expenses in Switzerland tend to be pretty high.
Comment: Hey Matt, thanks for the link. Unfortunately many universities have higher fees for either the foreign students or non-EU students, and I'm unsure whether I have good enough academic history to get into the best universities.
Comment: @Matt: Those fees look like those applied to local students.  The English numbers would be much higher for non-EU students, and from September 2012 will be about £9000 (~$14000) for new English students
Comment: @Huy: Thanks for that information.
Answer: Since I am living in France now on exchange, I can tell you a tiny bit about the system here, and why I might recommend France.
Let me start by mentioning:

The Tuition at some universities* is little to non-existent for undergraduate students.  Even international students.
It is one of the most prominent countries for mathematics over the last 200 years, and mathematics is one of the most respected subjects among many top French Universities.  (At Polytechnique it is the most important subject, as there is the underlying ideology that all scientists and leaders should have a concrete understanding of mathematics) Also, France is second only to the US for number of Fields Medalists with a population which is a 5th of the US.

One important thing is that their system is very different from North America and the rest of Europe.
There are two main branches after highschool, University and "Les Classes Préparatoires" which leads to "Les Grandes Écoles."  The second is considered more prestigious, and the most coveted institution in that line are École Normale Superieure and École Polytechnique. (For what it is worth, I believe that half of the CEO`s of the top 50 corporations in France, and 3 former presidents graduated from Polytechnique, while all 10 French Fields Medalists are alumni of École Normale Superieure)
I am not sure how admission to these schools works for international students, as taking "Les Classes Préparatoires" is probably not an option.  This would be something to look into.  (I can tell you about the Exchange program but that is probably of no help!)
For the other line, there are many very strong Universities as well. In particular Paris 6 and Paris-Sud 11 are probably the most notable for Mathematics as they are both excellent on the world stage. (Paris 6 is also known as Pierre and Marie Curie University, part of the Sorbonne)  Often times for research Paris 6 is ranked as number 1 in France.
An enormous number of the French Universities are in Paris, which I think is a plus because Paris is a beautiful city. The only downside to this is that the rent is extremely high.  However, fortunately the French government is quite left leaning and has set up programs which help students.  (Yes even international students!) In particular the CAF pays part of the rent for students, the so called "aide de logement."
Lastly French is very useful language as far as it goes.  There are quite a few countries which speak French, and many math papers are written in French.
In short, I suggest considering many universities in France, and actively looking for more details.  In particular, if you are interested you should seek out all the information you can, when the deadlines are, how the process works for international students at that particular institution, what are the costs, do I need to write a particular test, do they require a particular French level on the TOEFL, etc...
Remark:  Just worth thinking about the fact that the cost of living for 4 years is going to be a lot wherever you go.
Comment: Thanks for your suggestions Eric, I will look more into the admission procedure for international students.
Answer: Since I had the chance to do a major part of my education in France and especially through this system of "Classes préparatoires" and "Grandes Ecoles", I will try to give you more details about those, and particularly about the fees.
First I think the "Classes préparatoires" could fit you well, Eric Naslund gave a good overview of the French system.
What I can add is that most of the top "Classes préparatoires" provide grant for foreign people, including people coming from non-EU countries. They provide also a room for people that can't pay a rent in Paris for instance, so that you can study mostly without paying anything. There is also a strong alumni network that can help you and lend you some money to pay your studies. There is also a lot of "foyers" around Paris that allow you to have a room for a low monthly fee.
You can look for more information about the "Classes préparatoires" here:

http://www.louis-le-grand.org/
http://lyc-henri4.scola.ac-paris.fr/prepas/admission/index.html

And about the "foyers":

http://www.crous-paris.fr/
http://www.pariserve.tm.fr/logement/foyer.htm
http://www.letudiant.fr/loisirsvie-pratique/logement/logement_1/quels-foyers-pour-les-etudiants-.html

(You will need to use google translate unfortunately to get more details on those website)
Like a lot of French institutions, you need to speak well French. In some of them 15% of the students are not from France and they can follow french courses when they arrive if they don't speak french well. I can't provide you with a specific procedure to enter those "classes préparatoires" when you are not already in a "Lycée Français à l'étranger". You need, I think, to contact them directly, they will give you some details. I know that some tests are organised around the world to recruit some student out of the French scholar system. If you worry about your level, you must know that all the french "Classes préparatoires" have a different level, some require a good scholar history, other less. You just need to find the one that fit you the most. However, I don't know if all of them have a dedicated structure for foreign student.
Considering the French "Grandes Ecoles", one of the big advantages of schools like the Ecole Polytechnique or the Ecoles Normales Supérieures is that they also have no tuition fees, and they also provide grant to foreign people. At Polytechnique for instance, each foreign student has a grant either from his home country, either from the school or from the other French students themselves. It means that nobody is left without any money income during the time of the studies. Moreover they have specific admission track for foreign people, some of them even including intensive French course before the beginning of the studies (The Ecole Polytechnique has such a program for foreign student, so that you don't need any particular level in French to enter the admission system).
You can look for some more information here:

http://www.polytechnique.edu/jsp/accueil.jsp?LANGUE=1
http://www.ens.fr/?lang=en
Comment: Thanks for the suggestions and links ReV.
Answer: Hungary also has a very strong mathematical tradition, especially in discrete math, and has relatively cheap living standards. Many great mathematicians have studied at Eötvös Loránd University (ELTE) in Budapest. You can try looking there as well.
Comment: Hey user980123, thanks for the information.


A special condition on the Minimum Cost Flow Problem

Question: I am working on the following exercise:

Consider the minimum cost flow problem with the following additional constraint: For each vertex $i \in V$ we are given an upper bound $w_i$ for the amount of flow which enters vertex $i$. How can this version be transformed to the classical minimum cost flow problem?

I would say that it should be enough to replace the capacities $u$ with $w < u$ by $u^\prime := u-w$. Does this suffice?
Comment: What classical form do you consider?  Lower and upper bounds on flows?
Comment: The one described on the second page here http://www.columbia.edu/~cs2035/courses/ieor6614.S16/mcf.pdf
Comment: OK, so 0 lower bound and arbitrary upper bounds on flow.
Answer: Split each node $i$ into two nodes $i'$ and $i''$, with all incoming arcs to node $i$ redirected to enter node $i'$ and all outgoing arcs from node $i$ redirected to leave node $i''$.  Now introduce an arc from $i'$ to $i''$ with capacity $w_i$.  It remains to define $b(i')$ and $b(i'')$ in terms of $b(i)$.


How to establish ODBC connection through ssh tunnel?

Question: I have SSH access to an iSeries (DB2 Database) through a firewall. I am trying yo make queries to a db in the machine using ODBC.
I have found several tables explaining what ports are used by the protocol but don't know what to do with this information. Is there any way of redirecting traffic to the ports used by odbc if I have ssh access to the machine?
http://search400.techtarget.com/answer/What-TCP-ports-are-used-by-ODBC-to-connect-to-the-DB2-400
Answer: So, assuming you have a database client running on your PC, then you can create an ssh tunnel that sets up ports on your PC to reflect the ports that are running on the database server. Then direct your client to query your local host. Here's how to set up the tunnel for one of the ports, say 8471:
ssh -L 8471:localhost:8471
In this case "localhost" refers to the server, not your PC. You can replace "localhost" with the server ip address if you want.
After setting up this tunnel, if you "telnet" to port 8471 on your PC, it will connect you to the database server port 8471.
You'll have to repeat this for each of the ports in the list.
You may run into a problem if the database server requires its own hostname in the connection string. If it does, you will need to trick your client into thinking that the hostname of the PC is the same as the hostname of the db server.
Comment: @cabe56: (1) establish the ssh connection to dbserver in whatever way you like (2) the -L option on ssh will forward whatever PC port you want, to whatever dbserver port you want. (3) for testing, telnet PC port X. this will connect you to dbserver port Y. (4) firewall has nothing to do with it
Comment: The problem is that the server containing the DB is behind a firewall. I would have to redirect all ports in the firewall to those on the server, which would not allow for any other odbc connections through the firewall. Dunno about security issues, if anyone cares to comment that would be appreciated.
Comment: @cabe56: you don't need to touch the firewall. As long as the database listens to its its own local machine, you're fine. The ssh tunnel takes care of the rest.
Comment: As Michael has described, the idea here is that you're going to send/redirect the ODBC traffic - which would typically be going over the ports you found listed - over a port that isn't blocked by your firewall - in this case over the SSH protocol on port 22.  You shouldn't have to make any modifications to your infrastructure beyond that SSH redirect
Comment: Right now I'm fwding a port to the firewall port, which fwds to the db port:  -> firewall port -> machine w/ db port 22. What you mean is that if I tell my odbc client to use localhost through  the db machine will handle the rest?


Azure Traffic Manager Need to change DNS completely?

Question: We have an on premise infrastructure. We use our own DNS server. To use Azure Disaster Recovery, do we need to change the DNS resolver to Azure? It should be a big impact and risk to change the resolver for the whole on premise infrastructure.
Now:
On premise DNS--->Actual resolver(not Azure)

It has to be necessarily like this?:
On premise DNS-->Azure resolver

Is not that a big change for a on premise datacenter?
Answer: No you do not need to change to Azure DNS in order to use Azure Traffic Manager, there are instances where it might be beneficial but since you have not shared your setup its hard to say if you are hitting any of those use cases.
Comment: If users access to the on-premise with domain "ABC.com", when on premise fails, how will they get to "ABC.com" if the resolvers are not in Azure? I mean, the resolvers are in Mexico, users DNS request will go to Mexico not to Azure.
Comment: I think you are a bit confused, traffic manager will handle the request AFTER your DNS resolves the needed services, normally you use a CNAME in your DNS to point to traffic manager and traffic manager keeps track of any service for that URL on prem or cloud does not matter as long as its publicly available which is a requirement, also just beware  you cannot create CNAMES for apex(root) domains maybe thats your confusion because if thats your use case you hvae to use Azure DNS OR a redirect
Comment: So I need to add a CNAME to our DNS, but will this impact the normal DNS requests today? The normal requests (no failover) will start to ask Azure DNS?
Comment: It depends on your setup, I do not have enough details to say for sure but if setup correctly it wont affect anything else


How do I programmatically get a field's value?

Question: I copied node.tpl.php and I pasted it to node--my_content_type.tpl.php. My content type has a price. How can I get its value as a string?
Comment: Please can you take a little bit more time formulating your questions.  There have been multiple instances where your questions have actually all been the same, and have been posted relatively closely together. The [ask] has some useful tips on asking questions, and the [Help Centre](http://drupal.stackexchange.com/help) is a useful place to go as well.
Comment: For example: You want price field value "2"  to be shown as string  "two" .
Comment: No. If I get price field value 2.0, I want to be shown as string "2.0" or "2".
Answer: Make sure the field is displayed in the display settings of your bundle (admin/structure/types/manage/bundle/display; replace bundle with the machine name of the content type) and define its settings (e.g., delimiter, prefix suffix).

In your template file, add <?php echo render($content['your_field_name']); ?>
Comment: It doesn't work. It's field_name: field value. I want to get only field value·
Comment: Set the label to hidden in your display settings
Comment: I don't understand your directions. Firstly, in my project, url admin/structure/types/manage/bundle/display doesn't exists. Perhaps, may you get some screenshots?
Comment: You don't have to add the field to the display. You can get the field value directly using the $field_machine_name array. Run dpm (if you have devel module enabled) to get the exact structure of the array, it is something like $field_machine_name[0][LANGUAGE_NONE]['safe_value']
Answer: The documentation for node.tpl.php has the following note.

Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node->body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node->body['en'], thus overriding any language negotiation rule that was previously applied.

The description for the $content variable is then the following:

An array of node items. Use render($content) to print them all, or print a subset such as render($content['field_example']). Use hide($content['field_example']) to temporarily suppress the printing of a given element.

So, if the machine name of that field is field_price, you can get its raw value with $field_price, inside the node template file; use render($content['field_price']) to render it.
Answer: You've mentioned that print render($content['field_price']); doesn't work, so if all else fails - I'd use an EntityMetadataWrapper. Although if everything else is failing, then I think you're missing out some vital information and this probably won't work either.
My last resort if all the other suggestions don't work would be preprocessing the node template:
In a module or template.php:
function MYMODULE_preprocess_node(&$vars) {
  if (function_exists('entity_metadata_wrapper')) {
    $wrapper = entity_metadata_wrapper('node', $vars['node']);
    $vars['price'] = $wrapper->field_price->value();
  }
}

Then, in your node.tpl.php you can just write print $price.
This assumes you have the EntityAPI module installed, which is a pretty fair assumption.
If even this doesn't work, then you need to revisit your actual question, because it's badly written somewhere along the lines.
Answer: You can use one of the following code snippets.
 $val = $node->field_price[$node->language][0]['value'];
 print ".$val.";

<?php
  $my_field_items = field_get_items('node', $node, 'field_price1');
  if ($my_field_items) {
    $my_field_first_item = reset($my_field_items);
    $my_field_value = $my_field_first_item['value'];
  }
?>

Comment: You shouldn't access field data directly, use `field_get_items()` or an `EntityMetadataWrapper` instead
Comment: If you're going to use `field_get_items()`, then that snippet would be better in a `hook_preprocess_HOOK` implementation. Then you could just use `print $value;` in your template. That's much better than putting logic in your templates.
Comment: @user19455: Is that what you are asking for?
Comment: Probably yes, but I tried and errors appeared. Maybe, I did something wrong. My field is placed in group named group_photo1 and machine name of my field is field_price1. Could you tell me what shoud I write directly. I will be very grateful.
Comment: then try this $node->field_price1['und'][0]['value'];
Comment: $val = $node->field_price1['und'][0]['value'];
print ".$val.";
Comment: I would be inclined to use `$field_price[$node->language][0]['value']` instead of `und`.
Comment: Yes probably that would be best.
Comment: @user19455: Did that help you?
Comment: What Clive said. I would reverse my -1 to a +1 if the answer primarily recommended either of his suggestions, and discouraged the direct access form.


LogisticRegression - binary classification, "custom threshold"

Question: I have a binary classification problem that I am trying to solve with sklearn's Logistic Regression. I am aware of the fact that the predict_proba() function is apparently only an approximation of the "real" probability and somewhat fuzzy. However, after reading some threads, e.g. here, I was wondering whether I would violate some assumptions about the LR classification by customizing the threshold for the decision.
In the end, my classification problem allows me to make mistakes in one class but preferably not in the other, i.e. maximize the recall for the "important" class.
It appears to be a very intuitive solution to just shift the decision boundary in favor of one class and even have asymmetric decision boundaries. Or to put it differently, only assume the prediction is "correct" if probability > 0.75. Otherwise, don't make a prediction. Also, is this something with a known keyword in the ML world?
Edit:
I should add that the naive solution to classify everything in one class is not applicable (:
Answer: As written in numerous places on this site, logistic regression is a probability estimator.  Any decision you want to make takes the predicted probability from the fitted logistic regression model, applies a utility function you specify, and chooses the decision with the highest expected utility.  The utility should not be incorporated by playing with thresholds for the model (at least not usually).  Having probabilities also gives you the luxury of making no decision at all for class calls.
Comment: Not exactly.  There is value if having a gray zone with 'no decision'.  Utility functions have no notion of 'most probable'.  The utility function can be changed as often as someone changes their utilities, even though you don't change your interpretation of the predicted probability.
Comment: Okay, so what you are saying is that the utility function which decides which class is the most probable should not be changed. Rather, a cut-off can be used where we decide that no prediction is reliable and thus we ignore the predicted label and don't assign a class. Is that correct?

To elaborate a little bit, in my case not making a prediction is equal to assigning a sample to the *important* class. So the idea behind the LR is to reduce the amount of data.
Comment: Fine, I simply misunderstood what a utility function is. Thank you!


Remover caracteres de ponto consecutivos com regex c#

Question: Tenho este texto:
... AAAA ... BBBB ....

Preciso de uma regex que transforme os pontos consecutivos em apenas um ponto, sem remover os espaços:
. AAAA . BBBB .

Fiz uma tentativa:
Regex.Replace("... AAAA ... BBBB ....", @"[\.]*\. *", ".", RegexOptions.Multiline)

Mas está removendo os espaços do início e ficando assim:
.AAAA .BBBB .

Answer: Basta fazer:
Regex.Replace("... AAAA ... BBBB ....", @"\.+", ".")

No caso, \.+ é "um ou mais pontos", e aí basta substituir por um único ponto.
Ou então:
Regex.Replace("... AAAA . BBBB ..", @"\.{2,}", ".")

O quantificador {2,} significa "dois ou mais", então se tiver uma sequência de dois ou mais pontos, eu troco por apenas um. Acho que faz mais sentido, porque se tiver somente um ponto, esta regex nem faz a troca (a anterior faz, o que é redundante, embora dê o mesmo resultado).

Na sua regex você colocou um espaço seguido de *, que significa "zero ou mais espaços", por isso ele também estava removendo os espaços. Mas se quer mantê-los, então não os coloque na regex.
Também removi a opção Multiline, porque segundo a documentação ela só muda o comportamento dos marcadores ^ e $ (além de marcar o início e fim da string, com a opção Multiline eles também indicam o início e fim de uma linha). Mas como a regex não usa nenhum deles, então esta opção não faz diferença, e portanto não é necessária.


CKeditor 5 does not load with Aggregate JavaScript files option

Question: I use Drupal 9.5.5, CKeditor 5 and BootstrapBarrio theme.
When I enable "Aggregate JavaScript files" option in Performance, CKeditor does not load when a user (non admin) edits node.
I uninstalled Advanced CSS/JS Aggregation module also.
Any idea?
Thanks.
Comment: What does the browser console log say?
Comment: Browser console log says:

Uncaught TypeError: t.widget is not a function
Uncaught TypeError: _ref is undefined
Uncaught TypeError: Drupal.editors is undefined
Uncaught TypeError: Drupal.ajax is not a function
Comment: https://www.drupal.org/forum/support/upgrading-drupal/2022-12-22/ckeditor-5-stoped-working-after-an-update-to-drupal-95 describes a similar error, but there is not a solution.
Answer: It seems to be an error with JQuery UI library order
https://www.drupal.org/project/drupal/issues/3222107


What is the logic behind re-serving in volleyball and tennis?

Question: I have seen plenty of times a re-serve being awarded instead of giving the point to any of the team in both volleyball and I think tennis, too.  (I'm not sure if it's still the same in tennis).  I had always felt that a re-serve was an injustice.
What is the real logic behind it? Is it a fair thing?
Answer: In Tennis, if the first serve is not legal a "fault" is declared. If the second serve is again illegal ("double fault"), the other player gets the point. If the ball hits the net cord during the serve, but is otherwise legal, a "let" is declared and the player serves again. There is no limit on the number of lets in a service.
Anyway, a second-serve cannot be an injustice or unfair, because both players adhere to the same rules; if only the player serving first could serve twice or similar, it will be as such, but since both players are allow 2nd-service attempts it is perfectly fair.
As to the logic behind it (in tennis at least), proper serves requires mastering of a difficult technique, and so giving players a 2nd attempt at this allows more margin for error.  This may be why there is no such thing as a "2nd serve" in table tennis; there is no requirement to hit the opposite side of the court, so you can say service is easier.
Comment: You got the question wrong. Isnt Re-serve awarded in situations where the umpire is un sure? Like when the ball hits the line partially, etc
Comment: @Rohit - Not in tennis.
Comment: @Rohit: The umpire's decision is final, whatever they decide. Some matches have [hawk eye](http://en.wikipedia.org/wiki/Hawk-Eye) available, and the player can challenge the decision a set number of times per set.
Comment: I would add that serving into the right location is easy enough.  See the high percentage of second serves that get it right.  However allowing a second serve changes the dynamic of the game and allows players to take bigger risks with the first serve and thus gain more of an advantage.  It is an intentional game mechanic from a sport that wants to see big serves and to have holding serve as the default.

If you remove the rule double faults would not increase massively but return games won would.
Answer: @Matt has covered tennis so I will answer the Volleyball:
In volleyball the re-serve is allowed when there is outside(fan) interference, equipment failure, or some other event, that voids the volley.  If the ball lands on the line then the point is awarded.  If it lands outside the line then it is a side out.  It is the referee's job to make the call.  It used to be that an injury would not stop play but I think that has changed in High School play now.
Answer: Reserve is like serving again(that is the player has to serve once again), the reasons can be anything like the opponent team is not ready or due to some unavoidable disturbances from the audience or you try to serve before referee gives a call.


Articles Details Page Carry

Question: I have articles stored in a database. I want to click on a heading and open the appropriate article in another page on a jQuery Mobile site. The following was my alogorithm of thinking:

Find ID of article
Pass ID to the #news-article page
Display the article where Heading and Body share the same ID

I should also note that I am using a Repeater to display my article on the page:

<asp:Repeater ID="Repeater2" runat="server" DataSourceID="SqlDataSource1">
     <ItemTemplate>

    <a href="#news-body.aspx?id=<%# Eval("ID") %>">

<%# Eval("Heading")%>

<%# Eval("Date")%>

     </ItemTemplate>
</asp:Repeater>

<asp:Label runat="server" ID="Label1"></asp:Label>

I'm a bit stuck here and am seeking some tutorials because I'm new to ASP and .NET. I'm not quite sure what this concept is even called just yet to get good search results. I would appreciate any help you may have to offer. Thank you in advance for your time and help.
Comment: Once I start coding my page2, I get errors. Removing the code in page2 allows me to see the headlines in page1; however, it does receive an error loading the page (to be expected). Is my script even in the correct location for page2? Does that have to be in the ? I'm creating this in jQuery Mobile with navigation using ajax, so I am linking pages with #anchors...
Answer: Try this slight tweak on building your  tag? It's just that you've got to concat your ID to a string of your URL.
<ItemTemplate>

         <a href='<%#"news-body.aspx?id="+Eval("ID") %>'>

<%# Eval("Heading")%>

<%# Eval("Date")%>

 </ItemTemplate>

Comment: I tried tweaking the  tag; but unfortunately, it didn't fix any error. I receive an error that reads: "Lable1.Text = Request.QueryString["ID"].ToString() requires an object reference."  I'm not clear about what this means...
Comment: Not sure if it makes a major difference here, but I am using VB, not C#
Comment: Scratched this whole concept and got my ID passing. Just stuck with the data on details page not showing...Been following this tutorial if interested: http://msdn.microsoft.com/en-us/library/bb530323.aspx
Answer: I finally got it working. Looks like I needed some space away from coding to regroup my eyes. It was the little details in the datasource giving me a hard time and finding WHERE the id is identified and passed over. Thank you all for your help.

Articles Details Page Carry


Problema com Drag Drop ExtJs

Question: Me retorna o seguinte erro quando eu arrasto um "arquivo" para outra "pasta" na tree TypeError: b is null ou TypeError: a is null. Segue o meu código de two trees :
Ext.require(['Ext.tree.plugin.TreeViewDragDrop']);

var storeProc = Ext.create('Ext.data.TreeStore', {
    root: {
        children: [{
            id: 'src',
            text: "Processo1(4)",
            expanded: false,
            children: [{
                text: 'Intimacoes(2)',
                expanded: false,
                children: [{
                    text: 'ArquivoIntimacao1',
                    leaf: true,
                },
                {
                    text: 'ArquivoIntimacao2',
                    leaf: true,
                    cls: 'file'
                }]
            },{
                text: 'Manifestacoes(2)',
                expanded: false,
                children: [{
                    text: 'ArquivoManifestacao1',
                    leaf: true,
                },{
                    text: 'ArquivoManifestacao2',
                    leaf: true,
                }]
            }]
        },{
            text: 'Processo2(0)',
            expanded: false
        }]
    },
    folderSort: true,
    sorters: [{
        property: 'text',
        direction: 'ASC'
    }]
});

var storeArq = Ext.create('Ext.data.TreeStore', {
    root: {
        children: [{
            id: 'src',
            text: 'Arquivos(4)',
            expanded: false,
            children: [{
                text: "Intimacao0",
                leaf: true,
            },{
                text: 'Intimacao1',
                leaf: true,
            },{
                text: 'ArquivoIntimacao1',
                leaf: true,
            },
            {
                text: 'ArquivoIntimacao2',
                leaf: true,
            }]
        }]
    },
    folderSort: true,
    sorters: [{
        property: 'text',
        direction: 'ASC'
    }]
});

Ext.define('Procuradoria.view.menuPrincipal.Processos', {
    extend: 'Ext.panel.Panel',
    requires: ['Ext.layout.container.HBox'],

    title: 'Teste',
    layout: 'hbox',
    width: '100%',
    frame: true,
    items: [{
        id: 'tree',
        xtype: 'treepanel',
        title: 'Arquivos',
        width: '50%',
        border: 0,
        margin: '10 0 0 1%',
        rootVisible: false,
        itemId: 'arq-proc',
        useArrows: true,
        collapsible: false,
        collapseFirst: false,
        collapsed: false,
        hideHeaders: true,
        store: storeArq,
        viewConfig: {
            plugins: {
                ptype: 'treeviewdragdrop',
                appendOnly: true
            }
        }
    },{
        id: 'tree2',
        xtype: 'treepanel',
        title: 'Processos',
        width: '49.9%',
        border: 0,
        margin: '10 1% 0 1%',
        rootVisible: false,
        itemId: 'proc-proc',
        useArrows: true,
        collapsible: false,
        collapseFirst: false,
        collapsed: false,
        hideHeaders: true,
        store: storeProc,
        viewConfig: {
            plugins: {
                ptype: 'treeviewdragdrop',
                appendOnly: true
            }
        }
    }],
    tbar: [{
        id: 'bt-novo-proc',
        xtype: 'button',
        cls: 'x-btn-text-icon',
        icon: imageSource('page_add.png'),
        text: 'Novo',
        handler: function(){
            alert('novo');
        }
    }]

});

Answer: Na configuração do viewconfig não está faltando o ddgroup?
Exemplo:
viewConfig : {
                plugins : {
                    ptype : 'treeviewdragdrop',
                    ddGroup : 'groupx',
                    containerScroll : true,
                    expandDelay : 1000
                }
            }

Que deve aparecer nas duas árvores para que o Extjs consiga identificar entre quais componentes irá ocorrer o drag an drop.
Tente seguir este exemplo.
http://docs.sencha.com/extjs/4.2.2/extjs-build/examples/build/KitchenSink/ext-theme-neptune/#tree-two
Espero ter ajudado

Problema com Drag Drop ExtJs


c++ linked list inside another one

Question: I'm trying to make a linked list inside another one, here is my code
template<typename T>
class List {
private:
    int length;
    class Node {
    public:
        T data;
        Node* next;
    } *head;

public:
    List();
    ~List();

    void insert(T item);
    void remove(T item);
    void empty();
    T* getAll();
    int count() const;
};

template<typename T>
void List<T>::insert(T item)
{
    if (head == NULL)
    {
        head = new Node();
        head->data = item;
        head->next = NULL;
        length = 1;
        return;
    }
    Node* p = new Node();
    p->data = item;
    p->next = head;
    head = p;
    ++length;
}

struct Remainder {
    Date dt;
    List<int> notes;
};

void getDayEvents(Date dt, List<Remainder> l)
{
    Remainder* arr = new Remainder[l.count()];
    arr = l.getAll();
    for (int i = 0; i < l.count(); i++)
    {
        if (arr[i].dt.day == dt.day && arr[i].dt.month == dt.month &&              arr[i].dt.year == dt.year)
        {
            int* nArr = new int[arr[i].notes.count()];
            nArr = arr[i].notes.getAll();
            for (int j = 0; j < arr[i].notes.count(); j++)
            {
                cout << nArr[j] << endl;
            }
        }
    }
}

int _tmain() {
    Date dt1, dt2;
    dt1.setDate(17, 7, 2015);
    dt2.setDate(5, 11, 2015);

    Remainder r1, r2;
    r1.dt = dt1;
    r1.notes.insert(1);
    r1.notes.insert(2);
    r2.dt = dt2;
    r2.notes.insert(5);

    List<Remainder> l;
    l.insert(r1);
    l.insert(r2);

    getDayEvents(dt1, l);

    //----------------------------------------------------------
    int pause;
    cin >> pause;
    return 0;
}

just when insert r1 or r2 in the list, the data inside lists of notes inside each remainder just disappeared or destroyed
I don't know why? Where is the mistake?
Comment: For clarification are you writing a single linked list or double linked list?
Comment: Welcome to Stack Overflow. You haven't given us enough code to reproduce the error (e.g. what is `Date`?), which makes our job much harder. Also, you could probably simplify this code a good deal and still have a working example of the error. (This is what ["minimal complete example"](http://stackoverflow.com/help/mcve) refers to.) Finally, if you develop new functionality in isolation, you'll have fewer problems like this.
Comment: Can you show more of your source; Date is either a class or struct and don't see any implementation, and for you List class, you do not show any of your implementation there either. It is hard to tell where your error could be.
Comment: i added the implementation of insert method of the list and the date class declaration. Do you need any more info ? .. thanks for giving help :)
Comment: I edited your original post to improve formatting for better readability. Only visible to me until it is approved by peer review.
Comment: now better i think :) thanks
Comment: It makes it harder to read without the indentation.
Comment: when i debug the code, i found that the notes data destroyed just when i return form the insert method while inserting the remainder in the list
Comment: i don't understand the question but in general i implemented one class linked list with T type, then i've made one instance as list of Remainder that has also a list of string inside
Comment: A single link list has a forward pointer only as in head -> e1 -> e2 -> e3 -> tail where a double linked list has head < = > e1 < = > e2 < = > e3
Comment: I also do not see your insert() method
Comment: head -> e1 -> e2 -> e3 -> NULL
Comment: Ah ok so a single linked list
Comment: just when finish insertion of the remainder the data inside the notes list inside just disappeared
Comment: i noticed that i just can't do like this
    List x, y;
    x.insert(1);
    x.insert(2);
    y = x;
Comment: may be i should implement what assignment operator should do ?
Comment: Is there something wrong with `std::list > >`?
Answer: You're passing your objects into the insert function by value.
That means copy constructors and destructors are being called.
You did not declare the copy constructor of List so it's presumably
being generated by the compiler, and presumably is making a
"shallow" copy of the List when the copy constructor
of Remainder makes copies of the members of the input Remainder.
I think this copies the pointer head from one List to another
so that now you have
two List objects whose head pointers point to the same object.
You haven't shown the definition of the List destructor,
but depending on what you do in that destructor it could be deleting
a Node that the destroyed List points to while another List
still has a pointer to the same Node.
That may sound confusing, and frankly I'm not sure I can count the
invocations of constructors and destructors correctly myself,
so best to just make sure they can never be used unsafely.
A good start might be to define your own copy constructor and
operator = for List in such a way that the new List has
newly-allocated copies of everything that was in the old List.
Never let two head pointers point to the same object.
After you've inserted one List into another, you should be able to
confirm in the debugger that the new copy of the List

c++ linked list inside another one


custom checkout pane submission

Question: I'm using Drupal Commerce (7.x-1.4) + Commerce Coupon (and old version 7.x-1.0-beta6)
I'm using a custom checkout pane to handle my coupons redeem (we have a particular usage of coupons) and manually call the coupon redeem function after checking some stuff.
It works perfectly fine except that i cannot figure out how to make sure my custom pane form submit button doesn't trigger the whole form (and trigger all the checkout pane validations), but only my particular form
<code>    function hook_my_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
    $order = $form_state['order'];
    $pane_form = array();
    $pane_form['ticket_code'] = array(
        '#type' => 'textarea',
        '#title' => 'Tickets',
        '#description' => 'Blahblah',
        '#rows' => 10,
    );

    $pane_form['submit_ticket'] = array(
        '#type' => 'button',
        '#value' => t('Submit my tickets'),
        '#validate' => array('_my_custom_ticket_validate_order'),
        '#submit' => array('_my_custom_ticket_submit_order'),
    );

    $pane_form['coupon_code'] = array(
        '#type' => 'textfield',
        '#title' => 'Coupon code',
        '#description' => 'Enter your coupon',
    );

    $pane_form['submit_coupon'] = array(
        '#type' => 'button',
        '#value' => t('Use my coupon'),
        '#validate' => array('_my_custom_coupon_validate_order'),
        '#submit' => array('_my_custom_coupon_validate_order'),
    );

    return $pane_form;
}
</code>
So this works ! Except that when I click on one of the submit button, it triggers the validation of the other checkout panes on the page.
I would like to prevent this as the user is redirected to the same page after using his coupons / tickets anyway.
How can I prevent this ?
Many thanks !
Answer: The short answer is you can't do what you want, but there are other things you can do. You need to look into using the #ajax properties of form elements to submit data to the server when the customer clicks your button without initiating a POST redirect as you would for a full form submission.
However, that will still trigger a validation of the entire form, not just the pieces that you specifically want to validate. What Drupal allows you to do is limit validation errors from resulting in form errors when the form is rebuilt.
The topic is honestly a big bigger than can be answered here, but I hope this points you in the right direction. The best thing to do will be to investigate how a module with similar functionality achieves what it is you want to do and imitate the code (if it's up to date and / or well-maintained ; ).

custom checkout pane submission


Datatables exportar para Excel e formatar uma coluna texto como moeda (contábil)

Question: Estou tentando converter uma coluna numérica 8.5 em moeda contábil (R$ 8,50) quando utilizo exportar Excel do jQuery Datatable, mas não obtive sucesso.
Minha coluna está assim:
{
        "data": "Valor2", "orderable": true, "render": function (data, type, full, meta) {
                var valor = full.Valor.replace(',', '.');
                return parseFloat(valor);;
        }
},

Comment: Quando você fazer o replace, ele gera um erro, ou simplesmente não fica no formato que você quer?
Comment: Ele vai para o excel como formato "Geral", então quando utilizo a função soma, ele não consegue somar. Queria exportar com formato contábil
Comment: Porque você colocou um código, no qual você usa replace, este replace funciona? Ou esta modificação não funciona?
Comment: Esse código que coloquei do replace seria para converter o texto 8,5 por exemplo em 8.5, sendo possível assim, transformar o texto em float. O que eu queria agora era transformar esse float em moeada quando gerar o excel.
Answer: Para que ele seja reconhecido como moeda você coloca ao parâmetro type com o valor currency
{
    "data": "Valor2", "orderable": true, "type": "currency"
},

Esse plug-in fornecerá classificação numérica para colunas de moedas
  (detectadas automaticamente com o plug-in de detecção do tipo de moeda
  ou definidas manualmente), levando em consideração o símbolo monetário
  ($ ou £ por padrão).
O DataTables 1.10+ possui habilidades de classificação de moeda
  embutidas e será detectado automaticamente. Como tal, esse plug-in é
  marcado como obsoleto, mas pode ser útil ao trabalhar com versões
  antigas do DataTables.

Documentação
Comment: sim, infelizmente desisti do datatable e resolvi usar uma lib pra gerar o excel, mas obrigado pela ajuda
Comment: Infelizmente não funcionou pra mim.
Comment: Você viu isso? a = (a==="-") ? 0 : a.replace( /[^\d\-\.]/g, "" );
        return parseFloat( a ); na documentação?
Comment: sim, eu vi.... fiz exatamente como mostra na documentação, porém no excel continua como texto
Comment: já tentou deletar o arquivo para ver se ele esta criando um novo?
Answer: Supondo que os números no json de origem venham formatados em português;
Por exemplo:
Salary:  162700,00

Foi utilizada uma rotina (fnTextoNumericoParaFloat) para fazer substituição de:

pontos "." por espaço vazio ""
virgulas "," por ponto "."

Para forçar o formato americano dos dados da tabela na hora de exportar para o Excel.
No meu caso, os valores foram salvos corretamente como número;

Answer: Sei que o post é antigo mas como não vi nenhuma resposta que considero correta, aqui deixo minha visão.
Pelo oque entendi vc deseja pegar o formato de "8.50" e passar para "R$8,50", e depois exportar a tabela para Excel. Vamos por parte então:
1) Passando de  "8.50" para  "R$8,50"
Esse tipo de procedimento deve ser feito usando a propriedade do propio DataTable 'columnDefs' e não 'forçando' através de uma renderização externa pois caso contrario vc não vai conseguir por exemplo mandar o Data table fazer a soma dos valores ou exportar para excel ou pdf com a mascara correta.
No seu código procure a propriedade 'columnDefs', caso não tenha criado pode criar, vai ficar tipo assim
    -- ...codigo anterior do DataTable---

    pageLength: 50,
    responsive:true,
    data: dataSet,
    columnDefs: [
                { "width": "7%", "targets": 0 }, //defini manualmente o tamanho da coluna
                { "width": "5%", "targets": 1 }, //defini manualmente o tamanho da coluna
                { "width": "5%", "targets": 2 }, //defini manualmente o tamanho da coluna
                { "width": "7%", "targets": 3 }, //defini manualmente o tamanho da coluna
                { "width": "7%", "targets": 4 }, //defini manualmente o tamanho da coluna
                {"render": function(data){       //responsavel por 'renderizar' a coluna que vc deseja aplicando o filtro R$
        return parseFloat(data).toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});
        },"targets": 4
      }
      ],
      columns: [
               { title: "Tipo" },
               { title: "NºDoc" },
               { title: "Pedido" },
               { title: "Emissão" },
               { title: "Valor" }
               ]

--.... resto do código do seu DataTable ....--

Repare que a parte responsavel por aplicar o filtro fica dentro da propriedade 'columnDefs', 'render'.
{"render": function(data){       //responsavel por 'renderizar' a coluna que vc deseja aplicando o filtro R$
        return parseFloat(data).toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});
        },"targets": 4
      }

Aqui vc aplica corretamente a mascara e usa o comando 'targets' para apontar para qual coluna vc deseja estar aplicando
*obs:*Caso vc quisesse aplicar essa formatação para várias colunas bastaria vc colocar as colunas q deseja em array, tipo assim
   {"render": function(data){       //responsavel por 'renderizar' a coluna que vc deseja aplicando o filtro R$
            return parseFloat(data).toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});
            },"targets": [4,5,8]
          }

Lembrando q a primeira coluna vc conta 0, pois estamos trabalhando com array aqui
2)botão de exportação Execel
Eu não sei como foi feito o botão de exportação... porém eu faço da seguinte maneira:
    --- ... código do dataTable ...--
columns: [
         { title: "Tipo" },
         { title: "NºDoc" },
         { title: "Pedido" },
         { title: "Emissão" },
         { title: "Valor" }
         ],
         dom: 'Bfrtip',
         altEditor: true,
         buttons: [
                    {
                     text: 'EXCEL',
                     extend: 'excel',
                     exportOptions: {
                       modifier: {
                       page: 'current'
                       }
                      }
                     },
                   ]

-- ...resto do código do DataTable...---

E por fim mais não menos importante, lembre-se q vc dever importar as bibliotecas pertinentes caso não tenha, caso resolva fazer isso via cdn vai fica assim:
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.6.1/css/buttons.dataTables.min.css"/>

Prontinho!! parece muito mas não é. Com isso vc aplicou a mascara de dinheiro como manda a documentação e fica livre para manipular os valores da coluna sem se preocupar com isso.


How to query entity by generated ID

Question: The case
I'm kinda new to Google Cloud Datastore and am learning from their docs and tests under NodeJS.
datastore.save([ entity ], (error, apiResponse) =>
{
    console.log('---', key);
    console.log('---', error);
    console.log('---', apiResponse);
    datastore.get(key).then(([entity]) =>
    {
        console.log('+++', entity);
        console.log('+++', entity[DatastoreClient.KEY] === key);

        let query = datastore.createQuery(kind).filter('__key__', '=', datastore.key(kind));

        datastore.runQuery(query).then(([entity]) =>
        {
            console.log('...', entity);
        }).catch(console.log).then(() =>
        {
            done();
        });
    });
});

The saved entity output in the console is similar to
{
    a: 'Aa',
    z: 'Zz',
    [Symbol(KEY)]: Key {
        namespace: undefined,
        id: '30',
        kind: 'mch-gw/healthz/jgtdjd6h',
        path: [Getter]
    }
}

The issue
It also happens that few lines down, when I run the query, I get
Error: 3 INVALID_ARGUMENT: Key path element must not be incomplete: [mch-gw/healthz/jgtdjd6h: ]

I do understand that my key don't have to be incomplete, but how to avoid ?
What's the original purpose ?
As you can see the above output for saved entoty, there is an id field which value is '30'.
I want to be able to search by that id generated value.
Thanks to all in advance !!
Answer: No need for even query, since kind and id are known
datastore.save([ entity ], (error, apiResponse) =>
{
    console.log('---', key);
    console.log('---', key.path);
    console.log('---', error);
    console.log('---', apiResponse);

    const id = apiResponse[0].mutationResults[0].key.path[0].id;
    // note however, that if the entity is to be updated: ie it already have
    // entity[DatastoreClient.KEY] as a complete key, then
    // null === apiResponse[0].mutationResults[0].key;

    // also note that this `id` value need to be parsed as int...
    // since it is auto-generated by google-cloud-storage engine
    // and YES, even though output of entity seems to show it as a string
    // it costed me 06h testing à vue, stumbling and messing in order to figure it out, so beware
    const _key = datastore.key([kind, +id]);
    datastore.get(_key).then(([entity]) =>
    {
        console.log('+++', entity);
    }, console.log).then(done);
});

And the fetch output is as expected
{
    a: 'Aa',
    z: 'Zz',
    [Symbol(KEY)]: Key {
        namespace: undefined,
        id: '42',
        kind: 'mch-gw/healthz/jgtdjd6h',
        path: [Getter]
    }
}

How to query entity by generated ID


Proof of $A = \{x \mid f(x) \leq g(x)\}$ is closed in X

Question: I am facing trouble in the following problems in Munkres:
Let $X$ be a topological space. Let $Y$ be an ordered set with its order topology. let $f, g : X \rightarrow Y$ be continuous. Show that the set $A = \{x \mid f(x) \leq g(x)\}$ is closed in X.
I found a solution which is as follows:
The complement of $A$ in $X$ is
$X − A = \{x \mid g(x) < f(x)\}$. We will show that $X − A$ is open. Suppose that $ X − A$ is non-empty and pick an arbitrary element $x_{0} \in X − A$. Let $a$, $b$ and $c$ be elements in $Y$ such
that $a \leq g(x_0) < b \leq f(x_0) \leq c$. In the order topology, $[a, b)$ and $[b, c]$ are open sets. Because $ f $ and $g$ are continuous, $g^{-1}([a, b))$ and $f^{-1}[b,c)$ are open in $X$. Their intersection is an open neighborhood of $x_0$ which is entirely contained in $ X − A$. Since $x_0 $is an arbitrary element of $X − A$, we conclude that $X − A$ is open.
Link for the solution: http://www.personal.psu.edu/auw4/math429-practice1.pdf
Is this the correct solution?
Because if $b= f(x_0) = c$, then $[b,c] = \{c\}$ is not open in $Y$.
Please advise me.
Comment: Why are $[a, b)$, $[b, c]$ open?
Comment: I think if there exist a smallest element in $Y$, denote it by $a$. then $[a,b)$ is open in $Y$ (in the order topology).
Comment: But the proof is obviously wrong for e.g. $Y = \mathbb R$.
Comment: $[a,b)$ need not be open, but $(a,b)$ is and that is enough. Likewise for $(b, c)$ instead of $(b,c]$. But $b$ inbetween need not exist, as not all order are order dense...If $a$ exists $a$ and $c$ are unnecessary just use subbasic $(\leftarrow, b), (b, \rightarrow)$ instead...
Answer: No the solution is not completely correct. You'll have to consider cases.

There is no element of $Y$ between $g(x_0)$ and $f(x_0)$; then $(\gets,g(x_0)]$ and $[f(x_0),\to)$ are disjoint open sets around $g(x_0)$ and $f(x_0)$ respectively and the intersection of their preimages works
There is a $b$ between $g(x_0)$ and $f(x_0)$; then $(\gets,b)$ and $(b,\to)$ are disjoint open sets around $g(x_0)$ and $f(x_0)$ respectively and the intersection of their preimages works.


MVC ViewModel EntityFrameWork ICollection,IEnumerable virtual Class

Question: I have gone through a lot of documents and found several ways of trying to make a CreateViewModel.
I want to know what does ICollection Does.
public Payment{
   public int ID {get; set;}
   public string Details {get; set;}
   public virtual ICollection<Expense> Expenses {get; set;}

}

public Expense{
   public int ID {get; set;}
   public string MyDetails {get; set;}

}

So I guess in my View, I can Use just the plain class as virtual to make a Create Method. But if I want to use ViewModel to make a view with 2 or more DataModels for Creation. How will I go with that. Cause I guess I can always just make a
public virtual Payment payments {get; set;}
public virtual Expense expenses {get; set;}

But I am trying to ready this for Dynamically Having a Add Button Generating an Expense Details Input.
Not to mention, the IEnumerable as well, but I guess this needs an ID more suitable for Editing and Details for what I understand.
Answer: All you need is a PaymentViewModel class, where you'll use List<Expense> instead of ICollection<Expense>:
public class PaymentViewModel
{
    // ID property unnecessary here because it doesn't need
    // to be posted from the form

    public string Details { get; set; }

    // You may want to use something like `List<ExpenseViewModel>`
    // based on your needs
    public List<Expense> Expenses { get; set; }
}

With that, you add additional expense records to your form by making sure the input names are in the format of Expenses[N].MyDetails, where N is the index. Whatever JavaScript solution you use to add additional expense records to the form should create these inputs with properly indexed names. This would be a good place to use a JavaScript templating solution, or something that handles data-binding like Knockout.
For editing existing expenses, should you have the need, you just generate the fields like with any collection, but you need to use a for loop rather than the more traditional foreach:
@for (var i = 0; i < Model.Expenses.Count(); i++)
{
    @Html.EditorFor(m => m.Expenses[i].MyDetails)
}

As a side note, since you asked, ICollection<T> is the required type for entity navigation properties with Entity Framework. These reasons are very low level, but has to do with the way Entity Framework handles one-to-many and many-to-many relationships at an object level and issues such as lazy loading. However, ICollection<T> doesn't work for actually submitting items through an HTML form, due mostly to the fact that it's not indexable. That's why a view model is so important in this scenario.
Comment: Omg, makes perfect sense. Thank you!!


MySQL Syntax Error while adding user with IPv6 Address

Question: I am trying to create a SQL user on Server A so the Server B can access SQL server of Server A using IPv6 but for some reason I am getting syntax error while running create user command.
The Query I am trying to run:
MariaDB [(none)]> CREATE USER 'dbusr2'@'2600:3c00::f03c:91ff:fe24:8266' IDENTIFIED BY 'sd6@fs54sd4d';

Getting syntax error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual thatc00::f03c:91ff:fe24:8266' IDENTIFIED BY 'sd6@fs54sd4d'' at line 1 use near ':3c

Output of ip -6 addr show on Server B
root@debian:~# ip -6 addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 state UNKNOWN qlen 1
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
    inet6 2600:3c00::f03c:91ff:fe24:8266/64 scope global mngtmpaddr dynamic
       valid_lft 2591996sec preferred_lft 604796sec
    inet6 fe80::f03c:91ff:fe24:8266/64 scope link
       valid_lft forever preferred_lft forever
root@debian:~#

Since I am very new to IPv6 am I missing something here?
Comment: There has been issues with MySQL IPv6 support, so you need to check your MySQL version and see if newer versions fix IPv6 issues.
Answer: I think the problem you are seeing is caused by the 'magic quotes' you are using, this seems to work
CREATE USER 'dbusr2'@'2600:3c00::f03c:91ff:fe24:8266' IDENTIFIED BY 'sd6@fs54sd4d';

Note that this uses standard single quotes.
Comment: silly mistake. new to MacOS :)


Best books to self study number theory and especially diophantine equations?

Question: I'm an undergraduate math student. I've already passed linear algebra and abstract algebra and recently passed a course in elementary number theory and I really enjoyed it. (Our source was Daniel Flath's "Introduction to Number Theory" and Kenneth Rosen's "Elementary Number Theory".)
Now, I want to self-study more books this semester and I'm searching for good books with exercises. My main interest is in solving diophantine equations and their applications.
Thanks for your suggestions and sorry for my bad English. :)
Comment: https://bookstore.ams.org/mbk-105/
Comment: you may take a look at https://web.math.pmf.unizg.hr/~duje/numbertheorybook.html
Comment: Do you mean Daniel Flath's *Introduction to Number Theory* or Rosen's *Elementary Number Theory* or both?
Answer: If you are interested in arithmetic geometry and the theory of elliptic curves (Diophantine equations with geometry involved) then I can recommend The Arithmetic of Elliptic Curves, written by Joseph H. Silverman. It may or may not be a little difficult to read, but it is a rewarding journey.

About the Book
The first two chapters is preliminaries from algebraic geometry. If you don't know this theory from before, then you may spend a little time on these two chapters and you may also want to learn from another source.
The next two chapters is about the understanding of the geometry of elliptic curves and the group structure one can give on the points of an elliptic curve, this gives rise to a Projective Group Scheme.
The next five chapters spends time to look at elliptic curves defined over different fields and arithmetic objects.
Some things you will see are (among other things):

How elliptic curves over the complex numbers relates to elliptic integrals and elliptic functions.
The Weil Conjectures for elliptic curves. You define a generating function which encodes the number of points of the elliptic curves defined over finite fields. This object is called a $\zeta$-function. The Weil Conjecture is then a list of statements regarding this newly defined object.
See the Mordell-Weil Theorem for elliptic curves defined over the rational numbers. This means that you can find a finite list of rational points of the elliptic curve, from which you can generate all other points. This is an important result in the foundations of the Birch and Swinnerton-Dyer conjecture. This conjecture gives a fascinating relationship between arithmetic, geometry and analysis, I think.
How Elliptic Curves relates to problems in Diophantine Approximations

I think the book is great, but it can be a little bit difficult to read - perhaps.
$\text{ }$
If you want something slightly easier, then you maybe want to have a look at Rational Points on Elliptic Curves, which is by Silverman and John T. Tate.

Bonus Section
The Birch and Swinnerton-Dyer Conjecture is a great motivation for studying elliptic curves and their arithmetic properties. For that reason, I also want to add an extra book which I think is a really good introduction to that conjecture. The book is called  Elliptic Tales: Curves, Counting, and Number Theory and is written by Avner Ash and Robert Gross. It begins at a very elementary level and successively builds up to the conjecture. It is entertaining and describes most of the concepts in a non-technical language.
Comment: Thank you very much, sir.
Answer: I recommend the book written by Davenport; A higher arithmetic: An Introduction to the Theory of Numbers. He wrote this book with the intention that a high school student should be able to understand it.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://math.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://math.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/2067796)
Comment: Thank you for letting me know. I edited the comment I made above


Factor dependent correlation

Question: If I take a set of measurements and test correlation of variable $A$ vs variable $B$ and get a significant correlation, that makes sense to me.  But what if further analysis reveals that of those factors, there is only a significant positive correlation within one group, and that group is over-represented.  Is the global correlation still valid, or is it, upon more detailed inspection a sample-bias effect?
Here is some graphs to explain:
The global correlation

The group separated correlations
Comment: Just a little comment: it looks like the overall correlation might partly be explained by the fact that units belonging to group A all have lower scores whereas considering `valueB` alone doesn't help to separate the three groups.
Comment: I think if you give us more content (i.e., what do the groups mean) you will get better advice on what to do.
Answer: Are you familiar with Simpson's paradox? This would seem to be what you're observing here.
Edit: I didn't answer your question :) What exactly you should do is to some degree context dependent (Are the groups meaningful? Does this represent a problem in the study design? etc). At the very least you should report both results IMO.
Answer: I agree with JMS advice, that the answer is totally context dependent.
But what you are looking at may also be considered a moderation effect.

In statistics, moderation occurs when
  the relationship between two variables
  depends on a third variable.

(quoted from wikipedia)
A moderation is statistically significant if in a multiple regression analyses the interaction of the predictor with the third variable is significant.
Answer: The previous comments are all good, but with group sample sizes of 5, 7, and 11, I wouldn't trust any of their correlations as far as I could throw them.  You'll need to give the overall r a wide confidence interval as well.  btw Nice job on the graph.
Comment: +1, good point. I took it as an example, not the actual data, but reading again the OP certainly didn't say that.

Factor dependent correlation


Solving coupled ODE system with one eigenvalue

Question: I have the coupled system:
$$
\left\{
\begin{array}{c}
dx/ds=p_1 \\
dp_1/ds=-x
\end{array}
\right.
$$
I Tried solving it with the change of coordinates (eigenvalue, eigenvector) approach, but I ended up with one eigenvalue: $$\lambda = i$$
Therefore I do not know how to form my decoupling matrix, because AFAIK there are 2 methods for building it: finding the inverse matrix of the eigenvector matrix or making a diagonal matrix with the eigenvalues on the main diagonal. Since there is only one eigenvalue, the eigenvector matrix is not square and it has no inverse matrix and using the other method just produces a single number: i, which would not decouple the system.
Is there any other approach for building the decoupling matrix?
If there is not, what other method could I use, to solve the initial problem?
Thank you!
Comment: You can still diagonalize this system using both the eigenvalue $i$ and the eigenvalue $-i$. These each have one linearly independent eigenvector so you can proceed in the usual way (though you will need to deal with complex number arithmetic). You can save some calculation by noticing that if $A$ is real $v$ is an eigenvector $\lambda$ then $\overline{v}$ is an eigenvector with eigenvalue $\overline{\lambda}$.
Comment: This of course does not work as given for a matrix that is actually nondiagonalizable like $\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}$; in these cases you need to know the exponential of larger Jordan blocks.
Answer: So, @Ian's comment made me do my calculation once again, which led me to the conclusion, that I was wrong before and the system actually has 2 eigenvalues $$ \lambda_1 = 1 \ \ and\ \lambda_2 = -1 $$
Therefore, I can use the usual algorithm and the impediment is gone.


Unbiased Metropolis-Hastings estimator of the form $\frac{\sum_{i=1}^nW_if(Y_i)}{\sum_{i=1}^nW_i}$. How do we need to choose $W_i$?

Question: Let $(X_n)_{n\in\mathbb N_0}$ be the Markov chain generated by the Metorpolis-Hastings algorithm with proposal kernel $Q$ and target distribution $\mu$ and $(Y_n)_{n\in\mathbb N}$ denote the corresponding proposal sequence. Say we want to consider an estimator $A_nf$ for $\mu f$, $f\in L^1(\mu)$, of the form $$A_nf=\frac{\sum_{i=1}^nW_if(Y_i)}{\sum_{i=1}^nW_i}.$$

How do we need to choose the weights $W_i$ if $A_nf$ is supposed to be an unbiased estimator?

Assume $Q$ and $\mu$ admit densities $q$ and $p$ with respect to a common reference measure $\lambda$. In this paper, it is claimed that, assuming $\{p>0\}\subseteq\{q(x,\;\cdot\;)>0\}$ for all $x$, $W_i=\rho(X_{i-1},Y_i)$, where $$\rho(x,y):=\begin{cases}\displaystyle\frac{p(y)}{q(x,y)}&\text{, if }p(y)>0\\0&\text{, otherwise}\end{cases},$$ is a possible choice.

How do we prove that the estimator is unbiased with this choice of $W_i$? And are other choices of $W_i$ possible? I could imagine that $W_i$ might depend on $X_0,\ldots,X_{i-1},Y_1,\ldots,Y_i$.
Comment: To clarify - do you want to show unbiasedness for finite $n$, or asymptotic unbiasedness as $n \to \infty$?
Comment: @πr8 Ah, I guess with the choice in the paper the estimator is only "asymptotically unbiased" (just to be sure, this is supposed to mean that a strong law of large numbers hold, right?). In any case, I'm interested in both.
Comment: Yes, correct - in the paper, the estimator is asymptotically unbiased, and so an SLLN holds.
Answer: A partial answer: in the paper you reference, the unbiasedness is essentially a byproduct of the equality
\begin{align}
\int \int p ( x ) q ( x, y ) \cdot \rho ( x, y ) g ( y ) \, dx \, dy &= \int \int p ( x ) p ( y )  g ( y ) \, dx \, dy \\
&= \int p ( y ) g ( y ) \, dy.
\end{align}
Note that:

Finite-time unbiasedness will generally not hold, unless the Markov chain is initialised at equilibrium (i.e. with a draw from $p$), which is typically difficult.
Moreover, the importance sampling estimator you include is a ratio of estimators, which typically makes it difficult to establish unbiasedness for finite $n$. Fortunately, this is usually less of an issue when considering $n$ going to $\infty$.

If I remember correctly, it's also the case that the weights used in the paper are not quite $\rho = p / q$, but a constant multiple of this expression, where the constant is unknown. This doesn't get in the way of showing unbiasedness, but does explain why the ratio-type estimator is used; one is doing something a bit closer to self-normalised importance sampling.
To make other choices of weights, the following advice might be useful:

To obtain unbiasedness, one should construct weights $\rho$ which admit some sort of simplification, as in the integral expression at the beginning of this answer.
When performing importance sampling, one is comparing a distribution which you can sample from to one from which you cannot sample. The latter is usually your target distribution, i.e. $p$, and the former is some distribution which you have algorithmic access to. As such, it is simpler to think in terms of 'which importance distributions are available for me to sample from?' rather than 'which importance-weighting scheme should I use?'.
Basic importance sampling generally performs worse as the dimensionality of the problem increases, and so in some sense, you would like your importance distribution to be as low-dimensional as possible. As such, if one constructed importance weights involving more points (e.g. looking at $\{ X_{t-2}, X_{t-1}, Y_t \}$, then one could reasonably expect the weights to become more singular, and worsen the variance of the estimator.
Comment: Regarding the weights: Note that they don't assume $p$ to be a probability density and hence need to normalize it. So, the $p$ in my question is the already normalized density.
Comment: @0xbadf00d Okay - note that it will then usually be the case that you cannot evaluate $p$ directly, because of this normalisation, hence the need for the ratio estimator.
Comment: Sure. I only didn't want to make this question more complicated.


Confused how the SVD calculation chooses the correct axes to project onto

Question: I'm learning about singular value decomposition, and I think I have a decent understanding of how $A = U \Sigma V ^{T}$ is derived, but I'm having trouble understanding how the actual calculation chooses the "best" singular value axes to project $A$ onto.
In order to calculate the matrices $U$, $\Sigma$, and $V ^{T}$, I first solve for the eigenvalues and eigenvectors of $A^{T}A$.  From my -- admittedly not great -- understanding of eigenvectors, the eigenvectors of $A^{T}A$ are then used to construct $V$, as in the formula $A^{T}AV = U\Sigma^2$.
Now the formula $AV = U\Sigma$ is projecting $A$ onto $V$, right?
Assuming everything I've said is correct, I'm confused why $V$, which is an eigenbasis for $A^{T}A$, is able to be used as the axes to project $A$ onto in the singular value decomposition.  To put it another way; why are we able to use eigenvectors of $A^{T}A$ as eigenvectors of $A$?
I'm probably wrong about something that I've stated above, but I'm not sure what.
EDIT: I realize my original question was unclear, so here's what I hope is a better explanation:
Here is a graph of the $V$ matrix for the SVD of a set of four 2-dimensional points.  The first vector in $V$ gives the axis that $A$ should be projected onto to give the maximum variance between points in $A$.  The second axis in $V$ is orthogonal to the first axis.
So my question is: how does the SVD calculation "know" how to choose the best axes to project onto?  Since $V$ is constructed from the eigenvectors of $A^{T}A$, how does that result in the best projection axes for $A$?  In other words, how does the SVD calculation know to pick this specific set of orthogonal vectors, instead of any other set of orthogonal vectors that results in a worse SVD projection of $A$?
Comment: The eigenvectors of $A^{T}A$ aren't the eigenvectors of $A$  as $A$ is typically non-square. They're called the right singular vectors.
Comment: Then what I don't understand is since $V$ is constructed with the the eigenvectors of $A^{T}A$ (and not $A$), why is $V$ then the best basis to project $A$ onto (assuming I'm correct that that's what's going on)?
Comment: https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues
Comment: The SVD is unique up to sign of the vectors in $V$ and $U$...it's not like it's choosing anything.
Comment: some edits...showing the choice of reflector $F$
Answer: This may not answer your question as much

Assuming everything I've said is correct, I'm confused why $V$, which is
  an eigenbasis for $A^{T}A$, is able to be used as the axes to project A
  onto in the singular value decomposition. To put it another way; why
  are we able to use eigenvectors of $A^{T}A$ as eigenvectors of $A$?

They're not eigenvectors. They're the right singular vectors because a non-square matrix doesn't have eigenvectors.

In order to calculate the matrices $U$, $\Sigma$, and $V ^{T}$, I
  first solve for the eigenvalues and eigenvectors of $A^{T}A$.  From my
  -- admittedly not great -- understanding of eigenvectors, the eigenvectors of $A^{T}A$ are then used to construct $V$, as in the
  formula $A^{T}AV = U\Sigma^2$.

This doesn't work. Note that if I take $$A^{T}AV V^{*}  = U \Sigma^{2} V^{*} \\ A^{T}A = U \Sigma^{2} V^{*}  = U \Lambda V^{*} $$
The steps are
$ \textrm{1. Form }  A^{*}A $
$ \textrm{2. Compute the eigenvalue decomposition of }  A^{*}A  = V \Lambda V^{*} $
$ \textrm{3. Let }   \Sigma  \in \mathbb{R}^{m \times n}  $ be the non-negative diagonal square root of $\Lambda$
$ \textrm{4. Solve the system }   U\Sigma = AV $ for the unitary $U$ (e.g. using the QR factorization)
How is this done? There are few ways to accomplish it. One way is using Householder reflectors but you could simply form the eigendecomp of $AA^{T} = U \Lambda U^{*}$ and take $U$ but I'm pretty this isn't a good method computationally.

If you're taking numerical linear algebra this is the same way you get the matrix to Hessenberg form.

So my question is: how does the SVD calculation "know" how to choose
  the best axes to project onto?  Since $V$ is constructed from the
  eigenvectors of $A^{T}A$, how does that result in the best projection
  axes for $A$?  In other words, how does the SVD calculation know to
  pick this specific set of orthogonal vectors, instead of any other set
  of orthogonal vectors that results in a worse SVD projection of $A$?

The SVD is unique up to the sign of the vectors in $U,V$. It isn't choosing anything. In the actual computation you successfully apply Householder reflectors. What do they look like?
Like above this is called bidiagonalization. We take $A$ and do the following.
$$ Q_{n}\cdots Q_{1} A = R  $$
Thus $A=QR$ ...It looks like this...
Where $Q_{k}$ is given as
$$ Q_{k} = \begin{pmatrix} I & 0 \\ 0 & F \end{pmatrix} $$
$I \in \mathbb{C}^{(k-1) \times (k-1)}$ is an identity matrix and $ F \in \mathbb{C}^{(m-k+1) \times (m-k+1)} $ is a unitary matrix. When we apply this reflector $F$ to a vector $x \in \mathbb{C}^{m-k+1}$ it zeros everything most of the vector.
$$  x  = \begin{pmatrix}  x_{1} \\ \vdots \\ x_{m-k+1} \end{pmatrix}  \stackrel{F}{\to} Fx  = \begin{pmatrix}  \|x \| \\ 0 \\  \vdots \\ 0 \end{pmatrix} $$
this can be written also as $Fx = \|x\|e_{1}$ where $e_{1}$ is the $(m - k+1)$  dimensional vector given as $ e_{1} = (1 , 0, \cdots, 0)^{T}$
The extension to this is called Golub-Kahan Bidiagonalization...
$$ A \to U_{n}^{*} \cdots U_{1}^{*} A V_{1} \cdots V_{m} $$
for an $ n \times m$ matrix for instance. Each of these reflectors $F$ can be seen as reflecting the space $\mathbb{C}^{m-k+1}$ across a hyper-plane orthogonal to $v = \|x\| e_{1} -x$. This can be defined as
$$  F = I - 2\frac{vv^{*}}{v^{*}v}$$


How to make user profiles searchable and filterable by multiple fields in the context of a job site

Question: I'm currently in the process of developing a job search site hopefully with these abilities for users of the site:
Job seekers can search for and filter jobs. I'm on my way with this so no problem here.
However what I would like to do is create users searchable for employers. So users can sign up and fill in a number of fields, expertise, CV, skills or whatever else...
Then I want users with paid employer accounts to be able to search and filter employees by these fields.
I'm fairly new to Drupal and I was wondering how I would go about doing this?
Answer: I think you're going to need to use views here.
When you create your view, make sure you use Users and not Content. See screenshot. Once you do this you can set up and expose all the filters you need to allow searching, etc.


Vertical margin between elements are lost in Bootstrap v3?

Question: I´m facing a problem with the new release of bootstrap 3.
Why vertical margin are lost between some elements in the new version?
I´m migrating from v2.3, and now, a lot of things are going wrong.
In the example below, there is no margin between the panel and the form
This works fine in v2. Is there a workaround for this in v3?

    <form class="form-inline" role="form">

        <input class="form-control" id="search" name="search" placeHolder="Search" type="text" />

        <input type="submit" class="btn btn-primary" value="Search" />
    </form>

Panel heading

                Item No

                    1000

The Result:
Answer: I don't know why but you can fix this with :
.form-inline+.panel {
    margin-top: 10px;
}

Comment: Yes, this solution works, but I really want know WHY these margins are lost in the new version.
Comment: By the way, I don't see any bottom margin in `.form-inline` or inputs children in v2.3 and nothing in the "patch note". Take a look at http://getbootstrap.com/getting-started/#migration


How many pairs of integers have a fixed GCD?

Question: Let $k \ge 0, a \ge 0$ be a fixed integer and $f(x,k, a)$ be the number of positive integers pairs $(m,n), m < n \le x$ such that $\gcd(km-n, m + kn) = a$.
Question: Is there a closed form of expression $\lim_{x \to \infty}\dfrac{f(x,k,a)}{x^2}$ in terms of $a$ and $k$?
My experimental data suggest that a closed form exists.
$$
f(x,0,1) \sim 3 \pi^2 x^2
\\
f(x,1,1) \sim 2 \pi^2 x^2
\\
f(x,2,1) \sim \frac{5}{2} \pi^2 x^2
\\
f(x,3,1) \sim \frac{5}{3} \pi^2 x^2
\\
f(x,4,1) \sim \frac{17}{6} \pi^2 x^2
\\
f(x,5,1) \sim \frac{13}{7} \pi^2 x^2
\\
f(x,2,3) \sim \frac{5}{18} \pi^2 x^2
\\
f(x,1,5) \sim \frac{2}{25} \pi^2 x^2
$$
Code
<code>s = 2
j = 0
a = 3
test = 2

target = set = 10^2
while True:
    r = 1
    while r < s:
        if gcd(a*s - r,s + a*r) == test:
            j = j + 1
        r = r + 1
    if s > target:
        target = target + set
        print s, j, (pi^2*j/s^2).n()
    s = s + 1
</code>
Answer: $f(n,1,1) = \sum_{m < n, \gcd(m-n,m+n) = 1} 1 = \sum_{m < n} \sum_{d \mid m-n, d \mid m+n} \mu(d) = \sum_{d \mid 2n} \mu(d)\sum_{m < n, m \equiv n \mod d} 1 = \sum_{d \mid 2n} \mu(d)\left[\frac{n}{d}+O(1)\right] = n\sum_{d \mid 2n} \frac{\mu(d)}{d}+O(\tau(2n))$.
So, $\sum_{n \le x} f(n,1,1) = \sum_{n \le x} \left[n\sum_{d \mid 2n} \frac{\mu(d)}{d}+O(n^{1/2})\right] = \sum_{d \le 2x} \frac{\mu(d)}{d}\sum_{n \le x, d \mid 2n} n + O(x^{3/2})$. Ignore the $O(x^{3/2})$. We get $\sum_{d \le 2x, d \equiv 1 \pmod{2}} \frac{\mu(d)}{d}\left[\frac{1}{2}\frac{x^2}{d}+O(x)\right]+\sum_{d \le 2x, d \equiv 0 \pmod{2}} \frac{\mu(d)}{d}\left[\frac{x^2}{d}+O(x)\right]$. Similarly, we can ignore the $O(x)$ terms, so we end up with $\frac{1}{2}x^2\sum_{d \le 2x} \frac{\mu(d)}{d^2}+\frac{1}{2}x^2\sum_{d \le 2x, d \equiv 0 \pmod{2}} \frac{\mu(d)}{d^2}$. The first term is basically $\frac{1}{2}x^2\sum_{d=1}^\infty \frac{\mu(d)}{d^2} = \frac{3}{\pi^2} x^2$. The second term can be figured out also. So that's how the $\pi^2$'s come about.
One can do $f(n,a,k)$ similarly.
Comment: can downvoter explain?
Comment: By the looks of it you showed for $f(n,1,1)$ and said it can be similarly shown for $f(n,a,k)$ but the questions specifically asked if there is a general closed form $f(n,a,k)$ as opposed to the special case $f(n,1,1)$.
Comment: I just up-voted you answer by the way to raise it form -1
Comment: @NilotpalKantiSinha yes, I gave the method that yields the general closed form for $f(n,a,k)$.


Registrar doesn't allow to set dedicated IP as nameserver

Question: I have registered a .website domain, and I want to point it directly to my VPS (without using a CDN). I've done it before, with other registrars. But when I try to set the nameservers to my dedicated IP, the registrar's control panel gives me an error, saying:

DNS (XX.XX.XX.XX) is not in correct format

Is there anything I can do? Or should I just cave in and use a CDN?
P.S.: This is my registrar
Answer: You should enter the fully qualified host name for the name server.
This is because the delegation is made through NS DNS RR, which accepts a name, not an IP. The form you are filling is supplied as the data field of this record.
The registrar essentially adds something like the following records into the parent zone (which is com in this example):
example.com. NS alpha.example.com.
example.com. NS beta.example.com.
example.com. NS gamma.example.org.
alpha.example.com. A 192.0.2.66
alpha.example.com. AAAA 2001:db8::6a:7bc:8def
beta.example.com. A 203.0.113.77

Exactly same records should exist in your zone too (and the zone must be the same on all servers, in the sense that all of them should give the same replies to the same queries).
The DNS standard requires that each NS RR should contain exactly the name of the authoritative server. I used names alpha.example.com, beta.example.com and gamma.example.org for the example, someone might use just ns1.example.org and so on, this is arbitrary. Registrar doesn't know which names you have chosen for your name servers, so you must always tell them those names.
The additional glue records are only required for the names of authoritative servers that live within the delegated zone itself, as are first two servers in the example. This is the case when you need to specify IP and IPv6 addresses of name servers in addition to, but not instead of host names. If some (or all) servers your zone is going to be delegated to have names not within the zone itself, you don't specify any IP or IPv6 addresses for them at all, only names, because those addresses are specified elsewhere (in their own zone). This is the case of gamma.example.org.
Only specifying the IP addresses alone is never sufficient, because without the name the registrar is unable create the required DNS record for the delegation in the parent zone. Honestly, just as Patrick mentioned in the comment, I doubt you were able to only specify IP addresses and never entered any names.
Theoretically, it is possible to "infer" the names of name servers, if they are already configured to serve this to-be-delegated zone and correctly replying at the moment of filling the form, so the registrar can send a query to the specified IPs to retrieve the list of NS records, but nobody requires that registrars should implement such heuristics. This isn't what you should expect to always work. I've never seen registrars that do something like this.
Comment: "I have set direct IP as my nameserver before (with other domains and other registrars)" Which is wrong. At registrar side, you specificy the nameservers for your domain, no matter which DNS provider you use. Which means entering the *names* of those servers. Then you use this DNS provider panel/API to set up the content of your zone. Your registrar or webhosting company should be able to help you on that.
Comment: I didn't quite understand your answer. Can you elaborate more? I have set direct IP as my nameserver before (with other domains and other registrars)


Change chart y-axis text orientation

Question: I want to change my Google Chart's y-axis title to horizontal orientation. Currently, it is drawn with vertical writing, as shown in this image:

My chart drawing code

function drawVisualization() {
    // Some raw data (not necessarily accurate)
    var data = google.visualization.arrayToDataTable(temp);

    var options = {
        title: 'Report',
        //   vAxis: {title: 'Cups'},
        hAxis: {
            title: 'Date'
        },
        seriesType: 'bars',
        series: {
            0: {
                targetAxisIndex: 0
            },
            1: {
                targetAxisIndex: 1,
                type: 'line'
            }
        },
        vAxes: {
            0: {
                title: '報酬額',
                titleTextStyle: {
                    italic: false,
                }
            },
            1: {
                title: '再生',
                titleTextStyle: {
                    italic: false,
                }
            },
        },
        'chartArea' : {'width': '70%', left: '15%'}
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
Comment: Possible duplicate of [Vertical labels with google charts API?](https://stackoverflow.com/questions/786789/vertical-labels-with-google-charts-api)
Answer: You can see in the Axis Overview:

Direction - You can customize the direction using the
  hAxis/vAxis.direction option.
hAxis.direction    The direction in which the values along the
  horizontal axis grow. Specify -1 to reverse the order of the values.
Type: 1 or -1 Default: 1

If this didn't answer the question, try the workarounds from this SO post.
Comment: Pretty sure OP is looking to change the text rotation
Comment: i mean 'just change yaxis title'. but it did reversed all chart.
Answer: I did like this. And works well. I don't think this is pretty way.
If anyone find better way Please say to me thanks.
var textTags = document.getElementsByTagName("text");
        var searchPlay = "Play";
        var searchProfit = "Profit"

        $.each(textTags, function(index,value){
            if (value.textContent == searchPlay) {
                $(this).css('transform','rotate(1turn)');
                console.log(value);
            }
            if (value.textContent == searchProfit) {
                console.log(value);
                $(this).css('transform', 'rotate(1turn)');
            }
        });

Change chart y-axis text orientation


How to integrate $\int e^{(x+1)^{2}}(6x+23)dx$?

Question: How to integrate $$\int e^{(x+1)^{2}}(6x+23)dx$$ ? I am trying this question by multiplying the numerator and denominator by $(2x+2)$. Therefore, the above integral will become $$\int \frac{e^{(x+1)^{2}}(2x+2)(6x+23)}{(2x+2)}dx$$. Now Let's substitute $(x+1)^{2}=u$. Therefore, $(2x+2)dx=du$. Therefore the above integral will become $$\int \frac{e^{u}(6(\pm{\sqrt{u}}-1)+23)}{(2(\pm{\sqrt{u}}-1)+2)}du$$. Therefore, finally after simplifying a bit, the above integral will become $$\int \frac{e^{u}(\pm{6\sqrt{u}}+17)}{(\pm{2\sqrt{u}})}du$$. But after this step, I can't approach further. Please help me out with this integral.
Comment: You have $3\int e^{(x+1)^2}(2x+2)dx+11\int e^{(x+1)^2}dx$. You can get a nice antiderivative for the first term but the second will be left as is, or using the error function or something like that.
Comment: They are saying there is no elementary antiderivative. Do you know what an error function is?
Comment: What are you trying to say @pancini ? I can't understand
Comment: Where are you getting all these integrals?
Comment: No, I don't know what is an error function?@NinadMunshi.
Comment: @SyamaprasadChakrabarti It is pertinent to know the error function, but it is important to know that $\int e^{(x+1)^2}dx$ does not have a closed-form result.
Comment: Ok. I have understood what you are trying to say @ShubhavJain
Answer: $\int e^{({x+1})^2}(6x+23)dx$
$\int e^{({x+1})^2}6x \thinspace dx+ 23\int e^{({x+1})^2}\thinspace dx$
$6\int e^{({x+1})^2}(x+1) \thinspace dx-6\int e^{({x+1})^2}\thinspace dx+  23\int e^{({x+1})^2}\thinspace dx$
$3\int e^{u} \thinspace du+17\int e^{({x+1})^2}\thinspace dx$
$3e^{{(x+1)}^2} +\frac{17 \mathrm{erfi}(x+1)\sqrt\pi}{2}+C$


Best Approach to link MVC Application with multiple database and switch databases?

Question: I am working on a new project and client asked me to create separate SQL databases for their three different branches. The main problem is to switch the connection and creating the relationship between them in the Asp.Net MVC project.
I will be using Entity Framework Code First Approach to develop the application. I am thinking to create three different connections in the Web.Config file of the application.
SQL Connections
<add name="Con1" connectionString="Data Source=.\SqlExpress;Initial Catalog=dbBranch1;
     Integrated Security=True" providerName="System.Data.SqlClient" />

<add name="Con2" connectionString="Data Source=.\SqlExpress;Initial Catalog=dbBranch2;
     Integrated Security=True" providerName="System.Data.SqlClient" />

<add name="Con3" connectionString="Data Source=.\SqlExpress;Initial Catalog=dbBranch3;
     Integrated Security=True" providerName="System.Data.SqlClient" />

Now the problems is I don't know how to switch the connections based upon the branch user selects from the drop-down list. If user selects the Branch1 in the drop-down list while inserting the record then the record should be inserted into Branch1 Database. How will I configure three connections in Application Db Context File?
Application Db Context
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("Con1", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

Likewise, joining the three databases records and getting result will also be the headache. I might need to write stored procedure during seeding to get records.
I offered my client to create one database and have a table of branches and do normalization. But he wants three separate databases. What is the best architecture or approach to achieve this?
Comment: Well change the constructor on your context to take a `Con1`/`Con2`/whatever as a parameter instead of defaulting it.
Comment: How can I enable Migrations for them?
Answer: Instead of passing hard coded connectionString to your context class. pass a variable and pass that variable to bass class.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(string connString)
        : base(connString, throwIfV1Schema: false)
    {
    }
}

Then Initialize your connectionString like below
ApplicationDbContext dbcontext = new ApplicationDbContext("con1");

OR
ApplicationDbContext dbcontext = new ApplicationDbContext("Con2");

Comment: How can I change ApplicationUser for only dbBranch1 ?


Remove all files by filename (Linux one-liner)

Question: CakePHP has a convention of putting files called "empty" in empty directories. I'm sure they have a reason, but it really bugs me. (Yeah, OCD, I know...)
I want a one-line linux shell command that will delete every file with the name "empty" in every descendent directory. (I suppose it would be useful to be able to specify wildcards for more general use too.)
Any ideas?
Comment: An educated guess is that that CVS and git don't handle empty directories in their source code, so you usually touch a placeholder file and check that in.
Comment: @Server Horror: That makes sense - my original guess was that it would be something like "This page intentionally left blank."
Answer: Simplest is:
find . -name empty -type f -exec rm -f {} \;
"." starts at current directory, replace with a directory path if you want to execute it in another location.
"-type f" just makes sure it's a file.
Comment: "find . -name empty -type f | xargs rm -f" will call rm only once
Comment: tomdeb> Don't throw unquoted filenames at rm!
Comment: "find . -name empty -type f -exec rm -f {} +" will call find only as often as necessary and not for each file
Comment: Might want to throw on a -v flag to the rm, just so the user knows what's going on, but yes, great answer
Comment: I know you meant to say "will call rm" instead of find.
Comment: Shame you can't down vote comments. :( tomdeb's answer is open to problems with files that have spaces in.
"find . -name empty -type f -print0 | xargs -0 rm -f" is a slightly safer form.
Comment: @tomdeb: not exactly it will just like the "find ... +" call rm only as often as necessary if there are more files than the maximum command line length is it will subsequently call rm with the appropriate number of options
Answer: Short Summary:
There are multiple options:
find . -name empty -type f -exec rm -f {} \;

will call rm once for every file
find . -name empty -type f -exec rm -f {} +

will call rm only as often as necessary by constructing a command line that uses the maximum length possible
find . -name empty -type f | xargs rm -f

same as above, you may (or rather will, as above - which was my approach) run into problems with filenames that contain characters that need quoting
find -name empty -type f -print0 | xargs -0 rm -f

is probably the best solution Please Upvote Dan C's comment it's his solution. It will as the earlier snippet call rm only as often as need by constructing a command line that uses the maximum lenght possible, the -0 switch means that arguments to the rm command will be separated by \0 so that escaping is done right in the shell.
On a side note about the comment to restrict by using -type f you can also restrict with -size 0 (exactly 0 bytes) I can't verify if CakePHP really adheres to that convention but just about every project I know that uses placeholder files to check empty directories into the source repositories does that.
Also as Matt Simons points out adding a -v flag might be a nice option to see some progress, however do notice that this will definitely slow down the whole process. A better approach might be to follow the process by using strace -p $pid_of_xargs (add addtional options if you want to follow child processes, afaik that is possible)
Another note i just found in the manpage:
find -name empty -type f -delete

after all find has all of that builtin :)
Comment: "find -name empty -type f -delete"

Just check the manpage first, as older versions of 'find' didn't have the -delete option.  But as long as your OS is current, you should have this option.
Comment: since the OP asked for Linux I think it is valid (correct me but I don't know any distribution that doesn't come with the GNU tool collection)
Comment: Older versions of Linux had a find that didn't include "-delete" was all I was saying.  Older versions that are sadly still regularly used in too many places. ;)
Answer: A possible reason why cakePHP might do this is because some version control systems (e.g. Mercurial and Git) cannot track an empty directories.
Comment: Also some zip programs skip empty directories
Answer: This might do:
rm -f $(find /var/www -name empty -print)

Find recurses by default.
Comment: Not ideal. You might produce more arguments than your shell/rm is capable of handling. But more importantly, the argument list won't be properly escaped from nasties such as spaces. If for some reason you don't use find's -exec a safe alternative would be `-name empty -type f -print0 | xargs -0 rm -f`
Comment: Will not work correctly if there's (ugh) spaces, apostrophes, semicolons or other weird characters in the directory names.