Convergence of $n^{(-n^2)}$

Question: I'm aware that this sequence converges to 0, but I'd like to know why my first instinct was wrong.  I looked at this and took a cue from the old 1^inf technique of raising e to the natural log of the sequence:
$$\lim_{n\to \infty} n^{-n^2} \implies e^{\ln(n^{-n^2})}$$
leave e aside for now and concentrate on the natural log problem
$$-n^2\cdot \ln n\implies \frac{\ln n}{-n^{-2}}$$
by l'Hôpital's rule
$$\frac{\frac1n}{2n^{-3}} =\frac{n^2}2 $$
back to the original problem
$$\lim_{n\to \infty} e^{n^2/2} =( e^\infty)= \infty$$
The book offers a squeeze/sandwich theorem explanation, but I need to know what my mistake is so that I do not repeat it.  Where did I go wrong here?
Comment: You can't apply l'Hospital for 2 reasons: 1) it is not a function but a sequence. 2) Also extending to functions $\frac{log x}{-x^{-2}}$ is not an indeterminate form
Comment: @Isham yes of course, thanks!
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your mathematics. As it stands, this is relatively difficult to read.
Comment: Thank you Arthur, I will look at this now.  I'll accept gimusi's answer when I am able to in 5 minutes.
Comment: @gimusi can you correct  the x under the limit ? It makes no sense
Comment: @gimusi "Reason" 1 is ludicrous. Please avoid misleading the OP.
Comment: @Did I did sense that that was incorrect.  Convergence seems to intuitively be the limit at infinity.
Comment: @Did Refer here for details https://math.stackexchange.com/a/1398706/505767
Comment: @gimusi Relevant how?
Comment: @Did Why did you deleted your last comment? Maybe you have finally read the full text and also the comments where is highlighted that there are cases for which $f(n) \to L$ for $n \to \infty$ but $f(x)$ has not limit for $x \to \infty$? Yes maybe it is so and **YOU ARE WRONG!** since in general l'Hospital can't be extended to sequecences! In many cases we can do but we must be aware about it. Anyway l'Hospital is a bad method (in general) to solve limits if the aim is to understand them and I Always suggest to avoid it whenever possible.
Comment: @gimusi You are fantasizing: the suggestion is to deal with the function and to deduce results for the sequence, **which always works**, not to use the other direction, which indeed may not work. Please read carefully the link you provide. (If reactions from exuberant illiterates similar to yours are to generalize, the site will become difficult to use.)
Comment: @Did But we are not applying l'Hospital rule to the sequence, we are applying the rule to the corresponding function, that is exactly what I've pointed out in my point 2). What are you talking about? You are ludicrous with your attempts to put others in a bad perspective.
Comment: @gimusi Stick to the maths if you can: your Reason 1 does not work. Did I even mention Reason 2? No, hence you are either a sophist, or out of your league, or both.
Comment: @Did You are the sophist since extrapolate only one part of my comment without mention point 2 that is a part of it.
Comment: @gimusi Quote: "You can't apply l'Hospital for 2 reasons: 1) (something). 2. (something else)." Sorry but, as usual, you are trying to drag this very elementary point into a neverending discussion, so, please... do so if you must, but without me.
Comment: @Did part 2 is not something else since we claim "also extending to functions..." in order to use l'Hospital...etc.. I repeat: l'Hospital can't be applied to the sequences, it can be applied to the corresponding functions, that is exactly what I wrote! Bye
Comment: Well, I certainly didn't intend to create this train wreck :-)  I do appreciate all of the enthusiasm in the responses to my question.
Answer: Note that
$$n^{-n^2}=e^{-n^2\log n}=\frac{1}{e^{n^2\log n}}\to 0$$
indeed
$$n^2\log n\to\infty$$
Comment: So, is -inf*inf not an intedterminate form?  In other words I should have said limit x-> inf -n^2*ln(n) = -inf --> e^-inf --> 1/inf --> 0 ?
Comment: @patricio2626 yes of course, let me write in **symbolic way** that  $$\large{-\infty \cdot \infty=-\infty}$$

Convergence of $n^{(-n^2)}$


When using JPA2 EntityListener, how does it work if i use the in clause to update multiple rows?

Question: query : update Order set f='1' where key in (1,2,3,4,5)
<code>@PostUpdate
public void postUpdate(Order order) {
    ....
}
</code>
I wonder what happens if I work as above.
Comment: Can you add more info about code ? and also execute the code and if confusion or clarifcation then you can ask question here.
Answer: If you execute a bulk update/jpql update query of the from "update Order set f='1' where key in (1,2,3,4,5)" you get those rows affected and nothing else. JPQL bulk updates/deletes run in the database, so they do not affect your java entities and do not cause entity lifecycle events to occur.


Ajuda com php_printer.dll

Question: Uso PHP 5.5.12 e baixei a versão da dll compativel e quando abre a página não acontece nada e tambem não aparece nenhum erro.
Reiniciei o Wamp e adicionei as linhas correspondentes no php.ini
php.ini
 printer.default_printer=PHP_INI_ALL
 extension=php_printer.dll

imprime_cupom.php
<?php

 $printer_name = "Daruma D800";
 $handle = printer_open($printer_name);
 printer_start_doc($handle, "Cupom Teste");
 printer_start_page($handle);
 $font = printer_create_font("Arial", 100, 100, 400, false, false, false, 0);
 printer_select_font($handle, $font);
 printer_draw_text($handle, 'Teste de Cupom.', 100, 400);
 printer_delete_font($font);
 printer_end_page($handle);
 printer_end_doc($handle);
 printer_close($handle);
 ?>

Comment: @GuilhermeNascimento na verdade se trata de um cupom não fiscal tipo um sistema de PDV entao eu achei mais produtivo imprimir direto na impressora sem confirmação. caso saiba de outra maneira de imprimir sem confirmação sera bem vinda
Comment: Quer imprimir no Servidor ou no navegador?
Comment: @GuilhermeNascimento o servidor e o cliente sao na mesma maquina.
Comment: Se são na mesma máquina, não poderia resolver isto com um gerador de PDF ou HTML mesmo e depois `window.print` na página? Só por curiosidade que estou perguntando, de qualquer forma estou tentando baixar a dll compativel pra minha maquina pra testar e ver se consigo detectar o erro.
Comment: Verifique esta resposta https://pt.stackoverflow.com/questions/195301/listar-impressoras-na-rede-com-php/195376#195376 acredito que possa lhe ajudar, na mesma é abordado tanto a instalação quanto a utilização.
Answer:
A extensão php_printer é o meio padrão para se obter as impressoras conectadas ao servidor. Porém ela não vai identificar as impressoras de rede que não estejam configuradas no servidor pois não permite descoberta.

Se mesmo depois da instalação da extensão você não conseguiu tente seguir estes passos:

Obtendo impressoras sem a extensão, usando apenas linha de comando no windows:
Quando o PHP por sí só não consegue, podemos utilizar alguma interface de linha de comando, seja um script java ou python ou até mesmo um script php rodando com um php mais antigo. A técnica consiste em utilizar uma linha de comando e tratar a string do resultado.
<?php
//Função para tratar o retorno
function getPrinterProperty($key){
    $str = shell_exec('wmic printer get '.$key.' /value');

    $keyname = "$key=";
    $validValues = [];
    $fragments = explode(PHP_EOL,$str);
    foreach($fragments as $fragment){
        if($fragment == ""){
            continue;
        }
        if (preg_match('/('.$keyname.')/i', $fragment)) {
            array_push($validValues,str_replace($keyname,"",$fragment));
        }
    }
    return $validValues;
}
//Esplanação dos commandos:
// wmic /node:SERVER1 printer list status // Lista status das impressoras de um servidor remoto
// wmic printer list status // Lista status das impressoras  do servidor local
// wmic printer get // Obtem todas as propriedades da impressoa
// wmic printer get <propriedade> /value //Lista uma propriedade no formato chave=valor do servidor remoto
// wmic printer get <propriedade> /value //Lista uma propriedade no formato chave=valor do servidor local

//Obtém algumas propriedades, nesse caso vou pegar só algumas
$Name = getPrinterProperty("Name");
$Description =  getPrinterProperty("Description");
$Network = getPrinterProperty("Network");
$Local = getPrinterProperty("Local");
$PortName = getPrinterProperty("PortName");
$Default = getPrinterProperty("Default");
$Comment = getPrinterProperty("Comment");

$Printers = [];
foreach($Name as $i => $n){
    $Printers[$i] = (object)[
        "name" => $n,
        "description" => $Description[$i],
        "Portname" => $PortName[$i],
        "isDefault" =>($Default[$i] == "TRUE")? true : false,
        "isNetwork" => ($Network[$i] == "TRUE")? true : false,
        "isLocal" =>($Local[$i] == "TRUE")? true : false,
        "Comment" => $Comment[$i],
    ];
}

var_dump($Printers);

array(7) {
  [0]=>
  object(stdClass)#1 (7) {
    ["name"]=>
    string(29) "Microsoft XPS Document Writer"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(11) "PORTPROMPT:"
    ["isDefault"]=>
    bool(false)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(0) ""
  }
  [1]=>
  object(stdClass)#2 (7) {
    ["name"]=>
    string(22) "Microsoft Print to PDF"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(11) "PORTPROMPT:"
    ["isDefault"]=>
    bool(false)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(0) ""
  }
  [2]=>
  object(stdClass)#3 (7) {
    ["name"]=>
    string(32) "HPC4C962 (HP Officejet Pro 8600)"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(45) "WSD-5277c4df-fd03-46fb-a957-1d8a0fd65b01.003c"
    ["isDefault"]=>
    bool(true)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(30) "This is a web services printer"
  }
  [3]=>
  object(stdClass)#4 (7) {
    ["name"]=>
    string(29) "HP Officejet Pro L7600 Series"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(12) "192.168.1.22"
    ["isDefault"]=>
    bool(false)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(0) ""
  }
  [4]=>
  object(stdClass)#5 (7) {
    ["name"]=>
    string(24) "Foxit Reader PDF Printer"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(13) "FOXIT_Reader:"
    ["isDefault"]=>
    bool(false)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(0) ""
  }
  [5]=>
  object(stdClass)#6 (7) {
    ["name"]=>
    string(3) "Fax"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(7) "SHRFAX:"
    ["isDefault"]=>
    bool(false)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(0) ""
  }
  [6]=>
  object(stdClass)#7 (7) {
    ["name"]=>
    string(26) "Enviar para o OneNote 2013"
    ["description"]=>
    string(0) ""
    ["Portname"]=>
    string(4) "nul:"
    ["isDefault"]=>
    bool(false)
    ["isNetwork"]=>
    bool(false)
    ["isLocal"]=>
    bool(true)
    ["Comment"]=>
    string(0) ""
  }
}

Agora você terá a lista de impressoras instaladas no sistema, então você pode utilizar um aplicativo que permita a executar via linha de comando, como o Foxit Reader e utilizar o seguinte comando:

<?php

shell_exec('FoxitReader /t C:/Temp/file.txt "'.$Printers[0]->name.'"');

Estes procedimentos foram retirados da resposta Listar impressoras na rede com PHP acredito que possa lhe ajudar.
Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada. - [Da Revisão](/review/low-quality-posts/132271)

Ajuda com php_printer.dll


How to use same jquery fuunction on a multiple buttons that are created in a loop?

Question: Im creating the same button in a loop as long as there is a certain condition, and I want to run the same jquery event handler for those buttons.
The problem is that the event handler only works for the first button generated.
My button is generated like this:
<?php while($row_c= mysqli_fetch_array($result_comments))
{ ?>
<button name="comment" id="comment" class="button_comment" value="Post">Post</button>
<?php } ?>

and the jquery im using is this:
$('.button_comment').click(function()
{
    //some staff thats done here
});

What should do, so that the event handler works for all buttons that are generated?
Thank you
Comment: Your code should work as in, actually.
Answer: Your jQuery should work. Note that your buttons form invalid HTML/DOM: The id on an element must be unique. But since you're also using a class (which doesn't have to be unique), and that's what you're using in your jQuery selector, that works: Live Example | Source
Perhaps when you were trying it and it wasn't working, you were using $("#comment").click(...), which would not work, because of the id issue.
Comment: Yes I know, but only the first button triggers the jquery event handler, and I dont know why
Comment: @beckinho27: Not with what you've put in your question.
Comment: @beckinho27 Here is another quick test : http://jsfiddle.net/wared/QVGch/. Feel free to fork.
Answer: Check in firebug:

  var buttoncomments = $('.button_comment');
    console.log(buttoncomments);

Bind the control in question to a variable so you're certain that it's that one you're working with.

$('.button_comment').click(function()
 {
     var that = $(this);

Answer: "What should do, so that the event handler works for all buttons that are generated?"
A Fiddle would be a good way to show us the context of your problem ;)

Your code is valid because it will attach a handler to every element having 'button_comment' as a css class

Did you put this code inside a dom ready function ?
$(function(){
    /* code here  */
});

You can use event delegation
This mean you have to attach the event listener to the first common ancestor of those buttons. This is a good choice when many elements have to trigger the same routine an even more if some of them may be added to the DOM in the futur via AJAX (This keep the page from having to many event handlers attached to it)

Delegation syntax
// Event delegation
$( "#Ancestor").on("click", '.button_comment', function() {
    alert( $( this ).val() );
});

Answer: Take the ID off from your php code. Remember ID's should be unique elements. Also, change your jquery from:
('.button_comment').click(function()
{
    //some staff thats done here
});

to
('.button_comment').on('click', function()
{
    //some staff thats done here
});

The on event will perform what you tell it to do at the time you tell it to do, so it does it pretty much at runtime. If you use your previous code, the element must exist at page load time for it to work.


Link an external url to the Title in Colorbox

Question: I am trying to add an external link to the Title in the images in colorbox, so that by clicking the title leads to an external page. Have added custom field in the posts( I am using Wordpress) and given key = 'url' and value = an external link, say http://facebook.com. Have around 10 images on my page.
I am calling the following in the jQuery ready function in my home.php, which further calls a loop.php to display the images in hp-thumb format. .

The problem is this is not displaying the Title at all. Where am I going wrong?
Thanks in Advance.
Comment: You may have to use a onComplete:function(){) and replace the title.
Answer: I got the solution. It was a small syntax mistake in php.
I needed to use:
var newLandingPage =  keyValues['0'];
And I am done.


Android Displaying more than 1 variable textView

Question: I have a textView and I want to display two different variables at the same time, each on one line.
Here is what I have so far
TextView.setText("You answered :" + " " + correct + "correct" + '\n');
TextView.setText("You answered: " + " " + wrong + "incorrect");

this only displays the last line and not both lines of code in the textView. Can anyone tell me how i can go about displaying both of these in the same textView at the same time on 2 different lines? Much appreciated.
Answer: Using this snip code:
TextView.setText("You answered :" + " " + correct + "correct\n" +"You answered: " + " " + wrong + "incorrect");

Answer: String text = "You answered :" + " " + correct + "correct\n" +"You answered: " + " " + wrong + "incorrect";
TextView.setText(text);

Answer: Try this:
TextView.setText("You answered: " + correct + "correct\nYou answered: " + wrong + "incorrect");

Note: By convention, you should avoid naming variables with capital letters, especially if the name is already a class name. Consider using textView instead of TextView.
Answer: Try create the String first then set the text in the TextView.
Answer: Isn't the generic answer:
TextView.setText("You answered :" + " " + correct + "correct" + '\n');
// Lots of other intervening code
TextView.append("You answered: " + " " + wrong + "incorrect");

In addition, there is a lot of unnecessary string operations:
TextView.setText("You answered : " + correct + "correct\n");
// Lots of other intervening code
TextView.append("You answered:  " + wrong + " incorrect");


Find the solution of the differential equation that satisfies the given initial condition $~y'=\frac{x~y~\sin x}{y+1}, ~~~~y(0)=1~$

Question: Find the solution of the differential equation that satisfies the given initial condition $$~y'=\frac{x~y~\sin x}{y+1}, ~~~~~~y(0)=1~$$
When I integrate this function I get
$$y+\ln(y)= -x\cos x + \sin x + C.$$
Have I integrated the function correctly?
How do I complete the second part of the question $~y(0)=1~$
Comment: This is correct. Setting $x=0,\,y=1$ gives $C$. If you exponentiate both sides thereafter, you have $ye^y$ as a function of $x$. If you want $y$ as a function of $x$, see this: https://en.wikipedia.org/wiki/Lambert_w_function
Comment: Yes you have to exponentiate both sides as,$$ye^y=e^{1+sinx-xcosx}$$
So,$$y=W(e^{1+sinx-xcosx})$$refer link given by @J.G.
Comment: I managed to get C=1, so I now have y+ln(y)= -xcosx +sinx +1  How do I exponentiate both sides?
Comment: Thanks so much for your help. I'm still not sure how you get the left hand side ye^y. I understand the right hand side
Comment: @chelseathomson $e^{y+ln(y)}=e^ye^{ln(y)}=e^yy$ because $e^{ln(y)}=y$
Comment: Welcome to Math.SE!  You might benefit from the introductory note, [How can I format mathematics here?](http://math.stackexchange.com/help/notation)
Answer: What you can do is to use the so-called Separation of variables (see for example https://en.wikipedia.org/wiki/Separation_of_variables):

Write $y' = \frac{dy}{dx}$
Do the following transformation: $\frac{dy}{dx} = \frac{xy \sin(x)}{y+1} \Longleftrightarrow \frac{y+1}{y} dy = x\sin(x) dx$. Now integrate both sides (with respect to the corresponding variable), arriving at
$\int (1 + \frac{1}{y}) dy = \int x \sin(x) dx \Longleftrightarrow y + \ln(y) = \sin(x) - x \cos(x) + C$.
To get the integration constant $C$, set $x = 0$ and $y = 1$, then: $1 = 0 + C \Longleftrightarrow C = 1$.
You'll not be able to solve the equation in 3 for the function $y = y(x)$ in terms of elementary functions (such as trigonometric functions, exponential/logarithmic functions etc.); But what you can do is to use the so-called Lambert W function, see https://en.wikipedia.org/wiki/Lambert_W_function. Then you will get $y(x) = W(e^{\sin(x) - x \cos(x) + 1})$.
Answer: we write the equation in the form
$$\left(1+\frac{1}{y}\right)dy=x\sin(x)dx$$
integrating we obtain
$$y+\ln|y|=\sin(x)-x\cos(x)+C$$
Comment: Copying what is already in the question and not answering what is actually asked.
Comment: Which is irrelevant since $y(0)=1$. But if this is indeed your reason for copying parts of the question (which, somehow, I doubt...), you should indicate that is is in your post.
Comment: you are don't sitting here to see if i have copied the answer
Comment: What? My comment points out that your post "indicates" to the OP things they already know. (But hey, Dr., we all know you do not care, so why do you suddenly pretend you do?)
Comment: the solution is a absolut value missing
Comment: @Dr.SonnhardGraubner: The form $\log|y|$ stands for a pair of solutions $\log(x)$ for $x\gt0$ and $\log(-x)$ for $x\lt0$. Since $\int\frac{\mathrm{d}y}y$ diverges at $0$, solutions rarely exist across $0$. In this case $y\gt0$ and so the integral needed is simply $\log(y)$. Note further that promoting $\log|z|$ into complex integrals is not good.
Answer: Given that $$~y'=\frac{x~y~\sin x}{y+1}$$
$$\implies \frac{dy}{dx}=\frac{x~y~\sin x}{y+1}$$
$$\implies \frac{y+1}{y}~dy=x\sin x~dx$$
$$\implies \left(1+\frac{1}{y}\right)~dy=x\sin x~dx$$
Integrating we have $$y+\log y=\int x\sin x~dx $$
$$\implies y+\log y=-~ x\cos x+\sin x~+~C\qquad \text{where $~C~$is integraating constant.}$$
Now given condition is $~~y(0)=1~~$, which gives $$1+0=0+0+C\implies C=1$$
So the solution of the differential equation that satisfies the given initial condition is $$y+\log y=-~ x\cos x+\sin x~+~1$$

Using integrating by parts rule:
$$\int x\sin x~dx =x\int \sin x~dx~-~\int \left(\frac{d}{dx}x~\int \sin x~dx\right)~dx$$
$$=-x~\cos x~-~\int \left(1\cdot~(-)~\cos x\right)~dx$$
$$=-x\cos x+\sin x$$


What is the chord consisting of G F# A D?

Question: I'm somewhat new to more complex chords. I found this chord on YouTube which consists of G F# A D (from lowest to highest notes). The person said it is GMaj9 chord, but actually it misses the 3rd, which per all theory I read, cannot be a major chord.
So some guesses:

If I count G as root - then it has 1 - 7 - 9 - 5, I did not find how to call such a chord
If I treat G as an added bass note, then the F#-A-D looks like an inversion of  D chord - so perhaps this can be denoted as D/G chord? Can one add another bass note to an already inverted chord?
Alternatively, if I still consider G as bass note, but treat F# A D as a non-inverted chord, it comes to something like F#minb6/G

Are any of these directions correct, are there other better options?
Comment: It's the second inversion of the Steely Dan chord! If it was G - A - D - F#, then it would be a root-position Steely Dan chord. ;) Ok, maybe not taught on your basic theory classes... The Steely Dan chord is like "maj9omit3", but with the maj7 as the highest note. Leaving it out the third makes it special.
Comment: I dont think anything from music theory has to be taken as an unbreakable rule. You can voice a chord without the third and stillñ p2p
Answer: D/G might be the simplest description.   (Is G the bass note of the complete music, or are we just looking at a guitar voicing?).   But Gmaj9 might describe its harmonic purpose better.
If you want THOSE notes to be played, write notation.  Chord symbols can't do the whole job.
Comment: Yes. And yes - usually as D/G.
Comment: "G maj9 omit3" is another systematic name in addition to D/G. Leaving out the third makes a difference to the harmonic effect IMO.
Answer: A further option is to view the G as not a "true" part of the chord at all. Instead, that G could be viewed as a pedal tone below a D chord. This is a relatively common procedure: chord changes taking place above a stable tonic pedal.
In still other instances, we might actually view the G as the chord tone, making the D, F♯, and A all non-chord tones! This is very common in Classical music, with the D chord being suspended over the bass resolution to G.
As with most things in music, it's all about context. In some musical contexts we may call this a G chord, but in others we'd understand it as a D chord.
Answer: It could also be a A7sus(13) or more correctly, A7sus(add13).
A - root
D - 4th
G - 7th
F#- added 13th.
How it functions, harmonically will depend on the context.


Where to save my custom scripts so that my python scripts can access the module in the default directory?

Question: This is going to be a multi-part question but the ultimate aim is such that I can access custom-made modules/libraries/functions like how I do in native python.
Where are the non-native but pip installed python libraries stored and how to configure my interpreter/IDE to access them?
My users' script all starts with:
#!/usr/bin/env python -*- coding: utf-8 -*-

What's the difference between accessing from /usr/bin and /usr/bin/env, will the custom-made modules that should import like native python modules/packages work?
Should my custom scripts become packages? if so how do I make the user-side code, checks for ImportError and install/setup these packages in the try-except? e.g.
try:
  import module_x
except ImportError:
  # Install package, but how to do it within the script?
  pass

Is there a place to store my custom scripts such that it imports like a native library? If so, where? What are the consequences?
Comment: The `/usr/bin` vs. `/usr/bin/env` issue is (almost certainly) not something you need worry about.  When you specify `/usr/bin/python` you're telling the shell exactly where to find the `python` binary.  When you say `/usr/bin/env` you're telling the shell to find the `python` binary on its own.  If you only have one copy of `python` on your machine, then the two are equivalent.
Answer: Well, you've asked a lot of questions; I will address the one in the subject line.
You can put Python module files anywhere you want and still import them without any problems as long as they are in your module search path.  You can influence your module search path by altering the environment variable PYTHONPATH in your shell before invoking Python, or by altering the sys.path variable inside your code.
So if you've installed /home/alvas/python/lib/module_x.py and /usr/local/python/lib/foo.py you could run:
PYTHONPATH=/home/alvas/python/lib:/usr/local/python/lib /home/alvas/scripts/bar.py

and then the statements
import module_x
import foo

should simply work.
Alternatively you could do something like this in your code:
#!/usr/bin/env python
import sys
sys.path.append('/home/alvas/python/lib')
import module_x
sys.path.append('/usr/local/python/lib')
import foo

Either approach will work.
Comment: if I use the latter approach it does not work. I use python3.6 in Anaconda. I I append the new path to sys.path, it gets appended but if I exit and start python again, it is no longer in the list. What am I doing wrong?


How to sort a form field values through generator file using symfony?

Question: how are you all guys?
I want to sort(in ascending or descending order) a form fields through generator.yml in symfony. I mean I have 2 tables Events and Members. Relation between these two tables are many to many. What I want is that when I go to add/edit an event, members list should be sorted by their names.
I tried to use:
config:
      actions: ~
      fields:
        title:           { help: Title of the event ,label: Event Name *}
        event_datetime:  { help: Set the date and time of event ,label: Date time *}
        details:   { help: Details related to event ,label: Details *}
        venue_id:           { help: Select venue }
        is_visible:   { help: Select is visible or not}
        members_list:           { help: List of members }
        slug: { help: User Friendly URL,label: User Friendly URL }
      sort: [mmebers_list, asc]

But it does not work successfully.
any suggestion please?
Thanks
Answer: Try Adding this to your schema.yml
Member:
  actAs:
    Timestampable:
    Sluggable:
      unique: true
      fields: [name]
      canUpdate: true
  options:
    orderBy: name ASC

This will sort all the members lists globally in your application
Answer: I had a similar problem, but I use sfGuardUser plugin and I don't want to change their schema. I had to change action files and add:
public function executeNew(sfWebRequest $request)
{
    parent::executeNew($request);
    $sql = Doctrine_Query::create()->from('sfGuardUser u')->innerJoin("u.Profile p")->where('u.is_super_admin = ?',false)->orderBy('p.lastname');
    $this->form->getWidget('user_id')->setOption('query',$sql);
}

You need to pass query which symfony use to get data to field.


binary search, count duplicates

Question: I have sorted array
{1,2,3,5,5,5,7,8,8}

I would like to count how many times the number that i am sending is found in the array in longn only.
for example:
public static int count(int[] array,5)

will reply 3
public static int count(int[] array,8)

will reply 2
so my plan is:
1) to do a binary search to find the number
2) binary search the top border index and the bottom border index.
3) print (top index - bottom index) will give me the time of target number in the array.
Is my code is logn ?
Please help! :)
    public class binarySearch
{
    public static void main(String[]args)
    {
        System.out.println("d");
        int[]data={1,1,2,3,1,1,1};
        System.out.println(count(data,1));
    }

    public static int count(int[] a, int x)
    {
        int low=0;
        int high = a.length-1;
        int count=0;

        while(low <=high)
        {
            int mid=((low+high)/2);
            if(x>a[mid])
                low=mid+1;
            if(x<a[mid])
                high=mid-1;

            if(x==a[mid])
            {
                int top=findTopIndex(a,x,mid);
                int bottom=findBottomIndex(a,x,mid);
                return (top-bottom);

            }

        }
        return 111111111;

    }

    public static int findTopIndex(int[] a, int x, int index)
    {
        int low=index;
        int high = a.length-1;
        int mid;
        if(x==a[high])
        return high;

        while(low <= high)
        {
           mid=((low+high)/2);
           if(xx && a[mid-1]!=x)
           high=mid-1;

        }
        return 11111111;

    }
    public static int findBottomIndex(int[] a, int x, int index)
    {
        int low=0;
        int high = index-1;
        int mid;
        if(x==a[low])
        return low-1;

        while(low <= high)
        {
         mid=((low+high)/2);
           if(x>a[mid]&&x==a[mid+1])
           return mid;
           else if(x==a[mid])
                high=mid-1;
           else if(a[mid]<x && a[mid+1]!=x)
           low=mid+1;

        }
        return 111;

    }

}

Comment: @millimoose what for `{1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,8}`?
Comment: Do you *need* to search for the border indices with binary search? Seems that it'd be fast enough if you continue with a linear search after that.
Comment: Use else if instead of if if if...
Comment: @AlvinWong Depends on exactly how likely the scenario is with your data sets. Worst-case linear complexity isn't exactly terrible. You're also assuming that it's also possible to find the edges of that run of fives efficiently.
Comment: @millimoose then linear search will save more time.
Comment: @millimoose by performing two additional binary searches complexity is still O(log(n)) and you solve all scenarios even the worst-case one.
Comment: Can you use a different data structure? PriorityQueue, SortedMap etc?
Answer: What you have written is really close to the solution you need. You first do a binary search to find a single instance of the number you are searching for(let's say its found on position index) and then you do two more binary searches -one for the sequence 0, index, and one for index, size to find up to where in both sequences is the number found.
So I suggest you simply pass an index to both findTopIndex and findBottomIndex and make use of it. I can write the whole solution but it will be better for you to come to it on your own.
Comment: This is a good approach, I totally missed the O(logn) part on my (deleted) answer. A list full of the same elements results in O(n).
Comment: If there's a very long run of the same number, couldn't the "two more" searches also land somewhere in the middle of the respective two halves of said run? Seems like you'd want to search recursively to find the top and bottom indices - i.e. when you can't find the number anymore to the left of the current index, the current index is the beginning of the run. (And vice versa.)
Comment: @millimoose no, the two additional binary searches are performed in a different manner as to find the first position differing from x. The monotonous property I use for those searches is `equal to x` and by doing a single binary search one could find the single index where this property changes from 0 to 1.

binary search, count duplicates


Change all positive values in array to 1 (Python)

Question: So I have several 3D arrays that I need to add together. Each array consists of entries with either 0 or 1. All arrays also have the same dimension. Now, when I add these arrays together some of the values overlap (which they do). However, I just need to know how the structure of the total combined array is, which means that I don't need the values 1, 2 or 3 when 2 or 3 arrays have overlapped. This also just need to be one, and of course, wherever there is a zero, the value zero just need to remain zero.
So basically what I have is:
array1 =
[[[1, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 1, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 1], [1, 1, 1], [0, 0, 0]]]

array2 =
[[[1, 0, 0], [0, 1, 0], [0, 0, 0]],
[[0, 0, 0], [1, 1, 0], [0, 0, 0]],
[[0, 0, 1], [0, 1, 0], [0, 0, 0]]]

So when adding them together I get:
array_total = array1 + array2 =
[[[2, 0, 0], [0, 1, 0], [0, 0, 0]],
[[0, 1, 0], [1, 1, 0], [0, 0, 0]],
[[0, 0, 2], [1, 2, 1], [0, 0, 0]]]

Where I actually want it to give me:
array_total = array1 + array2 =
[[[1, 0, 0], [0, 1, 0], [0, 0, 0]],
[[0, 1, 0], [1, 1, 0], [0, 0, 0]],
[[0, 0, 1], [1, 1, 1], [0, 0, 0]]]

So can anyone give me a hint to how this is done ?
Comment: With numpy arrays, `array1 | array2`
Comment: So, those are `numpy` arrays?
Answer: (Assuming those are numpy arrays, or array1 + array2 would behave differently).
If you want to "change all positive values to 1", you can do this
array_total[array_total > 0] = 1

But what you actually want is an array that has a 1 where array1 or array2 has a 1, so just write it directly like that:
array_total = array1 | array2

Example:
>>> array1 = np.array([[[1, 0, 0], [0, 0, 0], [0, 0, 0]],
... [[0, 1, 0], [0, 0, 0], [0, 0, 0]],
... [[0, 0, 1], [1, 1, 1], [0, 0, 0]]])
>>> array2 = np.array([[[1, 0, 0], [0, 1, 0], [0, 0, 0]],
... [[0, 0, 0], [1, 1, 0], [0, 0, 0]],
... [[0, 0, 1], [0, 1, 0], [0, 0, 0]]])
>>> array1 | array2
array([[[1, 0, 0], [0, 1, 0], [0, 0, 0]],
       [[0, 1, 0], [1, 1, 0], [0, 0, 0]],
       [[0, 0, 1], [1, 1, 1], [0, 0, 0]]])

Comment: Ah, yes, they are numpy arrays. But thank you, I did not know about the | operator.


Is this a correct argument for why this space of sequences is a Hilbert space?

Question: I am assigned the following problem (a piece of Exercise 6.5 in Brezis's book):

Let $(\lambda_n)$ be a sequence of positive numbers such that $\lim_{n\to\infty}\lambda_n=+\infty$. Let $V$ be the space of sequences $(u_n)_{n\geq 1}$ such that
  $$\sum_{n=1}^\infty\lambda_n|u_n|^2<\infty.$$
  The space $V$ is equipped with the scalar product
  $$((u,v))=\sum_{n=1}^\infty\lambda_nu_nv_n.$$
  Prove that $V$ is a Hilbert space.

Here is the hint that Brezis provides for this part of the problem:

Let $T:V\to\ell^2$ be the operator defined by
  $$Tu=(\sqrt{\lambda_1}u_1,\sqrt{\lambda_2}u_2,\ldots).$$
  Clearly $\|Tu\|_{\ell^2}=\|u\|_V$ for all $u\in V$, and $T$ is surjective from $V$ onto $\ell^2$. Since $\ell^2$ is complete, it follows that $V$ is also complete.

It seems clear to me that Brezis intends the reader to use the open mapping theorem; the map is obviously linear, and the hint points out that the map is an isometry, which proves both that it is bounded as well as injective. As the hint says, it is also clear that the map is surjective. At this point, all we have is a continuous bijection from $V$ to $\ell^2$. But applying the open mapping theorem, we have that the inverse map is also continuous, so that $V$ is isomorphically isometric to $\ell^2$, and because $\ell^2$ is complete, $V$ is complete.
Here's my problem: the open mapping theorem requires both spaces to be Banach spaces. To use this argument to prove that $V$ is complete is circular reasoning.
Am I misunderstanding the intended path of the argument? How would Brezis's hint be filled in to a complete argument correctly?
Comment: Ah. We can just directly observe that $T^{-1}$ is continuous (evident in the same way that $T$ being continuous was), and skip the open mapping theorem.
Comment: I don't think he is using that theorem. See http://en.wikipedia.org/wiki/Banach_space#Linear_operators.2C_isomorphisms
Comment: If you have isometry between two spaces and one of them is complete, then the other one is too.
Comment: If I understand correctly, the key observation being that the inverse of an isometry is itself an isometry and therefore continuous, which is why we don't need the open mapping theorem.
Comment: See this: http://math.stackexchange.com/questions/501212/isometry-from-banach-space-to-a-normed-linear-space-maps
Comment: And then use that a closed set in complete space (in this case $l_2$) is complete.
Comment: What you wrote is correct, but it doesn't solve the problem. Is this link helpful? I thought it was clear enough, but write if you have any questions.
Comment: I see that that result would be useful to draw the necessary conclusion in general, but in this particular problem we know already that the map is a bijection. Still, thanks for bringing it to my attention.
Answer: Indeed, in order to use the open mapping theorem we need complete spaces. Hence it's not the good way to show that $V$ is complete.
However, if $(v_n)_{n\geqslant 1}$ is a Cauchy sequence in $V$, then the sequence $(Tv_n)_{n\geqslant 1}$ is Cauchy in $\ell^2$ endowed with the usual norm, hence it converges to some $w$. Since $T$ is surjective, there exists some $v\in V$ such that $w=Tv$, hence $v_n\to v$ in $V$. The proof admits completeness of $\ell^2$, but we can prove completeness of $V$ in the same spirit of the proof of completeness of $\ell^2$.


DDOS attack protection HAPROXY SSL

Question: I'm trying to protect my server from DDOS attacks, my server always have a redirection to the SSL/HTTPS protocol.
but I'm using the next configuration and it's not working
frontend http-in
    bind *:80

    stick-table type ip size 1m expire 5m store gpc0
    tcp-request connection track-sc0 src
    tcp-request connection reject if { sc0_get_gpc0 gt 0 }
    tcp-request connection reject if { src_conn_rate(Abuse) ge 10 }
    tcp-request connection reject if { src_conn_cur(Abuse) ge 10 }
    tcp-request connection track-sc1 src table Abuse

    redirect scheme https if !{ ssl_fc }
    reqadd X-Forwarded-Proto:\ http
    default_backend code

frontend https-in
    bind *:443 ssl crt [SOME CERT]
    reqadd X-Forwarded-Proto:\ https
    default_backend code

    stick-table type ip size 1m expire 5m store gpc0
    tcp-request connection track-sc0 src
    tcp-request connection reject if { sc0_get_gpc0 gt 0 }
    tcp-request connection reject if { src_conn_rate(Abuse) ge 10 }
    tcp-request connection reject if { src_conn_cur(Abuse) ge 10 }
    tcp-request connection track-sc1 src table Abuse

backend code
    stick-table type ip size 1m expire 5m store http_req_rate(10s)
    acl click_too_fast sc1_http_req_rate gt 10
    acl mark_as_abuser sc0_inc_gpc0(http) gt 0
    tcp-request content track-sc1 src
    tcp-request content reject if click_too_fast mark_as_abuser

    balance roundrobin
    option httpclose
    option forwardfor
    cookie JSESSIONID prefix
    server node3 [SOMEIP] check
    server node4 [SOMEIP] check

I'm testing my configuration with the command

ab -n 11 -c 1 [DOMAIN]

but the server never blocks my connection, what i'm doing wrong?
I've got the configuration from here:
https://www.haproxy.com/blog/use-a-load-balancer-as-a-first-row-of-defense-against-ddos/
Comment: Your config doesn't look at all as in the blog.
Answer: Eg.
tcp-request connection reject if { src_conn_rate(Abuse) ge 10 }
acl mark_as_abuser sc0_inc_gpc0(http) gt 0

You don't have tables Abuse nor http. The name of the table is the name of the back- or frontend in which it is defined. You have tables http-in and https-in, eg.
Comment: Yup, and you are only storing ONE variable in the stick-table and then trying to access more than one?
I used Willys blog and tried to make it simpler here:

https://www.loadbalancer.org/blog/simple-denial-of-service-dos-attack-mitigation-using-haproxy-2/

I probably failed though :-).

DDOS attack protection HAPROXY SSL


Como fazer um preview com mais de um arquivo do Ireport

Question: Gostaria de saber como fazer para efetuar um preview de vários relatórios do Ireport, ou seja, criei um projeto de teste para executar os relatórios ou formulários criados para verificar como ficaram antes de colocar no sistema.
Queria passar o array com os nomes e ele executar em lote todos, eu fiz um for e ao executar o segundo em diante, que o "O documento não possui páginas".
public static void main(String[] args) throws JRException {

    final String pastaImagens = "imagens/";
    final String pastaFormulario = "formularios/";

    // aqui deve se colocar o nome do arquivo da imagem do logotipo
    final String imagem = pastaImagens.concat("logoBanco.png");

    PropostaEmprestimoTest propostaEmprestimoTest = new PropostaEmprestimoTest();

    // aqui deve alterar pelo tipo da proposta
    //PropostaEmprestimo proposta = propostaEmprestimoTest.propostaEmprestimoVazia();
    PropostaEmprestimo proposta = propostaEmprestimoTest.propostaEmprestimo();

    String[] formularios = nomesDosFormulario();

    HashMap<String, Object> parametros = new HashMap<String, Object>();

    parametros.put("REPORT_LOCALE", new Locale("pt", "BR"));
    parametros.put("logo", imagem);
    parametros.put("empresa", propostaEmprestimoTest.createEmpresa());
    parametros.put("endereco", EcredUtil.formatarEndereco(proposta.getCliente()));

    setParameterRefinList(parametros, proposta.getRefins());

    List<PropostaEmprestimo> propostaList = new ArrayList<>();
    propostaList.add(proposta);

    JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(propostaList);

    // nome do formulário
    String nomeArquivo = "";
    String formulario = "";

    for (int i = 0; i < formularios.length; i++) {

        nomeArquivo = formularios[i];
        formulario = pastaFormulario.concat(nomeArquivo).concat(".jrxml");

        JasperReport pathjrmxl = JasperCompileManager.compileReport(formulario);
        JasperPrint printReport = JasperFillManager.fillReport(pathjrmxl, parametros, ds);
        JasperViewer.viewReport(printReport);
    }
}

private static String[] nomesDosFormulario() {

    return new String[] { "declaracaoConcordancia",
            "declaracaoDesistenciaPortabilidade", "propostaPortabilidade",
            "propostaPortabilidadeINSS",
            "termoAutorizacaoLiquidacaoEmprestimoINSS",
            "termoAutorizacaoLiquidacaoEmprestimoREFIN" };
}

private static void setParameterRefinList(HashMap<String, Object> parameters, List<ContratoRefin> contratoRefins) {

    int i = 1;
    Double somatorioRefin = contratoRefins.size() > 0 ? 0D : null;;

    for (ContratoRefin contratoRefin : contratoRefins) {

        parameters.put("contrato" + i, contratoRefin.getContrato());
        parameters.put("valor" + i, contratoRefin.getValor());
        parameters.put("dataAntecipacao" + i, contratoRefin.getDataAntecipacao());
        somatorioRefin += Double.valueOf(contratoRefin.getValor());
        i++;
    }
    parameters.put("somatorio_refin", somatorioRefin);
}

Answer: Não sei porque, mas ao remanejar uma linha de código consegui tal feito.
public static void main(String[] args) throws JRException {

    final String pastaImagens = "imagens/";
    final String pastaFormulario = "formularios/";

    // aqui deve se colocar o nome do arquivo da imagem do logotipo
    final String imagem = pastaImagens.concat("logoBanco.png");

    PropostaEmprestimoTest propostaEmprestimoTest = new PropostaEmprestimoTest();

    // aqui deve alterar pelo tipo da proposta
    //PropostaEmprestimo proposta = propostaEmprestimoTest.propostaEmprestimoVazia();
    PropostaEmprestimo proposta = propostaEmprestimoTest.propostaEmprestimo();

    String[] formularios = nomesDosFormulario();

    HashMap<String, Object> parametros = new HashMap<String, Object>();

    parametros.put("REPORT_LOCALE", new Locale("pt", "BR"));
    parametros.put("logo", imagem);
    parametros.put("empresa", propostaEmprestimoTest.createEmpresa());
    parametros.put("endereco", EcredUtil.formatarEndereco(proposta.getCliente()));

    setParameterRefinList(parametros, proposta.getRefins());

    List<PropostaEmprestimo> propostaList = new ArrayList<>();
    propostaList.add(proposta);

    JRBeanCollectionDataSource dataSource = null;
    JasperReport formularioCompilado = null;
    JasperPrint printReport = null;

    for (int i = 0; i < formularios.length; i++) {

        dataSource = new JRBeanCollectionDataSource(propostaList);
        formularioCompilado = JasperCompileManager.compileReport(pastaFormulario.concat(formularios[i]));
        printReport = JasperFillManager.fillReport(formularioCompilado, parametros, dataSource);
        JasperViewer.viewReport(printReport);
    }
}

private static String[] nomesDosFormulario() {

    return new String[] { "declaracaoConcordancia.jrxml",
            "declaracaoDesistenciaPortabilidade.jrxml",
            "propostaPortabilidade.jrxml",
            "propostaPortabilidadeINSS.jrxml",
            "termoAutorizacaoLiquidacaoEmprestimoINSS.jrxml",
            "termoAutorizacaoLiquidacaoEmprestimoREFIN.jrxml" };
}

private static void setParameterRefinList(HashMap<String, Object> parameters, List<ContratoRefin> contratoRefins) {

    int i = 1;
    Double somatorioRefin = contratoRefins.size() > 0 ? 0D : null;;

    for (ContratoRefin contratoRefin : contratoRefins) {

        parameters.put("contrato" + i, contratoRefin.getContrato());
        parameters.put("valor" + i, contratoRefin.getValor());
        parameters.put("dataAntecipacao" + i, contratoRefin.getDataAntecipacao());
        somatorioRefin += Double.valueOf(contratoRefin.getValor());
        i++;
    }
    parameters.put("somatorio_refin", somatorioRefin);
}


Qual a diferença entre as funções wraps e update_wrapper do módulo funtools

Question: No módulo functools da bibliotaca padrão do Python existem duas funções update_wrapper e wraps na documentação da função wraps temos:

This is a convenience function for invoking update_wrapper() as a
  function decorator when defining a wrapper function. It is equivalent
  to partial(update_wrapper, wrapped=wrapped, assigned=assigned,
  updated=updated).

Eu sei que a função update_wrapper é chamada internamente por wraps, gostaria de um exemplo onde se faça necessário o uso da função update_wrapper e não de wraps.
Comment: [Pergunta relacionada](https://stackoverflow.com/questions/15357776/what-is-the-difference-between-functools-wraps-and-update-wrapper) no Soen
Comment: A resposta do @nosklo explica bem. `update_wrapper()` faz a magia toda e `wraps()` serve para usar  `update_wrapper` como decorator.
Answer: Na verdade das duas funções, a única que faz alguma coisa é a update_wrapper. Ela copia, entre outras coisas, __module__, __name__, __qualname__, __annotations__ e __doc__ de uma função para outra.
Já a função wraps não faz nada em si, simplesmente chama a update_wrapper. O que muda são os parâmetros... Para a primeira função, você tem que passar as duas funções como parâmetro ao mesmo tempo, a de origem e a de destino da cópia:
resultado = update_wrapper(x, y) # copia de y para x

Já para a segunda você tem que passar os parâmetros separadamente:
tmp = wraps(y)
tmp(x)      #copia de y pra x

ou
wraps(y)(x)  #copia de y pra x

A razão é facilitar a utilização como decorador, afinal, o que a sintaxe de decorador @ faz é chamar a função passando a outra como parâmetro:
@wraps(y)
def x(...):
    ....

Isso permite definir a função e "wrappar" ela diretamente, em uma sequencia só de comandos.
RESUMINDO, wraps é uma função de conveniência que chama update_wrapper para você de uma forma que fica mais fácil usá-la como decorador.
Comment: Mais uma vez obrigado pela resposta.


How can I execute an RSpec test suite in one app from another app's test suite?

Question: I'm writing a Ruby Gem that integrates with the testing process and I would like write integration tests  that show that it works as I expect end to end. I am including a simple application (TestApp) which uses the Gem.
My gem includes a spec folder, and the test app in its root. The test app includes its tests in a features folder. (There's other stuff in there of course).
my_gem
  |
  - spec
  - test_app
      |
      - features

Before adding the new tests, if I am in the my_gem directory and execute bundle exec rspec, my tests for my_gem execute as expected. If I execute:
cd test_app
bundle exec features

my tests for test_app execute as expected. Now if I add  to my my_gem tests a test:
describe "Test test suite"
    it "executes as expected"
        `bundle exec test_app/features`
    end
end

and execute the tests in my_gem I get the following:
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/tzinfo-1.2.2/lib/tzinfo/data_source.rb:182:in `rescue in create_default_data_source': No source of timezone data could be found. (TZInfo::DataSourceNotFound)
Please refer to http://tzinfo.github.io/datasourcenotfound for help resolving this error.
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/tzinfo-1.2.2/lib/tzinfo/data_source.rb:179:in `create_default_data_source'
...

Following the instructions at the suggested URL leads me down a rabbit hole of adding dependencies to my gem that I would not otherwise require and don't want to force end users of the gem to depend on.
In addition to the above, I've also tried:
exec('bundle exec rspec test_app/features')

and
Dir.chdir('test_app') do
    `bundle exec rspec features`
end

but each time I get the same errors. Interestingly, I get the same errors without the extra test when I execute bundle exec rspec test_app/features from the my_gem directory in the console, but not when I execute the command without bundle exec. Removing bundle exec in the test makes no difference.
What is causing these errors and is there a way that I can execute my test_app test suite from within my my_gem tests so that they don't cause the error?
Answer: I found a solution here: http://makandracards.com/makandra/15649-how-to-discard-a-surrounding-bundler-environment
It turns out that the tests were getting executed under my current environment (someone else might be able to explain this better). The solution is to use Bundler.with_clean_env:
Bundler.with_clean_env do
    Dir.chdir('test_app') do
        `bundle exec rspec features`
    end
end


Difference between Scala pattern matching using variable binding and guard

Question: While pattern matching, what would be a scenario where variable binding would be necessary, where guarding would not suffice?
  "hello" match {
    case greeting @ ("yo" | "hello" | "hola") => println(s"greeting is $greeting")
    case _                                    => println("some other greeting")
  }

  "hello" match {
    case greeting if (greeting == "yo" || greeting == "hello" || greeting == "hola") => println(s"greeting is $greeting")
    case _ => println("some other greeting")
  }

Both of these approaches seem to be solving the same problem.
Comment: They may solve the same problem but I know which syntax is more idiomatic, elegant and readable...
Comment: Using a guard in such way is missing the whole point about pat/mat, rather directly use `if`, or just pat/mat, but wildcard pattern and guard is generally anti-pattern.
Comment: As we all know in scala `if` is an expression and in your second example you are almost doing something similar `val greeting = if (greeting == "yo" || greeting == "hello" || greeting == "hola")` and then printing the value of `greeting` which is not advisable to do atleast in `pattern matching` and morever you are creating the alias of result in first example which is much easier to read and recommended way to do pattern matching
Answer: When matching on sealed traits, there's a huge difference
sealed trait Option[+A]
case class Some[A](get: A) extends Option[A]
case object None extends Option[Nothing]

val x: Option[String] = ???

With pattern matching it's nice and readable:
x match {
  case Some(string) => println("got " + string)
  case None => println("didn't get anything")
}

And also compiler will issue a warning if you miss a case:
x match {
  case Some(string) => println("got " + string)
} // gives you warning that match might fail on None

For guard version, you need to use casts, and there's no warnings for forgotten cases:
x match {
  case some if some.isInstanceOf[Some[_]] =>
    println("got " + some.asInstanceOf[Some[String]].get)
  case none if some == None =>
    println("didn't get anything")
}

Furthermore, guards get ugly quickly when want to check structure deeper than one level. Compare:
case Some(Some(string)) => println(string)

with
case s if s.isInstanceOf[Some[_]] && s.asInstanceOf[Some[_]].get.isInstanceOf[Some[_]] =>
  println(s.asInstanceOf[Some[_]].get.asInstanceOf[Some[String]].get)

Comment: I understand your points, but I am more interested in understanding when would a variable binding come in more handy. Is there a specific scenario or should I just prefer variable binding since its more readable and clean?


Sql sort by query

Question: I have an Sql query that is the union of three queries, for example :
 query1
 Union
 query2
 Union
 query3

I want to ask if there is a way to have the output respective by queries , such that the results of query1 are first in the ResultSet , query2 second and query3 at then end.
Thank you
Comment: add sample data and expected output
Answer: You would normally do this by including a column specifying the query and ordering by that:
select . . .
from ((select q.*, 1 as ordering from (<query1>) q) union all
      (select q.*, 2 as ordering from (<query2>) q) union all
      (select q.*, 3 as ordering from (<query3>) q)
     ) q
order by ordering;

Note:  This replaces the union with union all, so duplicates are not removed.
Comment: @AbdallaIsmail in the first line you list the columns you want instead of writing `*`
Comment: every query is from a different table and has different joins , how can i apply this to my query?
Comment: @AbdallaIsmail . . . Put your queries where `` is.  Or, use CTEs so the code is easier to read.
Comment: Thanks for help , however in the results there is an addition column named ordering, how can i remove it?
Comment: @GordonLinoff I made 3 CTES instead of the 3 queries , however i am using {select COALESCE(Type,'Total found transfers'),total,totalSum from grpSum} instead of q.*. In the results I got Total found transfers Row in the middle of the result set not at the end.How can i solve this?

Sql sort by query


Rails form_for using wrong action

Question: I am using rails 3.2.8 and I am having an issue with form_for:
I have the following form within the view of a different model:
<%= form_for pair, { :method => :put } do |f| %>
     <%= pair.token.value %>
     <%= pair.pair_token.value %>
     <%= pair.freq %>
     <%= pair.distance %>
     <%= f.select :distance, [['', nil], ['Strongly Opposite', -3], ['Moderately Opposite', -2], ['Weakly Opposite', -1],
                              ['No Relationship', 0], ['Weakly Similar', 1], ['Moderately Similar', 2], ['Strongly Similar', 3]], {}, {} %>
     <%= pair.agree %>
     <%= f.select :agree, [['', nil],['True', 1], ['False', 0]], {}, {} %>
     <%= f.submit %>
<% end %>

This form is within the view for a model called tokens.  The page is actually the tokens show.html.  I am getting the response:
No route matches [POST] "/pairs/269671"

I am not sure what is going wrong as I am asking for the  PUT action and the pair object is trying to do a post.
Thanks
Answer: What does your routes file look like?
Rails has default HTTP verbs that it uses for different actions. See here:
http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
Create happens via POST, and update happens via PUT. So, your routes need to support both, which is what Rails does in the background via resources :pairs in config/routes.rb.
You shouldn't need to, if you're using default Rails conventions, override which HTTP verb is used for a given form submission.
And, if you want further insight into these issues, take a look at this SO question:
PUT vs POST in REST
Answer: try this out
<%= form_for pair do |f| %>
     <%= pair.token.value %>
     <%= pair.pair_token.value %>
     <%= pair.freq %>
     <%= pair.distance %>
     <%= f.select :distance, [['', nil], ['Strongly Opposite', -3], ['Moderately Opposite', -2], ['Weakly Opposite', -1],
                              ['No Relationship', 0], ['Weakly Similar', 1], ['Moderately Similar', 2], ['Strongly Similar', 3]], {}, {} %>
     <%= pair.agree %>
     <%= f.select :agree, [['', nil],['True', 1], ['False', 0]], {}, {} %>
     <%= f.submit %>
<% end %>

form_for knows how to handle create/update of the record, so there is no need to specify method.
Answer: Maybe you need to include the token in the form like:
<%= form_for [:tokens, pair] do |f| %>
 <%= pair.token.value %>
 <%= pair.pair_token.value %>
 <%= pair.freq %>
 <%= pair.distance %>
 <%= f.select :distance, [['', nil], ['Strongly Opposite', -3], ['Moderately Opposite', -2], ['Weakly Opposite', -1],
                          ['No Relationship', 0], ['Weakly Similar', 1], ['Moderately Similar', 2], ['Strongly Similar', 3]], {}, {} %>
 <%= pair.agree %>
 <%= f.select :agree, [['', nil],['True', 1], ['False', 0]], {}, {} %>
 <%= f.submit %>
<% end %>

So your routes will be:
[POST] /tokens/:token_id/pairs/:pair_id

If that doesn't work try this one:
<%= form_for [@token, pair] do |f| %>
 <%= pair.token.value %>
 <%= pair.pair_token.value %>
 <%= pair.freq %>
 <%= pair.distance %>
 <%= f.select :distance, [['', nil], ['Strongly Opposite', -3], ['Moderately Opposite', -2], ['Weakly Opposite', -1],
                          ['No Relationship', 0], ['Weakly Similar', 1], ['Moderately Similar', 2], ['Strongly Similar', 3]], {}, {} %>
 <%= pair.agree %>
 <%= f.select :agree, [['', nil],['True', 1], ['False', 0]], {}, {} %>
 <%= f.submit %>
<% end %>

Answer: Just don't hard code method cause same form is being used in different actions and you are breaking Rails conventions.
@object = MyModel.new
<%= form_for @object do |f| %>

same if you doing edit action
@object = MyModel.find(2)
<%= form_for @object do |f| %>

rails will take care about method. Hope it helps !

Rails form_for using wrong action


Associativity of cartesian product and nested ordered n-tuples

Question: for 3 sets $A,B,C$
is $A\times B \times C = A\times (B\times C) = (A\times B)\times C$
OR to be more specific,
is the ordered pair $((a,b),c)=$ ordered triplet $(a,b,c)=$ ordered pair $(a,(b,c))$?
Wikipedia states-

in another article on Wikipedia (and many other e-books and pdfs on the web)-

I think the root of confusion is the nested ordered pairs-
is the ordered pair $((a,b),c)=$ ordered triplet $(a,b,c)=$ ordered pair $(a,(b,c))$?
Please help
Answer: The ordered pairs $\big\langle\langle a,b\rangle,c\big\rangle$ and $\big\langle a,\langle b,c\rangle\big\rangle$ are not equal. Formally, an ordered pair $\langle x,y\rangle$ is the set $\big\{\{x\},\{x,y\}\big\}$, so
$$\big\langle\langle a,b\rangle,c\big\rangle=\left\langle\big\{\{a\},\{a,b\}\big\},c\right\rangle=\left\{\left\{\big\{\{a\},\{a,b\}\big\}\right\},\left\{\big\{\{a\},\{a,b\}\big\},c\right\}\right\}\;,\tag{1}$$
while
$$\big\langle a,\langle b,c\rangle\big\rangle=\left\langle a,\big\{\{b\},\{b,c\}\big\}\right\rangle=\left\{\left\{a\right\},\left\{a,\big\{\{b\},\{b,c\}\big\}\right\}\right\}\;.\tag{2}$$
As the second Wikipedia quotation says, $(A\times B)\times C$ and $A\times(B\times C)$ are equal if and only if at least one of $A,B$, and $C$ is empty, so that
$$(A\times B)\times C=\varnothing=A\times(B\times C)\;.$$
Note, however, that there is always a very natural bijection $h$ between $(A\times B)\times C$ and $A\times(B\times C)$, given by
$$h:(A\times B)\times C\to A\times(B\times C):\big\langle\langle a,b\rangle,c\big\rangle\mapsto\big\langle a,\langle b,c\rangle\big\rangle\;,$$
and in most settings it's both harmless and very convenient to pretend that they're the same set and ignore the technical, formal difference.
Whether either $\big\langle\langle a,b\rangle,c\big\rangle$ or $\big\langle a,\langle b,c\rangle\big\rangle$ is equal to $\langle a,b,c\rangle$ depends on how the ordered triple has been defined. It is perfectly possible to define ordered $n$-tuples as in the first Wikipedia quotation; if one does, then by definition
$$\langle a,b,c\rangle=\big\langle\langle a,b\rangle,c\big\rangle\;.$$
However, for $n>2$ one can also define ordered $n$-tuples to be functions whose domain is $\{0,1,\ldots,n-1\}$. If we adopt that definition, then
$$\langle a,b,c\rangle=\{\langle 0,a\rangle,\langle 1,b\rangle,\langle 2,c\rangle\}\;,$$
the function that sends $0$ to $a$, $1$ to $b$, and $2$ to $c$. Formally this is
$$\left\{\big\{\{0\},\{0,1\}\big\},\big\{\{1\},\{1,b\}\big\},\big\{\{2\},\{2,c\}\big\}\right\}\;,$$
something quite different from the sets in $(1)$ and $(2)$. Once again, though, in most settings it's a matter of indifference which technical definition of ordered $n$-tuple we use: the important thing is that an ordered $n$-tuple is an object with $n$ identifiable components, any of which may be equal, whose positions in the object are specified.
Answer: Brian M. Scott's answer is 100% correct, at least from the viewpoint of material set theory, which is perhaps the currently dominant paradigm. Let me briefly describe a different viewpoint, namely the structural viewpoint.
According to structuralist philosophy, the appropriate question isn't whether or not the set $(A \times B) \times C$ is equal to $A \times (B \times C)$. Rather, we should ask:

("Weak Sameness") Is it true that for all sets $A,B$ and $C$, the sets $(A \times B) \times C$ and $A \times (B \times C)$ are isomorphic?
("Strong Sameness") Is it true that the functor $\lambda A,B,C : \mathbf{Set},(A \times B) \times C$ is isomorphic to the functor $\lambda A,B,C : \mathbf{Set},A \times (B \times C)$?

The answer to the 1st question is clearly yes, using the function Brian denotes $h$ in his answer. In fact, the answer to the 2nd question also a resounding "YES!"; you can try to prove it yourself, if you want, or else try looking up the proof in any basic category theory text. If you're interested in this viewpoint, perhaps check out Sets for mathematics by Lawvere/Rosebrugh, and/or Categories for the Working Mathematician by Saunders Mac Lane.


Date sample code from apple website is not working?

Question: I'm trying to figure out how ti use current date in Swift 3. I read Swift has moved NSDate to Date object. So I checked this sample code:
let dateFormatter = DateFormatter()
let date = Date(timeIntervalSinceReferenceDate: 410220000)

// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // set template after setting locale
print(dateFormatter.string(from: date)) // December 31

// British English Locale (en_GB)
dateFormatter.locale = Locale(identifier: "en_GB")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // // set template after setting locale
print(dateFormatter.string(from: date)) // 31 December

But when I copy and paste this to my Xcode it is showing error that
Use of unresolved identifier DateFormatter
Use of unresolved identifier Date

When I check my swift version from terminal:
xcrun swift -version
Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1)
Target: x86_64-apple-macosx10.9

Am I missing importing some libraries?
EDIT
If I change it to this
let dateFormatter = NSDateFormatter()
let date = NSDate(timeIntervalSinceReferenceDate: 410220000)

It is working fine.
Comment: Given your edit, your project must be configured for Swift 2.3.
Comment: Where did you paste this code? It should go inside some method, of course. In answer to your question, the typical `import` statements (e.g. `import UIKit`) should include this.
Comment: of course it is inside a function.
Answer: You might have the latest Swift version installed on your computer, when  you check it in the terminal, but your project must be running on Swift 2.3.
Swift 2.3 does not know DateFormatter and Date types, it is only introduced in Swift 3.0+.
Comment: Yes I was using swift with code legacy assigned to "yes"


Highcharts : Stacked barchart on hover change the opacity

Question: I am using stacked bar chart from Highcharts .
right now opacity of chart is .3 or 30 % ; On hover I want to change the opacity to 100 % or 1; I want to keep the same color.
I am able to get this work if it is a bar chart by doing
hover: {color: 'rgba(161, 163, 163, 1)' }
I am having issue for stacked bar chart.

  $(container).highcharts({
        chart: {
            type: 'column',
            marginTop: 70,
            marginRight: 100,
            marginLeft: 70
                    //width: 1000
        },
        title: {
            text: ''
        },
        credits: {
            enabled: false
        },
        xAxis: {
            categories: displayData,
            labels: {
                rotation: -90
            }
        },
        yAxis: {
            min: 0,
            ceiling: 100,
            title: {
                text: ''
            }
        },
        tooltip: {
            formatter: function () {
                return '' + this.x + '
' +
                        this.series.name + ': ' + this.y + '
';
            }
        },
        plotOptions: {
            column: {
                stacking: 'normal'
            },
            area:
            {
                fillOpacity:.99
            },
            series: {
                stacking: 'normal',
                states: {
                    hover: {
                        lineWidthPlus: 5

                    }
                }
            }
        },
        series: [{
                name: '% of ' + firstSeriesName,
                data: firstSeriesData,
                color: 'rgba(227, 24, 55, .3)',
                borderRadiusTopLeft: 3,
                borderRadiusTopRight: 3
            },
            {
                name: '% of ' + secondSeriesName,
                data: secondSeriesData,
                color: 'rgba(64, 154, 64, .3)',
                borderRadiusTopLeft: 3,
                borderRadiusTopRight: 3
            }],
        navigation: {
            buttonOptions: {
                height: 40,
                width: 48,
                symbolSize: 24,
                symbolX: 23,
                symbolY: 21,
                symbolStrokeWidth: 2,
                borderRadiusTopLeft: 5,
                borderRadiusTopRight: 5
            }
        }
    });
Answer: You can define color like this
states: {
  hover: {
    color: 'rgba(68, 188, 93, 1)'
  }
}

in each series.
Example based on your code - http://jsfiddle.net/tosx33ae/1/


django: get() returned more than one Freelancers -- it returned 3

Question: i am trying to assign a freelancer to a particular gig but it shows get() returned more than one Freelancers -- it returned 3!. I have tried getting the logged in freelancer to is trying to create the git like this freelancer = get_object_or_404(Freelancers, user=user)  and before i save the form i assign the value like this  new_form.creator = freelancer .
views.py
@login_required
def create_gig(request):
    user = request.user
    freelancer = get_object_or_404(Freelancers, user=user)
    if request.method == "POST":
        form = CreateGig(request.POST, request.FILES)
        if form.is_valid():
            new_form = form.save(commit=False)
            new_form.user = request.user
            new_form.creator = freelancer
            new_form.slug = slugify(new_form.title)

            new_form.save()
            messages.success(request, f'Gig Created Successfully, Would be Live Soon')
            return redirect('freelance:listings')
    else:
        form = CreateGig()
    context = {
        'form': form
        }
    return render(request, 'freelance/create.html', context)

models.py
class Gigs(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gig_user')
    creator = models.ForeignKey(Freelancers, on_delete=models.CASCADE, related_name='gig_creator')
    title = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Enter what you will do", default=" I will ")

Comment: `get_object_or_404` will return one instance if it encounters more than one instance maching the filter it will generate exception. Check your `Freelancers` it would have 3 instance of user.
Comment: Show your Freelancers model, that might help to narrow down why you're getting 3 results.
Answer: In my code, it is getting a logged-in user instance and then creating the gig by assigning the freelancer to the created form.
@login_required
    def create_gig(request):
        freelancer = Freelancers.objects.get(user = request.user )
        if request.method == "POST":
            form = CreateGig(request.POST, request.FILES)
            if form.is_valid():
                new_form = form.save(commit=False)
                new_form.creator = freelancer
                new_form.slug = slugify(new_form.title)

                new_form.save()
                messages.success(request, f'Gig Created Successfully, Would be Live Soon')
                return redirect('freelance:listings')
        else:
            form = CreateGig()
        context = {
            'form': form
            }
        return render(request, 'freelance/create.html', context)

You also don't need this line in your view:
new_form.user = request.user

Comment: okay, it means you need to use get instead of filter. just replace filter with get
Comment: because the gig is already created now try creating another gig
Comment: try logging in from another user
Comment: and you should also handle this user for better user experience. means if a gig already created from a specific user or id then you should display an error message to use if user try to create another gig with the same id
Comment: okay let me try it
Comment: i tried it now and this is the error i got  - Cannot assign "]>": "Gigs.creator" must be a "Freelancers" instance.
Comment: okay let me try it
Comment: i think the error is gone, now i used get. but it now shows this - NOT NULL constraint failed: freelance_gigs.user_id
Comment: okay, let me create another gig now
Comment: i just logged in from another user and created a new gig and it working fine. tnx alot.
Comment: can you please change the Freelancers.objects.filter(user = request.user ) above to Freelancers.objects.get(user = request.user ). So i can mark it as an answer?
Comment: edited with the correct code
Comment: i tried creating another gig but with the exact exising name of another gig. Then it throws a slug error like this - UNIQUE constraint failed: freelance_gigs.slug -  i dont know if you have an idea on what i should do
Comment: because at the moment only one user can create only one gig. you need to change your model structure
Comment: Your Gigs model have a relation of 1 to many, which means a user can create only 1 gig at the same time. If you want to allow a user to create multiple gigs using 1 account then you need to make a relation of many to many
Comment: okay let me change my model


Create a field instance programmatically on a taxonomy vocabulary

Question: I'm trying to create a module which creates a taxonomy vocabulary on installation of the module, and creates one text field on the taxonomy vocabulary/term. But I'm getting the following error when I enable my module:

[error] FieldException: Attempt to create an instance of field field_flickr_photoset on forbidden entity type taxonomy_term. in field_create_instance() (line 468 of
  /var/www/www.example.com/htdocs/modules/field/field.crud.inc).

First of al, why a Forbidden entity type? Is it not possible to create a field on a taxonomy vocabulary through code? Or am I missing some parameters?
I used very similar code to create a node type and attach fields to it, which currently works without any problems. I didn't think that changing the entity type would cause such problems.
I tried searching on google and here on how to do this, but all I get is people who are asking how to attach a taxonomy term reference field to a node type, which is not what I'm asking. It's attaching a text field to a taxonomy term/vocabulary.
Answer: If you look in taxonomy_entity_info() you'll see this code that defines the taxonomy_vocabulary entity type:
$return['taxonomy_vocabulary'] = array(
  'label' => t('Taxonomy vocabulary'),
  'controller class' => 'TaxonomyVocabularyController',
  'base table' => 'taxonomy_vocabulary',
  'entity keys' => array(
    'id' => 'vid',
    'label' => 'name',
  ),
  'fieldable' => FALSE,
);

The important bit to note is 'fieldable' => FALSE...that's why it's 'forbidden' to add fields to that type.
The taxonomy_term entity type is fieldable so you won't have any problem adding field instances to one of those.
If you really want to add a field to the vocabulary, you'll need to implement hook_entity_info_alter() to change the vocabulary entity to 'fieldable' => TRUE (I've done it before, it's perfectly safe):
function MYMODULE_entity_info_alter(&$info) {
  $info['taxonomy_vocabulary']['fieldable'] = TRUE;
}

Comment: I actually didn't know that `taxonomy_vocabulary` and `taxonomy_term` were different entities. So thanks for this info. When I first written the code I set the `entity_type` for the field as `taxonomy_vocabulary` and enabled the module. And even after I disabled my module, it didn't remove the field from db, and it was still set as taxonomy_vocabulary entity type field in {field_config} table. So even after changing my code, and disabling re-enabling cc all-ing I was scratching my head. Now I deleted the record and re-enabled and now the field is created. Your info was very useful thanks.
Answer: Drupal 7
If you check the code which causing that Exception, you'll see the following condition:
  // Check that the field can be attached to this entity type.
  if (!empty($field['entity_types']) && !in_array($instance['entity_type'], $field['entity_types'])) {
    throw new FieldException(t('Attempt to create an instance of field @field_name on forbidden entity type @entity_type.', array('@field_name' => $instance['field_name'], '@entity_type' => $instance['entity_type'])));
  }

That means the field which you're trying to define has restricted entity_types attribute which has list of entities to which the field can be attached.
So either you need to define your entity via the following property of your field:
  'entity_types' => array(0 => 'allowed_entity_type'),

leave it empty, or just try to remove entity_types attribute from the field definition at all.

Don't forget to clear the caches in Performance.
If the problem persist, you may try to remove the field to be able to recreate it again (e.g. drush eval "field_delete_field('field_which_is_broken');").


how to rename a column in linux?

Question: I have a table like this
 bedGraph  chrom=chr1 chr1:0-000
    1000    0
    2000    0
    3000    0.003802
    4000    0.046175
 bedGraph  chrom=chr2 chr2:5000-6000
    5000    0.103756
    6000    0.161337

 EXPECTED RESULTS

bedGraph  chrom=chr1 rep
    1000    0
    2000    0
    3000    0.003802
    4000    0.046175
 bedGraph  chrom=chr2 rep
    5000    0.103756
    6000    0.161337

and I would like to rename the 3rd col only (the 2nd cols changes along the file). Is possible to do that using sed?
Thanks!
Comment: post the expected result
Comment: I've just posted the expected results as suggest!
Answer: For the given example, this one-liner works:
awk 'NF==3{$3="rep"}7' file

Comment: @KamilCuk yes....
Comment: That `7` on the end can be any number except zero?
Answer: sed '/bedGraph/s/chr[12]:.*/rep/'

For the lines containing badGraph substitute chr[1 or 2]:<anything> for rep.
sed 's/^\([[:space:]]*[^[:space:]]\+[[:space:]]\+[[:space:]]\+[^[:space:]]\+[[:space:]]\+\)[^[:space:]]\+$/\1 rep/'

Filter and remember first two words in the line with [[:space:]]*[^[:space:]]\+[[:space:]]\+[[:space:]]\+[^[:space:]]\+[[:space:]]\+ which bassically means: <spaces or nothing><not spaces><spaces><not spaces><spaces> then filter out the third word with [^[:space:]]\+ and print the first two words (ie. the first match) and substitute the third column with rep.

how to rename a column in linux?


Display a value other than the one in the model

Question: I have this text box defintion in my view
@Html.TextBoxFor(model => model.MaxNumberOfExtensions == "0" ? "Unlimited" : model.MaxNumberOfExtensions, new { required = "required", id = "maxNumberOfExtensions" })

What I am trying to do is say,

If the value MaxNumberOfExtensions is 0 then display 'Unlimited' in
  the text box, otherwise display, the value in the field
  MaxNumberOfExtensions

This does not work at runtime.  It gives the error
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

What is the correct way of doing this?
Answer: Such complex lambda expressions are not supported by the HTML helpers. They only support property access and indexer access expressions.
The correct way is to use a view model of course. So you would have a property which will already contain the required text based on the value of your domain model.
For example:
public class MyViewModel
{
    public string MaxNumberOfExtensions { get; set; }
}

and then in your controller action rendering this view:
public ActionResult SomeAction()
{
    SomeDomainModel model = ...
    MyViewModel viewModel = new MyViewModel();
    viewModel.MaxNumberOfExtensions = model.MaxNumberOfExtensions == "0" ? "Unlimited" : model.MaxNumberOfExtensions;
    return View(viewModel);
}

and then in the view:
@model MyViewModel
...
@Html.TextBoxFor(x => x.MaxNumberOfExtensions, new { required = "required", id = "maxNumberOfExtensions" })

Alternatively if your application is currently not following best practices (not using view models) you could write a custom template where you could perform this task.
For example, add the following template in ~/Views/Shared/EditorTemplates/FormattedNumberOfExtensions.cshtml:
@model string
@{
    var value = Model == "0" ? "Unlimited" : Model;
}

@Html.TextBox("", value, new { required = "required", id = "maxNumberOfExtensions" })

and then in your view:
@Html.EditorFor(x => x.MaxNumberOfExtensions, "FormattedNumberOfExtensions")


Form implemented using form_alter not always showing the changed contents in select list

Question: I have created a module to alter a  select dropdown of a view's exposed filter like this
function myform_form_alter(&$form, &$form_state, $form_id) {

   if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-staff-page") {
$form['field_department_tid']['#type'] = "select";
    $form['field_department_tid']['#size'] = null;
    $form['field_department_tid']['#default_value'] = $form['field_department_tid']['#options']['All'];
    $form['field_department_tid']['#options'] = array(
      'All' => t('All Offices'),
      '6' => t("Office of the Chairman"),

'Administration & Financial Affairs Department' => array(
            '2'=> t('Administration'),
            '3' => t('Finance'),
            '4' => t('HR'),

         ),

    );
 }

But occasionally it is showing the original unaltered select list instead of the new select list and in such cases, I need to clear cache every time to display the changed dropdown.
What is the problem with my code?
Answer: Try this way
Change
$form['field_department_tid']['#default_value'] = $form['field_department_tid']['#options']['All'];
to
$form['field_department_tid']['#default_value'] =  t('All Offices');
Comment: It is not a sing value that is not showing, but entire set


Prove $\bigcap\limits_{n=1}^{\infty}(-\frac{1}{n},1+\frac{1}{n})=\left[0,1\right]$

Question: Good night. I make a proof of this prove:

Prove $\bigcap\limits_{n=1}^{\infty}(-\frac{1}{n},1+\frac{1}{n})=\left[0,1\right]$

Proof:
Be $\left\{ x_{n}\right\} =\left\{ -\frac{1\;}{x}:\;x\;\epsilon\:\mathbb{N}\right\}  $ and $\left\{ Y_{n}\right\} =\left\{ \frac{1}{y}+1\;:\;y\;\epsilon\:\mathbb{N}\right\}$ sequences such then $lim_{n\rightarrow\infty}\frac{1}{x_{n}}=0$ and $lim_{n\rightarrow\infty}\frac{1}{y_{n}}+1=1$ but when i see the intersection that confused me because the intersection is $Ø$. Can someone help me?
Comment: Prove the double inclution
Answer: Hint 1: $[0,1] \subset(-\frac{1}{n},1+\frac{1}{n})$.
Hint 2: If $x \in \cap_{n=1}^{\infty}(-\frac{1}{n},1+\frac{1}{n})$ then
$$-\frac{1}{n} < x < 1+\frac{1}{n}$$
What happens when you take the limit by $n$?
Comment: I'm an idiot. sorry -.- Good answer!


How to evaluate a single image in PyTorch model?

Question: I used this code to train a model:
def train(model, epochs):
    for epoch in range(epochs):
        for idx, batch in enumerate(train_loader):
            x, bndbox = batch    # unpack batch
            pred_bndbox = model(x)# forward pass
            #print('label:', bndbox, 'prediction:', pred_bndbox)
            loss = criterion(pred_bndbox, bndbox)     # compute loss for this batch
            optimiser.zero_grad()# zero gradients of optimiser
            loss.backward()     # backward pass (find rate of change of loss with respect to model parameters)
            optimiser.step()# take optimisation step
            print('Epoch:', epoch, 'Batch:', idx, 'Loss:', loss.item())
            writer.add_scalar('DETECTION Loss/Train', loss, epoch*len(train_loader) + idx)    # write loss to a graph

train(cnn, epochs)

torch.save(cnn.state_dict(), str(time.time()))# save model

def visualise(model, n):
    model.eval()
    for idx, batch in enumerate(test_loader):
        x, y = batch
        pred_bndbox = model(x)
        S40dataset.show(batch, pred_bndbox=pred_bndbox)
        if idx == n:
            break

How do I evaluate the model prediction on a single image to check the operation of the neural network?
Comment: Hi, what do you mean when saying you want to 'upload' an image to the NN? Did you mean evaluating the prediction of the network on a new image?
Comment: Yes. Please, help me
Answer: You can use:
model.eval()              # turn the model to evaluate mode
with torch.no_grad():     # does not calculate gradient
    class_index = model(single_image).argmax()   #gets the prediction for the image's class

This code will save the network's prediction as the index of the class in the class_index variable. You have to save the image you would like to examine in the single_image variable in the right shape.
Hope that helps.


Find all possible values of det(P)

Question: Suppose that $P$ is an $n \times n$ matrix such that $P^T(P^3)=I$ , where $I$ is the $n \times n$ identity matrix. Find all possible values of $\det(P)$.
I solved to $P^T=P^{-1}(P^{-1})(P^{-1})$ where $\det(P)=\det(P^{-1}(P^{-1})(P^{-1}))$ but I'm pretty sure it's incorrect.
Answer: $\det (P^t P^3)=1\implies \det P^t\det P^3=1\implies (\det P)^4=1\implies \det P=1\text {or}\det P=-1$
Answer: Edit: I just noticed that you probably meant the 'T' to denote the transpose of $P$. In that case the train of thought is similar, but now along with the property $\det AB=\det A\det B$ you need also to use that $\det A^t=\det A$. This being said the calculations are easy:
$$
1=\det I=\det (P^t)\det (P^3)=\det P(\det P)^3=(\det P)^4\Rightarrow \det(P)\in\{1,i,-1,-i\}.
$$

You don't need to cancel $P^3$ (as an aside; notice that that would need a justification that $P$ is not singular). Just take determinants in $P^TP^3=I$ (another aside; notice that $P^TP^3=P^{T+3}$) to arrive at
$$
1=\det I=\det (P^{T+3})=\det(P)^{T+3}.
$$
So $\det{P}$ satisfies the equation $1=x^{T+3}$; i.e. $\det(P)$ is a $(T+3)-$root of unity. More explicitly
$$
\det(P)=e^{2\pi i\frac{k}{T+3}}
$$
for some $0\leq k<T+3$.

Find all possible values of det(P)


Upgrading Neo4J 3.3.4 -> 3.4.0 missing dependency "com.sun.jersey.multipart.FormDataParam", what is the replacement?

Question: When upgrading Neo4J from 3.3.4 to 3.4.0 the dependency "com.sun.jersey.multipart.FormDataParam" no longer exists. We are using it like this:
@POST
@Path("/path/to/api")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response restorePost(@Context HttpServletRequest httpRequest,
                            @FormDataParam("file") InputStream file) {

    return service.processRequest(httpRequest, file);
}

Is it another way of doing this in 3.4.0?
Answer: After asking this question to the Neo4J support I got this answer:

Unlike in Neo4j 3.3.5 which includes:
$NEO4J_HOME/lib/jersey-server-1.19.jar
  $NEO4J_HOME/lib/jersey-core-1.19.jar
  $NEO4J_HOME/lib/jersey-multipart-1.19.jar
  $NEO4J_HOME/lib/jersey-servlet-1.19.jar
3.4.0 no longer includes:
$NEO4J_HOME/lib/jersey-multipart-1.19.jar
since it is no longer used by the core Neo4j database. However you
  should be able to simply add a new dependency similar to what is
  described at
  https://mvnrepository.com/artifact/com.sun.jersey.contribs/jersey-multipart/1.9.1
  then this should address your issue.

So in my scenario this was solved by adding this dependency to our pom.xml:
<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.19.3</version>
</dependency>

Note that the version differs from what is linked in the response from Neo4J. Not sure if the answer is wrong, or if it is because I am testing this on a release candidate. But in my version 3.4.0 RC Neo4J server, the jersey version included is 1.19.3 and not 1.19.1 (check in the "lib" folder of your Neo4J server).
Apart from this you need to make sure that the proper jar's are deployed to your Neo4J plugins folder. In our case we do this with a configuration in maven, but you could also add the dependencies manually. Note that jersey-multipart 1.19.3 is dependent on mimepull 1.9.3, so you need to add both.


How to add Array Object and Data to JSON in Laravel

Question: How to add Array Object and Data to JSON in Laravel
$json = {'id':5, 'name':'Hassan'};
I want to add new object role and value Admin to $json
I want result like
$json = {'id':5, 'name':'Hassan', 'role':'Admin'};
Answer: You could decode the JSON, add the values you want and then encode it back to JSON:
$data = json_decode($json, true);

$data['role'] = 'Admin';

$json = json_encode($json);

json_decode() Docs
json_encode() Docs
Answer: Try this
$object = json_decode($json);
$object->role = 'Admin';
$json = json_encode($object)


Multiple Regression independent variables

Question: I have a relative straight forward question.
Lets say we have a typical multiple regression model. With lets say 3 different independent variables. If one independent variable with its beta parameter has a very low value compared to the other parameters, lets say 0.00025.
Would it be better to not include this variable in the model?
/Peter
$$
\log y = 5.32 + 0.3\log(x_1) +0.15(x_2) + 0.00025(x_3) + u
$$
where y is measured in pounds and the independent variables are measured in percentages.
Comment: That must depend on what the purpose of your model is, what the scale of that variable is, what the relationship between the predictor variables is.
Comment: okej @mdewey I've added a more specific model, does this help?
Comment: my theory is that we can omit x_3 since, it has such a small effect on logy.
Answer: There is no relation between estimated parameter value and it's significance.
Basically, parameter should be selected based on the significance of the partial r-squared value not the estimated value of the parameter.
You can try the step wise regression method and build the model.


Render image field with custom image style in custom block template

Question: This is basically the same question as this, but I can't get the technique to work in a custom block type template: https://drupal.stackexchange.com/a/219052/71100

I have a custom block type called link_card.
I have an image field field_link_card_image.
I have a List(text) field to select an image style field_link_card_size
I have confirmed that field_link_card_size is outputting the key, which is the machine name of my image style.
My theme template is block--bundle-link-card.html.twig. It overrides block.html.twig. The template is working.
I want to render the image and use the image size selected.

Here is the first way I tried based on what worked in the answer for page.html.twig.
{% set image = {
  '#theme':      'image_style',
  '#style_name': content.field_link_card_image_size[0],
  '#uri':        file_url(content.field_link_card_image['#items'].entity.uri.value),
  '#alt':        content.field_link_card_image[0].alt,
 } %}

 {{ image }}

I get this white screen error:

Error: Call to a member function transformDimensions() on null in
  template_preprocess_image_style() (line 303 of
  core/modules/image/image.module).

And this error in Report Log in the admin area:

Warning: array_flip(): Can only flip STRING and INTEGER values!

If I replace the value for '#style_name: with the just the  machine name of one of my image styles (such as square) it almost kinda works.

The image renders but with the _incorrect image src: /D8_1318_LinkCard/web/files/styles/square/public//D8_1318_LinkCard/web/files/2019-06/unsplash_1500x500-4.jpg?itok=c16MdkOY (You can see it's sort of repeated itself.)
The alt text doesn't come in at all, so I probably have that wrong, too.

This leads me to believe that there are problems how I'm pulling in the field content from the block.
Here is the second way I tried:
{% set image = content.field_link_card_image[0] %}
{% set imagestyle = content.field_link_card_image_size[0] %}|
{% set image = setimage|merge({ '#image_style': imagestyle }) %}

{{ image }}

The errors are:

Error: Call to a member function transformDimensions() on null in
  template_preprocess_image_style() (line 303 of
  core/modules/image/image.module).
and
Warning: array_flip(): Can only flip STRING and INTEGER values!
and
Error: Call to a member function transformDimensions() on null in template_preprocess_image_style()

This works if I do imagestyle = 'square'. But of course I'm trying to use the value of the field.
Here the problem seems to be an issue with getting in the field_image size to sneak into the variable imagestyle.
TLDR: How do I render an image field with a custom style in the custom block template.
Thanks!
Answer: This module is exactly what I need. https://www.drupal.org/project/field_image_style
:D


Version control on Entity form type submissions

Question: A project collecting data from multiple entity forms was handed over to me. My client requested the implementation of a review mechanism for the data that are stored in entity form submissions.
The reviewers should have the ability to edit the submissions while they are keeping the initial content intact. The features extend to comparison between the various versions of the submission along with comments that can be attached to each version explaining the scope of the changes.
Pretty much the exact functionality that Node revisions are covering at the moment.
Unfortunately I just discovered that revisions are not available for entityform submissions (Add revision support to submissions) leading me to a dead end.
So, I seek some experienced guidance if there is a workaround to this, that I'm unable to see.

Could I create this versioning system somehow with the current data
structure?
Would it be able to migrate the data collected from form submissions to content type nodes so that I can use their revision framework (along with Diff and Node Compare modules)?
Answer: Trying to hack data out of an Entity form seems to make things unnecessarily more complicated, so I decided to redesign the whole form as a content type create form, while using entity reference fields to link the various instances.


Find $\frac{dy}{dx}$ when $x=\cos^3{\theta}$, $y=\sin^3{\theta}$

Question: Answer:

How did they get the 1st step in the 1st place?
Comment: $$\dfrac{\mathrm dy}{\mathrm dx}=\dfrac{\frac{\mathrm dy}{\mathrm d\theta}}{\frac{\mathrm dx}{\mathrm d\theta}}$$
Answer: For the sake of having an answer...
They used the chain rule,
$$\frac{dy}{dx} = \frac{dy}{d\theta} \frac{d\theta}{dx} = \frac{dy}{d\theta} \Big/ \frac{dx}{d\theta} = \frac{3\sin^2\theta \cos\theta}{-3\cos^2\theta\sin\theta}$$


mysql master-slave partitioned table doesn't exists

Question: I use create Raw Data Files for mysql-master-slave replication,after setup,It's return table xxx doesn't exists when query on the partitioned tables,but it's work ok on the other tables.
And,When I change to use mysqldump, It's all work ok.
Can anyone help me to fix this problem?
Answer: If the partition table did not work but the other tables did and the mysqldump worked fine, my best guess would be that your Partitioned data is not stored in the same place as the rest of your data.  Thus, when you used the tar, zip, or rsync method to copy your data directory, you left out the data that made up the partitioned table.  You would need to locate where the partitioned data is stored and moved that over along with the rest of the data directory.
Based on your comment below, however, you have what is called the famous Schrodinger table. Based on Schrodinger's Cat paradox, This is where Mysql thinks that the table exists, because it shows up when you run show tables, but does not allow you to query of it; as in it exist but does not exist.
Usually this is as a result of not copy over the metadata (as in the ibdata1 file, and the ib_logfiles) correctly.  One thing that you can do to test this is, if possible, remove the partition from the tables and try your rsync again.  If you are still getting this error, it has nothing to do with the fact that the table is partitioned.  Then, this test would lead me to believe that you did not copy all the data over correctly.
Comment: thanks,but I'm sure the partitioned data is in the same place,I compare the  whole data directory ,and found the two directory's  file is all same,and `show tables` also list the Partitioned table,but cannot query.
Comment: Thanks again,Now I change the master running on ubuntu  and It's work fine.(on windows8.1 before) ,I guess there's something different between these two os for running mysql,but i can't find the answer.