Evaluating Coldfusion directory path for file existence

Question: I've been working on a script for a couple of weeks tweaking it as need be to track CGI.script_PATH and CGI.REFERER on an older coldfusion install which has over 500 .cfc and .cfm pages. I just hit a snag in my code. It doesn't capture a page name in the CGI.Referer variable when the referer is a folder. I'm sure it has something to do with Coldfusion automatically looking for an index.cfm even when the path doesn't include an actual file name.
How can I write an addition to my script where if there is no .cfm in the CGI.Referer, it can search the directory and capture the default file set to load or at least search for an occurrence of index.cfm or default.cfm?
Here is a block of code handling the referer element:

    <cfset referer_path_and_file = "">
    <cfset referer_path = "">
    <cfset referer_file_name = "">
    <cfset script_path_and_file = "">
    <cfset script_path = "">
    <cfset script_file_name = "">

    <cfif cgi.HTTP_REFERER neq ''>

      <cfset referer_path_and_file = ListFirst(CGI.HTTP_REFERER, "?")>

      <cfset referer_path = ListDeleteAt(CGI.HTTP_REFERER, ListLen(CGI.HTTP_REFERER, "/"), "/")>
      <cfset referer_path = ReplaceNoCase(referer_path, "https", "", "All")>
      <cfset referer_path = ReplaceNoCase(referer_path, "http", "", "All")>
      <cfset referer_path = ReplaceNoCase(referer_path, "://machine1.fss.com", "", "All")>
      <cfset referer_path = ReplaceNoCase(referer_path, "://www_dev.fss.com", "", "All")>
      <cfset referer_path = ReplaceNoCase(referer_path, "://www.fss.com", "", "All")>
      <cfset referer_path = ReplaceNoCase(referer_path, "://10.11.2.60/", "", "All")>
      <cfset referer_path = referer_path & "/">
      <cfset referer_path = ReplaceNoCase(referer_path, "/", "\", "All")>

      <cfset referer_file_name = ListLast(referer_path_and_file, "/")>

    </cfif>

<cfset currentHeader = CGI.HTTP_REFERER >
<cfset currentScriptPage = CGI.SCRIPT_NAME >

<cfset reverseScriptPage = ReReplace(#currentScriptPage#, "/", "\","ALL")>

<cfset newScriptPage = ListSetAt(#reverseScriptPage#, 1, "#reverseScriptPage#") >

The code just strips the CGI script and referer variables of their http web references and then strips the directory structure portion and inserts the .cfm file name and original directory structure into the DB table, but not before reversing the / characters to \ because they want to be able to setup a script which will loop through the table and see something like "\admin\controls\" and auto create those directories, then copy the example.cfm page into that directory. The aim is to 1.) determine which of the 500 cfc/cfm files are still used in the application, then copy them and their directory structure to a new location, and redesign those files in a new technology that isn't Coldfusion.
Update:  I'm running into an issue with my code. When I test it, it works well, truncating the http domain portion. However once its operating live under the web server, it doesn't truncate the url despite there being a ReplaceNoCase method to do so:
Under the web root in the wwwroot root, it works well giving this output:
refererPage: testFiles.cfm  refererPath = testCodes\MVC
Under the live site I get this:
refererPage: client_display refererPath: **:\dev.fss.com\admin_area**
despite having this line in my code:

Any idea why?
Comment: Are you tracking real users? The CGI.HTTP_REFERER is only set when a link is followed. It can also be blocked by things like Norton Internet Security so you can't guarantee it'll exists. The HTTP_REFERER shouldn't be affected by the running the default directory index file.
Comment: _"I'm sure it has something to do with Coldfusion automatically looking for an index.cfm even when the path doesn't include an actual file name"_ More like the web server default file list.
Comment: Not related to your question, but you might miss all the cfc files with this approach.  Those are often accessed with createobject or cfobject inside the cfm files.
Comment: Please clarify.  In the first paragraph you are talking about the cgi scope and in the second, it's the url scope.
Comment: Its an internal application on a server. Management wants to see what pages get hit and what pages people go to next because there are 500 cfc/cfm files. Their idea is to monitor those variables and store then in a DB table along with the path name. Last night they ran into the issue of how the application is designed that if they click to a directory called Project, it directs them there but doesn't log the page they are going to in the Project folder.
Comment: "Management wants to see what pages get hit and what pages people go to next". You know the web server can / does pretty much log this for you, right? It can log every request made.
Comment: I tried to express that to them but they want it the way they want it which has led to the above code.
Answer: If your cgi.http_referrer variable does not not contain .cfm, you can use the DirectoryExists function on your referer_path variable.  If it returns true, you can use the DirectoryList function or cfdirectory tag to search for an occurrence of index.cfm or default.cfm.
Answer: they may have this going through a framework (like a model view controller). Without knowing more about the URL structures and the naming conventions.
And without knowing more I would say you are dealing with dynamic content (especially if it is going through index.cfm). Even in an engine with 500 pages, there is a unique identifier and that should be your target not a file.  So we may assume there are no files at all and we are just calling parts and pieces from here and there to make a page based on your URL querystring, local variables and/or form variables.
So tables are your friends.  Examine your URL structure, try to break down the parameters, search the code base for those parameters and once you have located the area that builds the pages then somewhere there set your tracking tools (a bit higher up stream in the page request stream).
Maybe with some code snippets we could give you a more precise answer but for now this should at least get you looking at your code base for clues.


Setting background-color of select options in JQuery

Question: I have a page with multiple select boxes, as per the following:
<code><select name="item-0-status" id="id_item-0-status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>
</code>
These are being auto-generated in django, so it is not possible to apply css classes, ids or attributes directly to the options. The select elements have ids of 'item-0-status','item-1-status','item-2-status' etc.
How can I add css colours to the options using the id of the select element?
I have tried to follow the code here: How do you select a particular option in a SELECT element in jQuery?
This has lead me to do, e.g. the following for setting 'offline' options to red:
<code>$('select[id$=-status][id^=id_item-]').children().find('option[value="2"]').css('background-color','#FF0000');
</code>
but this has no effect.
How can I make this work? I realise support for this varies between browsers, but this is not an issue. For the purposes of this question working in Firefox 3.6 is enough.
Answer: You have a typo.
It should be background-color. You have missed 'r'
Comment: well spotted and corrected - but still doesn't work, unfortunately
Answer: Something like should work though note that I am not so sure.
<code>$(function(){

$('#id_item-0-status').children().each(
        function (){
            if($(this).val() == 2){
                $(this).css({'background':'red'});
            }
        }
);

})
</code>
Comment: this works, thanks, but any idea how I can now set the background colour of the selects to that of the selected options? I've tried $('select[id$=-status][id^=id_item-]').css({'background':$('option:selected',this).css('background')});
Comment: or,better (but still not working):$('select[id$=-status][id^=id_item-]').each(function(){$(this).css({'background':$('option:selected',this).css('background')});});
Comment: never mind, I have asked this as a separate question http://stackoverflow.com/questions/5068087/set-background-colour-of-select-to-selected-option-in-jquery


dotnetzip zipping large files - Unity app stops responding

Question: I'm using dotnetzip in my Unity3d Project for zipping/unzipping files. I am using a code similar to below to zip some part zip files. If the files are small everything works as expected. But if these files are large(each one around 100mb) then the Unity app(exe) stops responding. I don't get any errors. But I think it's due to memory issues because it works if the files are small.
Can you please tell me how to fix this issue.
<code>  String[] filenames = { "ReadMe.txt", "c:\\data\\ABC_ExportContent.zip.001", "c:\\data\\ABC_ExportContent.zip.002", "c:\\data\\ABC_ExportContent.zip.003"};
  using (ZipFile zip = new ZipFile())
  {
    zip.AddFiles(filenames);
    zip.Save("Archive.zip");
  }
</code>
Update - Today I tested this with the Task Manager opened, and the app becomes not responding due to CPU usage goes to 100%. Not actually due to memory as I guessed.
Please let me know how to overcome this issue.
Update 2 - Since I couldn't find a solution for this, decided to move to SharpZipLib and so far it seems to be doing good.
Comment: If you crash, then there is an Exception with a Stack Trace.  Could you please show them to us
Comment: Hi Richard, as I mentioned in my question what happens is Unity stop responding. I have put try catch in the code and running the Unity app in debug mode. But I don't get any errors in the log. When this happens I have to go to task manager and kill the app. Thanks
Comment: You might want to take out the parts of  your question which refers to a crash, given that you're stated in comments that the app doesn't crash, and this is going to confuse people.
Comment: Thanks Poldie. I removed the word crash.
Comment: Have you waited enough for it to end?
Comment: Yes Jcl, I think so. When I test in a Windows 7 machine  after waiting for a long time, I need to kill the process. In a Windows 8 machine I have to restart the machine, Even task manager doesn't respond when this happens. Whole computer seems to freeze.
Comment: Btw. if you need to do a lot of exporting or other repetitive tasks, uTomate (http://www.ancientlightstudios.com/utomate/) may be an option for you. It also contains an action for zipping up stuff (http://www.ancientlightstudios.com/utomate/documentation/actiondocs/build_zip_file.html). And it's designed to keep Unity responsive while it's doing it's work.
Comment: Thanks Jan, I'll have a look at it.
Answer: We got this fixed by using SharpZipLib instead of dotnetzip.


Dificuldade com IF e ELSE do Javascript - Retornar texto do resultado na tela

Question: DÚVIDA: Como faço um IF ELSE com javascript para que exiba um texto (Ex: Aprovado) quando localizar uma determinada palavra (Ex: Verde). Meu código atual é esse abaixo, mas não está funcionando e não consigo encontrar o problema. Sou iniciante com Javascript, então caso alguém souber me ajudar agradeço!
var status_atual = 'Azul'; //

   if (status_atual = "Verde") {
  return 'Aprovado';
} else if (status_atual = "Vermelho") {
  return 'Reprovado';
} else if (status_atual = "Amarelo") {
  return 'Incompleto';
} else if (status_atual = "Azul") {
  return 'Novo';
} else {
  return 'Cor e status não identificados!';
}

Eu precisava fazer com que o resultado fosse exibido na tabela, igual como é feito no PHP com a função echo, dessa forma por exemplo:
<?php

$status_atual = 'Azul';

   if ($status_atual = 'Verde') {
  echo 'Aprovado';
} else if ($status_atual = 'Vermelho') {
  echo 'Reprovado';
} else if ($status_atual = 'Amarelo') {
  echo 'Incompleto';
} else if ($status_atual = 'Azul') {
  echo 'Novo';
} else {
  echo 'Cor e status não identificados!';
}

?>

Exemplo do resultado IF ELSE sendo exibido na tabela:
Comment: Note que tanto o código JS quanto o PHP apresentam problemas.
Comment: Operador de comparação é `==` ou `===`.  O `=` sozinho é operador de atribuição.
Answer: Em muitas linguagens de programação, assim como no javascript, o operador = não é um comparador, mas atribui o valor a uma variável.
Nesse seu caso, substirua-o, onde estiver fazendo comparações, por ==.
No Javascript há também o operador ===. Procure ler sobre a diferença entre os 2.
Segue fiddle de exemplo: https://jsfiddle.net/jhtcsLw7/.
Comment: Certo, obrigado pela resposta. Preciso colocar esse if else dentro desse outro código heheheh, teria alguma ideia de como seria feito isso?

`{
                "render": function ( data, type, row ) {
                    return 'CODIGOIFELSEAQUI';

                },
                "targets": 3
            },`
Comment: Tentei fazer dessa forma, consegue dar uma olhada? https://jsfiddle.net/h9e1mkcn/
Comment: @BrunoFariasProgramming criei um fiddle como exemplo. Note que no fiddle que vc enviou vc trocou o `=` na `atribuição` também.
Comment: Concordo com o @tvdias. Sei que na pergunta menciona claramente que quer usar um `if/else`. Porém, nestes casos penso que seria mais adequado utilizar um `switch/case`. Fica a sugestão.


Matrix multiplication property

Question: Help me please!
So consider  two matrices of integer numbers:
$$ A_{m,n}, B_{n,k}  $$
I want to find product of them
$$ C_{m,k} = A_{m,n} B_{n,k} $$
Let
$M$ is a very large number.
$$ D = (10^0,10^M,10^{2M},..,10^{(k-1)M}) $$
$D_j$ – $j$-th element of $D$.
 $B_j$ – $j$-th row of $B$.
 $A_i$ – $i$-th row of $A$.
 $C'_i$ - $i$-th element of vector $C'$, so that:
$$C'_i = A_i⋅ ((B_1⋅D),..,(B_n⋅D)) ,∀ i = 1..m$$
Then
$$c_{i,j}={C'_i/D_j} \mod D_{2} , ∀ i = 1..m,j = 1..k, c_{i,j} \in C$$
So I need a $2n^2$ multiplication (or not ?) for calculate a matrix product via precalculation $D$ and $(D ⋅ B_j)$ for all $j = 1..n$.

First question: Is it really $O(n^2)$ multiplication for calculate
matrix product, or not ?
Second question: Are there other possible ways to multiplication
matrix with this idea? (for example another operations )
Comment: http://en.wikipedia.org/wiki/Matrix_multiplication#Algorithms_for_efficient_matrix_multiplication
Answer: There is no known $\mathcal{O}(n^2)$ general algorithm for matrix multiplication, although it is believed that one may exist.
The closest one can get is a (recent) slight improvement over the Coopersmith-Winograd algorithm.
Regarding your second question, there may be other techniques to come up with a matrix product, but almost certainly they include addition and multiplication. There is no obvious "natural" operation, but the rules of algebra certainly allow us to create our own. Nevertheless, working in the group of integers, there are only so many operations that we can concoct without resorting back to addition and multiplication.
Comment: You mean $\mathcal{O}(n^{2+\epsilon})$?

Matrix multiplication property


Instruments simultaneous playing in a different key

Question: I am learning to play the piano using Bartok's Mikrokosmos. Piece 44 is written for 2 pianos, but the first piano is playing in a different key than the second piano.

What are the keys the pianos are playing in?
How does this work (how does it sound good)?
Is there other music that uses multiple keys simultaneously ?
Comment: I think not everyone would say that it **does** sound good. Also, it might help to think of it as not being in more than one key, but as not being in any key at all. There are many, many 20th century works that were composed without being in a particular key.
Comment: If it's not in a key at all, why would the composer than choose these key signatures (except for the fact that they maybe are the most common in the piece)?
Comment: Your guess is one possible explanation - that Bartok wrote in key signatures that had the most used accidentals. Or it could be that Bartok did not actually write key signatures when he wrote it and an editor/publisher added them to try to make it "more readable" or something.
Comment: Related [question](https://music.stackexchange.com/q/11054/2600): Why does key signature give accidentals, which are never used.
Answer: While Schoenberg was escaping from Common Practice harmony into serialism, Bartok was experimenting with modes and polytonality.  (In this piece, he's using both!)  He chose to use non-standard key signatures - not always terribly helpful in the pieces where he constantly mixed his modes!
If you're interested in 'Bartok Theory' dip into this:
https://open.bu.edu/bitstream/handle/2144/6387/Horan_Mother_Annunciata_%201957_web.pdf?sequence=3
See also Strange key signature?
Answer: there are actually no different keys:

Piano I is for the beginner
Piano II is the teacher's part

Both parts are in E major (until measure 12, where after he goes poly tonic)
But as in Piano I there is no D# and A# to play - Bartok doesn't notate them! ...
probably to make the beginner to focus on the 2 black keys for the matching fingers. This was certainly a pedagogical intention.


Writing an infinite series as the sum of the series

Question: I have $$ y= \sum_{x=1}^\infty \frac{k}{10^{k^{2}}} =0.1002000030000004...$$
I want to be able to write this in terms of a geometric progression.
I've tried doing $ 10y = 1+\frac{2}{10^3}+\frac{3}{10^8}+...$, but I can't seem to get it in the form where I can sum an infinite series.  I can see the difference between the powers of the terms is like 3,5,7... but I'm not sure how I could use this?
Comment: A little thing here, but the bottom of your summation should say $k = 1$.
Answer: There's no "nice" closed form. However, you can notice the following:
$$\sum_{k = 1}^{\infty} \frac{k}{10^{k^2}} = \sum_{n = 1}^{\infty}  \sum_{k = n}^{\infty} \frac{1}{10^{k^2}}$$
Furthermore, $$\sum_{k = 1}^{\infty} \frac{1}{10^{k^2}} = \frac{1}{2} \left(\theta_3 \left(0, \frac{1}{10}\right) - 1\right)$$
From this, one can derive similar expressions for $\displaystyle \sum_{k = 2}^{\infty} \frac{1}{10^{k^2}}$ and so forth by subtracting $\frac{1}{10^{k^2}}$
Answer:
I can see the difference between the powers of the terms is like 3,5,7...

It is not geometric precisely because of this; the terms of a geometric series have a constant ratio, e.g. the series $\dfrac12,\dfrac14,\dfrac18,\dfrac{1}{16}$ has the constant ratio of $\dfrac12$. But in your series, the ratio changes, i.e. the ratio between the first two numbers is
$$
\frac{2}{10000}\frac{10}{1} = \frac{2}{1000}
$$
but the next ratio is
$$
\frac{3}{10^9}\frac{10^4}{2} = \frac{3}{2}10^{-5}
$$
Answer: you could make it a geometric series with your observation. e.g.,
observe what
$$-\frac{k}{10^{k^2}}+\frac{k-1}{10^{(k-1)^2}}=\frac{-k+(k-1)(10^{2k-1})}{10^{k^2}}$$
so your series is
$$\sum_{k=1}^{\infty}\sum_{n=1}^{k} \frac{10^{2n-1}-1)n-10^{2n-1}}{10^{n^2}}$$
which has 2 geometric progressions in the numerator, but the denominator cannot be modified to form any sort of geometric progression


Autofs mount nfs issues

Question: I'm having some issues getting autofs to work properly on a new Centos 5.5 installation.
Please find Exports from my storage servers:
/san/files  *(rw,sync,no_subtree_check,no_root_squash)
/san/mail   *(rw,sync,no_subtree_check,no_root_squash)

On my client my auto.master looks as follows:
/home   /etc/auto.home --timeout=60
/net    -hosts

auto.home:
vmail -fstype=nfs,hard,intr,nodev,nosuid,rw xxx.xxx.xxx.xxx:/san/mail

I'm not wanting to use NIS however my bigger picture is to have a fall over nfs server however at the present time im just working with the single server.
I can manually mount the nfs share perfectly fine using "mount -t nfs xx.xxx.xxx.xxx:/san/mail /home/vmail" (when mountpoint exists Obv)
permissions on /home:
# ls -shalt /home
total 8.0K
   0 drwxr-xr-x  2 root root    0 May  3 08:51 .
8.0K drwxr-xr-x 24 root root 4.0K May  3 08:51 ..

The problem is when trying to go to /home/vmail i get the following:
# ls -shalt /home/vmail
ls: /home/vmail: No such file or directory

running "automount -vf" I get the following output:
Starting automounter version 5.0.1-0.rc2.143.el5_5.6, master map auto.master
using kernel protocol version 5.01
mounted indirect on /home with timeout 60, freq 15 seconds
mounted indirect on /net with timeout 300, freq 75 seconds
attempting to mount entry /home/vmail
lookup(program): lookup for vmail failed
failed to mount /home/vmail

Using /net/xxx.xxx.xxx.xxx/san/mail/ works!
Please help with any pointers? I'm at a dead end now.
Comment: Does it help to `mkdir /home/vmail` ?
Comment: no my understanding of autofs should create this folder dynamically, when automount is running i am unable to create the directory.
Comment: Oh OK. Sorry, it's been over 10 years since I worked with automount ....
Comment: Do you have selinux enabled, BTW? SElkinux under Centos 5.x tend to be pretty strict.
Answer: lookup(program) means automount thinks your map is an executable, does it have the executable bit set?
lookup(file) is what you should be seeing
See http://www.squarebox.co.uk/cgi-squarebox/manServer/automount.8.

Autofs mount nfs issues


Multiple linear regression through orthogonal matrices

Question: An example of linear regression could look like:
$min \sum_{i=0}^{m}||x_i A - y_i||_2^{2}$, where ${x_i, y_i} \in \mathbb{R}^n$ and $A \in \mathbb{R}^{n\times n}$.
I am interested in knowing how do I solve such problem with an of the following extra constraints, $A$ is an orthogonal matrix or $A$ is a rotation matrix.
Notice that a rotation matrix is orthogonal.
Answer: This problem is called the orthogonal Procrustes problem. You can find a closed form solution in terms of the SVD at http://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem.


Linear Algebra: Change of Basis

Question: Let $A[a,b,c]$ and $B[d,e,f]$ be two non-standard bases. I have to find the $3\times3$ matrix that will convert a vector defined in terms of $A$ to $B$.
My solution is:
Let's assume a standard basis $O[e_1,e_2,e_3]$.
Now, the rotation matrix $R(A\to O)$ to change basis from $A$ to $O$ is:
$
\begin{bmatrix}
ax & bx & cx \\
ay & by & cy \\
az & bz & cz
\end{bmatrix}
$
and $R(O\to B)$ is
$
\begin{bmatrix}
ax & ay & az \\
bx & by & bz \\
cx & cy & cz
\end{bmatrix}.
$
So, $R(A \to B)=R(A \to O)\cdot R(O\to B)$.
Is this the correct solution?
Thanks a lot.
Answer: I see no reason you should expect a rotation matrix. Two arbitrary bases are just related by multiplication by an invertible matrix (of which many are not rotations!)
Moreover, when thinking about this sort of question for the first time it's wise to develop some notation which denotes the coordinate vectors for differing choices of basis. I'm not seeing this in your post.
A typical notation goes like this: if $v \in \mathbb{R}^3$ and $v = c_1f_1+c_2f_2+c_3f_3$ then $\Phi_{\beta}(v)=[v]_{\beta} = [c_1,c_2,c_3]^T$ where $\beta = \{ f_1,f_2,f_3 \}$ is a (possibly) nonstandard basis. You can derive all sorts of short-cut formulas for $\mathbb{R}^3$ since the coordinate map $\Phi_{\beta}$ is a linear transformation on $\mathbb{R}^3$.
If you search posts about change of basis (many of which are linked over $\rightarrow$
then you'll get a better idea about how to communicate these sort of calculations. Unfortunately, at the present, I can't quite get what you're saying in the post.
Answer: Let $\alpha=\{a,b,c\}$ and $\beta=\{d,e,f\}$ be bases for $\mathbb{R}^3$ (thinking of elements of $\mathbb{R}^3$ as column vectors). Then the matrix $A=[a|b|c]$ transitions from $\alpha$-coordinates to standard-coordinates. Likewise the basis $B=[d|e|f]$ transitions from $\beta$-coordinates to the standard-coordinates. So $B^{-1}$ goes from standard-coordinates to $\beta$-coordinates. Thus $B^{-1}A$ goes from $\alpha$-coordinates (to standard and then standard) to $\beta$-coordinates and is the matrix you're looking for.
Example: Let $\alpha=\left\{\begin{bmatrix} 1\\0\\0 \end{bmatrix},\begin{bmatrix} 1\\1\\0 \end{bmatrix},\begin{bmatrix} 1\\1\\1 \end{bmatrix}\right\}$ and $\beta=\left\{\begin{bmatrix} 1\\-1\\0 \end{bmatrix},\begin{bmatrix} 0\\1\\-1 \end{bmatrix},\begin{bmatrix} 1\\0\\1 \end{bmatrix}\right\}$.
Then ${\bf v}=\begin{bmatrix} 1\\2\\3 \end{bmatrix} = (-1)\begin{bmatrix} 1\\0\\0 \end{bmatrix}+(-1)\begin{bmatrix} 1\\1\\0 \end{bmatrix}+3\begin{bmatrix} 1\\1\\1 \end{bmatrix}$. So ${\bf v}$ in $\alpha$ coordinates is $[{\bf v}]_\alpha = \begin{bmatrix} -1\\-1\\3\end{bmatrix}$.
Let $A=\begin{bmatrix} 1 & 1 & 1 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{bmatrix}$. Notice that $A[{\bf v}]_\alpha = \begin{bmatrix} 1 & 1 & 1 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{bmatrix}\begin{bmatrix} -1\\-1\\3\end{bmatrix} = \begin{bmatrix} 1\\2\\3\end{bmatrix}$.
Let $B=\begin{bmatrix} 1 & 0 & 1 \\ -1 & 1 & 0 \\ 0 & -1 & 1\end{bmatrix}$. Then $B^{-1} = \frac{1}{2}\begin{bmatrix} 1 & -1 & -1 \\ 1 & 1 & -1 \\ 1 & 1 & 1 \end{bmatrix}$ and so $B^{-1}A = \begin{bmatrix} \frac{1}{2} & 0 & -\frac{1}{2} \\ \frac{1}{2} & 1 & \frac{1}{2} \\ \frac{1}{2} & 1 & \frac{3}{2} \end{bmatrix}$ goes from $\alpha$ to $\beta$-coordinates.
An alternate way to compute this change of basis matrix is to create the augmented matrix: $[B|A] = [d|e|f|a|b|c]$ and row-reduce. This will compute $[I|(B^{-1}A)]$ where $B^{-1}A$ is the desired matrix.

Linear Algebra: Change of Basis


Every element in a finite (abelian) group $G$ is an $n$'th power if $\,\gcd(n,|G|)=1$

Question: How to prove that every element in a finite (abelian) group $G$ is an $n$'th power if $\,\gcd(n,|G|)=1$
Comment: @TobiasKildetoft no i dont know  Bezout's identity !!
Comment: Ok, alternative way then. Do you see that $x\mapsto x^n$ is a homomorphism from $G$ to itself?
Comment: @TobiasKildetoft yes i can see that..lets say that x=a^t then
x^n= a^t*n
Comment: Why do you assume $x$ is some power of some other element? That is not what it means to be a homomorphism.
Comment: @TobiasKildetoft it means that x↦x^n is  bijection ..am i right ?
Comment: Why? We were going to use the fact that it is a homomorphism to show it is a bijection. I am not really sure which direction you are going.
Comment: Sorry im really confused with this question..i dont know how to start thinking
Comment: Well, can you see why the map I mentioned is a homomorphism?
Comment: @TobiasKildetoft no ! can you explain more ?
Comment: Do you know the definition of a homomorphism?
Comment: @TobiasKildetoft for every a,b $\in$G f(ab)=f(a)f(b)
Comment: Ok, and does this map satisfy that?
Comment: x-->x^n , b-->b^n  ,

x^n*b^n =xb^n,

xb--> xb^n,
@TobiasKildetoft yes
Comment: Good (apart from a few missing parentheses). Now, we would like to show that this map is injective. So what elements are in the kernel?
Comment: e=e^n @TobiasKildetoft
so e is in the kernel
Comment: Right. Can there be any other elements?
Comment: True, but make sure you know why this is the case (i.e. which assumption makes this true).
Comment: @TobiasKildetoft let me try to explain why
Comment: @TobiasKildetoft its because (O(G),n)=1
Answer: Perhaps you don't know it by the name "Bezout Equality", but it is probably the easiest way to go here.
It says that if $\;x,y,\in\Bbb Z\;$  and if $\;\;$ g.c.d. $(x,y)=d\;$ , then there exist $\;m,n\in\Bbb Z\;$ with $\;mx+ny=d$ .
In our case, there exist $\;a,b\in\Bbb Z\;$ s.t. $\;a\mathcal O(G)+bn=1\;$ , and then for any $\;g\in G\;$ we get
$$g=g^1=g^{a\mathcal O(G)+bn}=\left(g^{\mathcal O(G)}\right)^a\left(g^b\right)^n=1 x^n=x^n\;,\;\;\text{with}\;\;x:=g^b$$
Comment: This answer also shows that you don't need $G$ to be abelian.
Answer: Here are my comments expanded into an answer which does not use Bezout's identity (I will in fact at the end use this to prove Bezout's identity purely using group theory).
Let's take a more general setup and prove something a bit stronger:
Let $G$ be any finite group and assume that $n$ is coprime to $|G|$. Then for any $x$ in $G$ there is a $y\in G$ such that $y^n = x$ and such that $y = x^m$ for some $m$.
Proof: Let $H = \langle x\rangle$ and consider the map from $H$ to itself given by $a\mapsto a^n$. This is easily seen to be a homomorphism since $H$ is abelian.
We also see that since $n$ is coprime to $|G|$ it is also coprime to $|H|$ and hence the only element $h\in H$ with $h^n = 1$ must be $1$ (by Lagrange). This means that the map above has trivial kernel, and hence that it is injective.
But since $H$ is finite, this also means that the map is surjective, and hence $x$ must be in the image, which precisely means that there is some $y\in H$ with $y^n = x$ (and since we have $y\in H$ we have $y = x^m$ for some $m$).
To prove Bezout's identity from the above, let two coprime numbers $k$ and $n$ be given. We need to find integers $a$ and $b$ such that $ak + bn = 1$. Note that by definition this means that we need to find an integer $b$ such that $bn\equiv 1\pmod{k}$.
To apply the above statement, let $G = \langle x\rangle$ be the cyclic group of order $k$. The above says that there is an integer $m$ such that $(x^m)^n = x$.
But $(x^m)^n = x^{mn}$, and if this equals $x$ then this means that $x^{mn - 1} = 1$, i.e. that $mn - 1$ is divisible by the order of $x$, which is $k$. By definition, this means that $mn - 1\equiv 0 \pmod{k}$ or in other words that $mn\equiv 1\pmod{k}$, so $m$ is the integer we were looking for (the $b$ above).
Comment: Yes, deriving Bezout from Lagrange is one possible way to organize  arithmetic (number theory in $\Bbb Z$), e.g. see the paper of Pierre Samuel that I cite [here](https://math.stackexchange.com/a/1151530/242), which examines all permutation of few foundational theorems as bases for arithmetic.
Answer: As in $U(\Bbb Z/m),\,$ it's easy to take $n$'th roots in a group if $\,n\,$ is coprime to the group order $\:\!|G|$.
Theorem $ $ Compute $\,n$'th root in group $\,G\,$ by raising to power $\frac{1}n\!\pmod{\!|G|}\,$ if $\,\gcd(n,|G|)\! =\! 1$
Let $\,\color{#0a0}{f=|G|}.\,$ By Bezout $\,\gcd(n,f)\!=\!1$ $\Rightarrow \exists\:\!  n' \equiv \frac{1}n\equiv n^{-1}\!\pmod{\!f},\, $ so  $\ \color{#c00}{nn' = 1 + fj}\,$ so
$$ \bbox[8px,border:2px solid #96f]{{a^{\Large\color{c00} n} = b \iff a =  b^{\:\!\Large n'},\ \ n' \equiv \frac{1}n\!\!\!\!\pmod{\!f}}}\qquad$$
$\begin{align}{\bf Proof}\ \ \   &b = a^{\large n}\,\Rightarrow\, b^{\large n'}\! = a^{\large \color{#c00}{nn'}}\! = a^{\large\color{#c00}{1+fj}} = a(\color{#0a0}{a^{\large f}})^{\large j} = a\\
&a = b^{\large n'}\!\Rightarrow\, a^{\large n} = b^{\large\color{#c00}{n'n}} = \,b^{\large\color{#c00}{1+fj}} = \,b(\color{#0a0}{b^{\large f}})^{\large j} = b \end{align}$
because, $ $ by Lagrange's Theorem,  $\ \color{#0a0}{f=|G|\,\Rightarrow\, a^f = 1 = b^f}$
Answer: This is related to the OP. In fact, the converse of this statement is also true, i.e., if every element in a finite group $G$ is a $n$-th power, then $\gcd(n,|G|) =1$.
We prove this by contradiction. First we note that the map $G \to G: g \mapsto g^n$ is surjective by assumption. Since $G$ is finite, this map is also injective. Now we suppose that $\gcd(n,|G|)>1$, then there's a prime number $p$ dividing both $n$ and $|G|$. By Cauchy's theorem, there is an element $x\in G$ with order $p$. Since $x$ is a $n$-th power (by assumption), there is $y\in G$ such that $x = y^n$, and $|y^n|=p$, i.e., $y^{np}=(y^p)^n = 1$. Because the map $g\mapsto g^n$ is injective and $1^n = 1$, we know that $y^p=1$. This forces $|y|=p$. Therefore, $y^n = y^{p\cdot (n/p)} =1$. But then this contradicts the fact that $|y^n| = p$ and we proved the claim.
Comment: Welcome to MSE! Interesting additional lemma, +1. "$x$ is a $p$-th power" should be "$x$ is a $n$-th power" though. I can't suggest that edit because of the minimum limit of six characters.
Comment: Thanks! I'll change it now


Adjust values in a list by normalizing_zybook

Question: 1.7 LAB: Adjust values in a list by normalising
When analysing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalising to values between 0 and 1, or throwing away outliers.
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, adjust each integer in the list by subtracting the smallest value from all the integers.
Ex: If the input is:
5
30
50
10
70
65

the output is:
20
40
0
60
55

The 5 indicates that there are five integers in the list, namely 30, 50, 10, 70, and 65. The smallest value in the list is 10, so the program subtracts 10 from all integers in the list.
Anyone can solve this question in python?
This is my code.
arr1 = []

input = int()

for i in range(0,input):
    e = int(intput())

arr1.append(e)

k = min(arr1)

for i in range(0,val):
    arr1[i] = arr1[i] - k

for i in range(0,val):
    print(arr1[i])

Here is the error.
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    arr1.append(e)
NameError: name 'e' is not defined

Comment: We're not here to do your homework for you.
Answer: You could use list comprehension:
input = [5,30,50,10,70,65]
input = input[1:]
output = [i - min(input) for i in input]

print(output)
[20, 40, 0, 60, 55]

Comment: As with the OP, you have made the mistake of using the name of an existing (useful) function as a variable name. You should aim to avoid this.
Answer: This is the way I solved it
list = []

values = int(input())

for n in range(values):
    number = float(input())
    list.append(number)

largest = max(list)

for number in list:
    number = number / largest
    print(f'{number:.2f}')

Comment: You shoul always try to avoid using the names of built-in function or types like `list` as variable names.
Answer: def get_minimum_int(nums):
    low = min(nums)
    return low

if __name__ == '__main__':
    num = int(input())
    nums = []
    while num != -1:
        nums.append(num)
        num = int(input())
    l = get_minimum_int(nums)
    for n in nums:
        print(n - l)

Answer: idk if your question ever got answered but I also had the same type of task.
Mine was:
"For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
5
30.0
50.0
10.0
100.0
65.0

the output is:
0.30
0.50
0.10
1.00
0.65

The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0."
So this is how I solved mine:
x = int(input())
dislist = []

i = 1
while i <= x:
    y = float(input())
    dislist.append(y)
    i += 1

q = max(dislist)

for item in dislist:
    item = item / q
    print('{:.2f}'.format(item))

Tell me what you think :)
Answer: A few problems I can see with your code.

input = int()`

input in the name of a function that gets an input string from the user. int() simply returns 0. You are assigning the value 0 to a variable named input, making the input function no longer accessible.

for i in range(0,input):
  e = int(intput())

Because input is 0, this is an empty range. The loop never runs. Which is good because it would have no idea what intput is.
Because the loop never runs, e is never defined, which is why you get the error you do.
Another style note: arr1 is a list so using a name that suggests it's an array is misleading.
You likely wanted something like the following tweaked version of your code.
n = int(input())

vals = []
for _ in range(0, n):
    e = int(input())
    vals.append(e)

k = min(vals)

for i in range(0, n):
    arr1[i] = -= k

for i in range(0, n):
    print(arr1[i])

Gathering the input numbers could be simplified using a list comprehension.
vals = [int(input()) for _ in range(0, n)]

Answer: When analyzing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This adjustment can be done by normalizing to values between 0 and 1, or throwing away outliers.
For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow.
Output each floating-point value with two digits after the decimal point.
This is how I went about solving this problem.
# Get the number of floating points the user wants to use
user_num = int(input())

# Declare num_list to store floating points from the user
num_list = []

# Get floating point numbers from the user and add them to num_list
for i in range(user_num):
    num_list.append(float(input()))

# Find the largest floating point
max_num = max(num_list)

# Divide each floating point number in num_list by the max_num and print the result
for num in num_list:
    num_result = num / max_num
    print(f'{num_result:.2f}')

Answer: This may be helpful for your lab:
user_int = []

while True:
  user_input = int(input())
  user_int.append(int(user_input))

  if len(user_int) > (int(user_int[0])):
    break

user_int.pop(0)

vals = min(user_int)

for user_vals in user_int:
  my_vals = user_vals - vals
  print(my_vals)

Comment: Hi and welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour). Thanks for contributing an answer but can you also add an explanation on how your code solves the problem?
Comment: I can't help but feel like your approach to looping to gather the values from input is excessively "clever" and obfuscated vs. prompting for a number to input and then clearly looping that many times.


newline character in comm perl script

Question: There is a newline character getting inserted between the 2 filenames.
How do I avoid this?
$diff = `comm -3 "/tmp/${PATH1U}_${SITE1}_s_${USER} /tmp/${PATH2U}_${SITE2}_s_${USER}"|wc -l`;

This is the error message while executing:

comm: missing operand after `/tmp/file1\n /tmp/file2\n'
Comment: `chomp` the filenames after reading them.
Answer: Two problems:

$USER's value ends with a newline. You can chomp it away. Fix:
chomp($USER);

You are passing one very long and incorrect path instead of two. Fix:
`comm -3 '/tmp/${PATH1U}_${SITE1}_s_${USER}' '/tmp/${PATH2U}_${SITE2}_s_${USER}' | wc -l`

But that's a hackish way of creating shell literals. Cleaner:
use String::ShellQuote qw( shell_quote );

my $comm_cmd = shell_quote('comm', '-3',
   "/tmp/${PATH1U}_${SITE1}_s_${USER}",
   "/tmp/${PATH2U}_${SITE2}_s_${USER}");

`$comm_cmd | wc -l`

newline character in comm perl script


Brouwer's fixed point theorem $n=1$ case

Question: I have read a sketch of the proof for Brouwer's fixed-point theorem, i.e. that every continuous $f:\mathbb{D}^n\to\mathbb{D}^n$ has a fixed-point ($n\ge1$).
The idea is to construct a retract $r:\mathbb{D}^n\to\mathbb{S}^{n-1}$ such that $r\circ i=id_{\mathbb{S}^{n-1}}$. Taking $H_{n-1}$ yields the contradiction $[\mathbb{Z}\to 0\to\mathbb{Z}]=id_{\mathbb{Z}}$.
But as far as I see this only works for $n>1$, not for $n=1$, since $H_0(\mathbb{D}^1)=\mathbb{Z}\neq 0$.
So what can I do in the $n=1$ case?
Comment: Use reduced homology $\tilde H_0$ rather than $H_0$ itself.
Comment: Are you asking how to show that a continuous function $f:[-1,1] \to [-1,1]$ has a fixed point?
Comment: $\mathbb{S}^0$ consists of two points, so $\tilde{H}_0 (\mathbb{S}^0) \cong \mathbb{Z}$. And $\mathbb{D}^1$ is connected, thus $\tilde{H}_0 (\mathbb{D}^1) = 0$.
Comment: There still does not exist a retract $[-1,1]\to \{-1,1\}$. Or use the Intermediate Value Theorem.
Comment: Is $\tilde{H}_{n-1}$ still a covariant functor?
Comment: Well yes, it is! But what is $\tilde{H}_0(\mathbb{S}^0)$?
Comment: May you please give further details to $\tilde{H}_0(S^1)=Z$?
Comment: @user114179 Do you mean $\mathbb{S}^0$? For $\mathbb{S}^1$, the group $\tilde{H}_0$ is trivial, as $\mathbb{S}^1$ is connected. For details, you should know that $H_0$ is generated by the connected components, and $H_0 \cong \tilde{H}_0 \oplus \mathbb{Z}$.
Answer: Basically just expanding on von Eitzen's comment here if you don't see it immediately.
For $n=1$, $f:[-1,1]\rightarrow[-1,1]$ and $f$ is continuous.
Define $g:[-1,1]\rightarrow[-2,2]$ such that $g=f(x)-x$. Note that $g$ is also continuous.
Now if either $g(1)$ or $g(-1)$ is equal to zero, we are done.
If not, $g(-1)<0$ and $g(1)>0$.
By the intermediate value theorem, $\exists c\in (-1,1)$ such that $g(c)=0$.
$g(c)=0\implies f(x)=x$.


Criar uma coluna com o segundo maior valor da linha

Question: Gostaria de criar uma coluna no dataframe teste com o segundo maior valor da respectiva linha, tal como fiz para encontrar o Min e Max.
library("matrixStats")
teste <- read.table("https://raw.githack.com/fsbmat/StackOverflow/master/teste.txt",header = TRUE)
teste$ML_anual <- round(rowSums(teste[,c("LIQ_Jan2013","LIQ_Fev2013","LIQ_Mar2013","LIQ_Abr2013","LIQ_Mai2013","LIQ_Jun2013","LIQ_Jul2013","LIQ_Ago2013","LIQ_Set2013","LIQ_Out2013","LIQ_Nov2013","LIQ_Dez2013")],na.rm = T)/12,digits=2)
teste$Min <- round(rowMins(as.matrix(teste[,c("LIQ_Jan2013","LIQ_Fev2013","LIQ_Mar2013","LIQ_Abr2013","LIQ_Mai2013","LIQ_Jun2013","LIQ_Jul2013","LIQ_Ago2013","LIQ_Set2013","LIQ_Out2013","LIQ_Nov2013","LIQ_Dez2013")]),na.rm = T),digits=2)
teste$Max <- round(rowMaxs(as.matrix(teste[,c("LIQ_Jan2013","LIQ_Fev2013","LIQ_Mar2013","LIQ_Abr2013","LIQ_Mai2013","LIQ_Jun2013","LIQ_Jul2013","LIQ_Ago2013","LIQ_Set2013","LIQ_Out2013","LIQ_Nov2013","LIQ_Dez2013")]),na.rm = T),digits=2)

O banco de dados original tem 130 mil linhas, por isso, gostaria de encontrar uma função que não necessite de um laço for para agilizar o processo!
Answer: Aqui vão duas funções que calculam o segundo maior elemento em cada linha de uma tabela. A segunda função usa o conhecimento de qual é o valor máximo em cada linha para calcular o 2º maior.
SegundoMaiorLinha <- function(DF){
  m2 <- rep(-Inf, nrow(DF))
  for(i in seq_len(nrow(DF))){
    M <- max(DF[i, ], na.rm = TRUE)
    for(j in seq_len(ncol(DF))){
      if(DF[i, j] > m2[i] && DF[i, j] != M) m2[i] <- DF[i, j]
    }
  }
  m2
}

SegundoMaiorLinha2 <- function(DF, Max){
  m2 <- rep(NA, nrow(DF))
  for(i in seq_len(nrow(DF))){
    DF[i, which(DF[i, ] == Max[i])] <- -Inf
    m2[i] <- max(DF[i, ], na.rm = TRUE)
  }
  m2
}

Este vetor cols serve só para simplificar o código. Depois testam-se ambas as funções e os resultados são iguais.
cols <- c("LIQ_Jan2013","LIQ_Fev2013","LIQ_Mar2013","LIQ_Abr2013",
          "LIQ_Mai2013","LIQ_Jun2013","LIQ_Jul2013","LIQ_Ago2013",
          "LIQ_Set2013","LIQ_Out2013","LIQ_Nov2013","LIQ_Dez2013")

SegundoMaiorLinha(teste[, cols])
#[1] 10509.62 13577.62  5628.19

SegundoMaiorLinha2(teste[, cols], teste$Max)
#[1] 10509.62 13577.62  5628.19

Teste de desempenho. A diferença não é grande mas a segunda é mais rápida.
library(microbenchmark)
library(ggplot2)

mb <- microbenchmark(
  fun = SegundoMaiorLinha(teste[, cols]),
  fun2 = SegundoMaiorLinha2(teste[, cols], teste$Max),
  times = 1e3
)

print(mb, order = "median")
autoplot(mb)

Answer: Uma forma mais rápida e simples de se fazer é via apply:
cols <- c("LIQ_Jan2013","LIQ_Fev2013","LIQ_Mar2013","LIQ_Abr2013","LIQ_Mai2013","LIQ_Jun2013","LIQ_Jul2013","LIQ_Ago2013","LIQ_Set2013","LIQ_Out2013","LIQ_Nov2013","LIQ_Dez2013")
teste$seg.max <- apply(teste[,cols], 1, FUN = function(x){sort(x, decreasing = T)[2]})

Comparando com as demais:
SegundoApply <- function(DF){
  apply(DF, 1, FUN = function(x){sort(x, decreasing = T)[2]})
}
mb <- microbenchmark(
  fun = SegundoMaiorLinha(teste[, cols]),
  fun2 = SegundoMaiorLinha2(teste[, cols], teste$Max),
  fun3 = SegundoApply(teste[, cols]),
  times = 1e3
)

> print(mb, order = "median")
Unit: microseconds
 expr      min        lq     mean    median        uq       max neval cld
 fun3  389.099  418.6315  477.543  440.2565  469.4095  4875.095  1000 a
 fun2 1918.865 1991.0090 2189.838 2028.4195 2105.4355 11119.613  1000  b
  fun 1998.850 2055.3400 2295.097 2088.6375 2170.4150  9949.591  1000   c


Bootstrapped regression with total data or bootstrap with matched data?

Question: I'm investigating the effect of a continuous variable A on a measurement variable M stratified by another factor variable C in an observational dataset.
Due to heteroscedasticity I decided to use a bootstrapped regression analysis. However looking at the data, the background set of variables are not evenly distributed if I dichotomise A (present or not). I've just finished running another analysis where I do the same analysis after having matched the dataset for confounders (using CEM in R).
Now the problem is which analysis to trust: the bootstrapped regression approach on the entire dataset or the bootstrapped version of the matched data? Under one of the factors in C the results diverge.
Any ideas how this can be analyzed?
Answer: There is a wrinkle that you need to worry about. In the case of matching, you are throwing away observations (i.e., those that aren't matched and don't make it into your analysis) and some might be replicated. These decisions aren't random; they are a function of covariates. As a result, creating confidence intervals in this context are a bit complicated. To calculate the appropriate standard errors, see Large Sample Properties of (Matching Estimators for Average Treatment Effects by Abadie and Imbens. Additionally, Abadie also has a paper on On the Failure of the Bootstrap for Matching Estimators. To implement Abadie-Imbens standard errors, see the Matching package in R by Jas Sekhon.
On the question of which estimator to believe, it depends on how well you think that matching is correctly controlling for confounders, I'd be inclined to believe that approach. It seems that your first set of analyses doesn't control for those factors in any way? If you think that they are important, then you probably wouldn't be inclined to believe those results.
Comment: I´ll look into the matching package. My first analysis does control for the same factors as implemented in the match procedure in a multivariate linear regression model. Thx for the feedback..


testing component when a service injected angular2.0

Question: I am using angular2.0 for my application
I am trying to write test cases for a component where a service is injected
//component.ts
import { Component, OnInit } from '@angular/core';
import { FPService } from './shared/services/forgot-password.service';
import { CookieService } from 'angular2-cookie/core';

@Component({
  // moduleId: module.id,
  selector: 'app-fp',
  templateUrl: 'fp.component.html',
  styleUrls: ['fp.component.css'],
  providers: [FPService]

})
export class FPComponent implements OnInit {

  constructor(
    private cookie: CookieService,
    private fpService: FPService
  ) { }

  ngOnInit() {

  }
  fnRequest(email) {

    var oData = { "email": email };
    this.fpService.fnFPServie(oData)
      .subscribe(
      data => {
        console.log('success', data);

      },
      error => {
        console.log('error', error);

      }
      );
  }

}

my spec.ts
import { FPComponent } from './forgot-password.component';

import { FPService } from './shared/services/forgot-password.service';
import { CookieService } from 'angular2-cookie/core';

class mockFPService {
    fnFPServie(data) {
        return {}
    }
}

class mockCookieService {
    getObject(name: string) {
        return true;
    }
}

let comp: FPComponent;
let fixture: ComponentFixture<FPComponent>;
describe('Component: FPComponent', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({

            declarations: [FPComponent],
            providers: [

                { provide: FPService, useClass: mockFPService },
                { provide: CookieService, useClass: mockCookieService },

            ]
        });

        fixture = TestBed.createComponent(FPComponent);
        comp = fixture.componentInstance;

    });

    it('should have  method fnRequest', () => {
        expect(comp.fnRequest('email@example.com')).toBeTruthy;
    });

    it('should sent data to fnFpService() of FpService', () => {

        comp.fnRequest('firstname.lastname@example.com');

        **************************************************
        how do inject the Fpservice and call fnFPServie ?
       ********************************************************

    });

});

It would be helpfull if anybody suggest how to mock injected Fpservice to test fnRequest() function
Thanks in advance
Answer: It's not enough to just add a fnFPServie method. The caller then subscribes to the returned observable, calling subscribe. How you can mock this is to just do something like
class MockFPService {
  error;
  data;
  fnFPServie(data) {
    return this;
  }

  subscribe(next, err) {
    if (next && !error) {
      next(this.data)
    }
    if (err && this.error) {
      err(this.error);
    }
  }
}

Here, you are just returning the service itself, which has it's own mock subscribe method. When some call's subscribe, they pass in the success and error callback functions, and you just call the callback passing in the appropriate response.
You can also configure the mock during the test, either with data, or with an error. So you can test both outcomes separately.
let mockFPService: MockFPService;

beforeEach(() => {
  mockFPService = new MockFPService ();
  TestBed.configureTestingModule({
    providers: [
      { provide: MockFPService, useValue: mockFPService }
    ]
  })
})

it('..', () => {
  mockFPService.data = 'some data';
})

it('..', () => {
  mockFPService.error = 'some error';
})


Discovering groupings of descriptive tags from media

Question: Some media websites have a collection of descriptive tags paired to every image or video, which are intended to help users filter their searches. Such data are observational, so I would limit an analysis to exploring the properties of a (large) sample without inferring causal effects. Rather, I am interested in hypothesis generation from an exploratory data analysis.
For each tag we can create an indicator function $I_{x\in A_i}(x)$ for the $i$th tag. I am interested in learning which tags tend to co-occur, and which tags to tend to not co-occur. Observed groupings of tags might suggest, but not rigorously demonstrate, possible groupings of content preferences.
I could calculate joint frequency probabilities and compare them to the marginals, or perform frequent pattern mining, or one of various clustering algorithms. From a technical standpoint, I essentially have a collection of one-hot vectors. I am wondering what is a suitable approach for finding groupings with such data based on co-occurrence.
Comment: How many tags are there? Is it a small subset, or a large, growing set like in the case of StackExchange?
Comment: @Tim Over ten thousand tags across a couple of million observations. I have not checked yet how many are [Hapax legomenon](https://en.wikipedia.org/wiki/Hapax_legomenon), but some quick checks suggest the tags might be power law distributed... Maybe Zipf, specifically, but I have not checked that yet.
Comment: tags sometimes "beg the question".  If the customer is running after the keyword, then the association is with the word-symbol, and not necessarily the actual product.  I like dark beer but I'm a little picky, so I can look in that section of a supermarket, and find nothing, but if it was an online store they might infer that I connect whatever it was I was looking at before with dark beer, when in fact their dark beer selection was so bad I went elsewhere.  User interface design has a huge impact, and the evolution of the amazon webstore UI over time shows that there is still a lot to learn.
Comment: You make a logical jump from video tags to personal preferences. Unless you have data about views, or even better, data on views by individual viewers, it's not clear how you'd learn about personal preferences from co-occurrences of labels. It's not even clear whether the labels are assigned by the viewers themselves, so actually the labels might reflect the video platform's guess/knowledge about user preferences. So you might end up doing analysis of their analysis.
Answer:
You can use the market basket analysis, a simple and popular data mining technique that does exactly what you described: groups co-occurring items together.
For a more sophisticated solution, you can use cluster analysis. For binary data, there is a rich family of models called latent class analysis that are designed for this purpose. I'm not sure though if it would scale to a large dataset with many columns and rows like yours.
You could transform the binary data into embeddings that would reduce its dimensionality and convert it into continuous features that later could be clustered, which makes it a simpler problem. For creating the embeddings, you could use a neural network or take one of the latent matrices created by matrix factorization (an algorithm used usually for recommender systems), where both scale very well to large data. They will create continuous features, so you can cluster them with any algorithm, e.g. $k$-means.
Answer: If you are after visualizing the relationships, then you might use some network visualization algorithms.
I did this once with the tags of cross validated (Disclaimer: I am not an expert at this). I made a matrix that keeps track of the number of times of times that the different tags are appearing together. Then I used that matrix as

a matrix describing the edges in a network graph
a correlation matrix in PCA and
3 after some arbitrary trial and error with transformations, as a dissimilarity matrix in an hierarchical clustering method


cost function in logistic regression vs optimization algorithms

Question: I have a table like:
    tabla <-data.frame(c=c(-3, -2, -1, -1, 1, 2, 3, 0, 0, 5, 4,
              3,  0, 8, 9, 10, 6, 6, 7, 3, 0), e=c(0, 0, 0, 0, 0,
              0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1))
    tabla <- tabla[order(tabla$c), ]

Let's suppose I need to predict e with c using a logistic regression:
    log_pru <- glm(e ~ c, data = tabla, family = binomial(logit))
    tabla$pred_res <- predict(log_pru, tabla, type = "response")

Let's suppose also that my gain is 90 when my choice is TP, and -10 when is FP function is:
    mycost <- function(r, pi){
      weightTP = -90 #cost for getting 1 ok -90
      weightFP = 10 #cost for getting 0 wrong 10
      cTP = (r==1)&(pi==1) #logical vector--- true is actual==1
                           #and predict ==1
      cFP = (r==0)&(pi==1) #logical vector - true if actual 0
                           #but predict 1
      return(mean(weightTP*cTP+weightFP*cFP))
    }

If I'm able to identify each TP without FP, my gain would be:
    maxgain <- tabla$e*90
    sum(maxgain)
     630

In the log model, my gain would be:
    tabla$ganLog <- ifelse(tabla$pred_res>.1, tabla$e*90-10, 0)

which is 420.
I thought that introducing the cost function in the optimizing algorithm might be useful to reflect my actual problem.
So, to use "optim", I wrote the following function (which is a sigmoidal):
    fn <- function(x) {
      alpha <- x[1]
      beta <- x[2]
      J <- exp(alpha + tabla$c * beta)
  prediction <- ifelse(J/(1+J) > 0.5, 1, 0)
  mycost(tabla$e, prediction)
    }

    guess <- optim(c(0,0), fn, method='SANN')

And my result is:
    alpha <- guess$par[1]
beta <- guess$par[2]
    J<-exp(alpha + tabla$c * beta)
tabla$pred_guess = J/(1+ J)
    plot(tabla$c, tabla$e)
    lines(tabla$c, tabla$pred_guess)
    mycost(tabla$e, ifelse(tabla$pred_res > 0.1, 1, 0))

    tabla$ganOpt<-ifelse(tabla$pred_guess>.5, tabla$e*90-10,0)
sum(tabla$ganOpt)

Which is 460. (almost 10% greater than the obtained by the logistic with glm). If I plot both graphs:
    plot(e ~ c, data=tabla)
    lines(tabla$c, log_pru$fitted, type="l", col="red")
    abline(0.1, 0)
    abline(v=min(tabla$c[tabla$pred_res>0.1]), col="blue")

An the other model would be:
    plot(tabla$c, tabla$e, main="optim")
    lines(tabla$c, tabla$pred_guess, col="red")
    abline(0.5, 0)
    abline(v=min(tabla$c[tabla$pred_guess>0.5]), col="blue")

I know that you can introduce a cost function in cv.glm but this is only o select among models already chosen, so, my questions are:

Would it be a good idea to introduce a cost function in the algorithm that selects the parameters?
What does SAS do with the cost function in Miner? Does it use it to select the parameters values?
Why glm package in R doesn't have the possibility to introduce another cost function?
Would it be a bad idea to use  "optim" in real examples? What about over-fitting? And also, do I have to program all the variables like I did in this mini example? Is there a better way?
What about doing oversampling or downsampling to avoid this?

I would really appreciate a theoretical answer.
Answer: If I understand what you have done, you have done things out of order.  Maximum likelihood or penalized maximum likelihood estimation is the gold standard method for estimating parameters in a regression model.  The cost function does not apply to how one estimates risk.  The cost function is applied to individual risk estimates to provide an optimum decision for that one observation.
Comment: The cost/loss/utility function is applied to individual optimum predictions to obtain optimal decisions.  Here is an analogy: Suppose you want to make the best medical decision about a disease a patient may have.  You get an estimate of the probability that the patient has the disease irrespective of the cost function that may apply to later decisions.  Now the physician discusses this with the patient and finds the patient has a certain cost function that was not expected.  An optimum treatment is selected for that patient.  The cost function depended on initially unavailable variables.
Comment: thanks Frank. I understand but in this case I'm loosing the opportunity to gain because I'm not introducing the cost function in the method for estimating parameters....Why? and ...What do you think would be better in this way?
Comment: @FrankHarrell What would you, then, think of [this](https://stats.stackexchange.com/a/538524/247274) example, where it seems like we profit the most by building our model based on classification accuracy, rather than accuracy of probability predictions?
Comment: I wish I had time to understand that long example.  In general it's impossible for classification accuracy to have anything to do with optimum decisions.  Perhaps there is a discontinuous degenerate case where my statement doesn't hold.


Panels Node template with additional arguments

Question: The basic crux of what I'm trying to achieve is this:
When viewing a node - Content Type A (which is currently overridden with a panels node template) I want to be able to show a views block that will display the fields from one node of content type B.
To control which node from Content Type B would display on Content Type A pages, the idea was to set up a views pane with a contextual filter, so that any two nodes from hte two content types could be displayed together. This works fine by itself and in the preview.
But, I am having trouble getting panels to comply with my wishes!
I can set up a node template panel, but can't work out how to pass the second argument to the view pane. And I have tried to create a new panel to override the node so that I can pass the argument to the pane but it isn't overriding the node.
Any ideas how I can do this please?!
Comment: are you using D7 and Views and Panels 3?
Comment: Apologies, yes d 7.10 views 7.x-3.0 panels 7.x-3.x-dev
Comment: I have the same problem, but i am using drupal 6. I just want to pass additional parameters from the node tempalate to the view. I cant find it (if there is any). What can i do?
Comment: http://drupal.stackexchange.com/questions/72999/passing-argument-from-url-in-panel-to-view-pane-or-block-d7
Answer: You need a few components to make this work properly.

You View must have a display of type "Content pane".
A contextual filter.
In the Pane settings you should set your argument input to be "From context", and then picking an argument source that matches what your contextual filter wants. Most likely that will be a node id. (The argument setting could be a specific argument, first, second or so, as well, but that's generally not a very good idea)
Add the View pane to your panel page, not the View itself. If the Pane doesn't show up in the listing, your Pane settings are wrong.
Done.
Answer: To pass URL argument from Panel to Content pane, try:

Add Contextual filter to the View.
E.g.: Views contextual filters taxonomy name
Change settings in 'View -> Pane settings -> Argument input' to load the argument 'From panel argument' (e.g. First). Try other options for your needs.


Annoying Python list index out of range error

Question: I have an array already initialized to be a 3x6 array called self.ascii. I am trying alter a 3x3 block of this array at a time, using the code:
for x in range(3):
    for y in range(3):
       # currY and currX represent the bottom left corner of the 3x3 square I am tyring to alter
       self.ascii[y+currY][x+currX] = arr[y][x] # yes I know the x and y values are backwards between the arrays

However I keep getting the error, in GNURadio-Companion list index out of range--before I even try to run it. I know that the indexes here do not leave the range of the list.
Question: Why does python check this before running, and is there a different way I should be loading these 3x3 arrays
Comment: Can you post the traceback message that shows the failing line? Python doesn't check list indexes before you run it, so something else is going on. Printing `self.ascii`, plus `currY` and `currX` would be useful. One of these is different than you think.
Comment: Maybe `2+currY > your length of one dimension`.
Comment: If `currY` is bottom left, then the rows you want are `currY-0`, `currY-1` and `currY-2`, but you are adding postive numbers here. Perhaps you want `self.ascii[currY-y][currX+x]` or maybe since you use y on both sides, `self.ascii[currY-3+y]`
Answer: Learn to use pdb.
import pdb

pdb.set_trace()

# Now your code.
for x in range(3):
    for y in range(3):
       self.ascii[y+currY][x+currX] = arr[y][x]

This will drop you into an interpreter where you can see the value of anything you like, and use commands like n to execute the next instruction in the code. Go step by step until you find which index is going outside the range of its list.


how to disable motion of ViewPager when touching specific view in this ViewPager Android?

Question: I have a ViewPager. In each pager, it display a listview. Each row in the Listview contains a HorizontalScrollView element. Here is the code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white" >

    <LinearLayout
        android:id="@+id/survey_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentTop="true"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/store_name"/>

        <TextView
            android:id="@+id/txt_store_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"/>

    </LinearLayout>

    <HorizontalScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_below="@id/survey_header"
        android:scrollbars="none">

        <TableLayout
            android:id="@+id/survey_table"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TableRow
                android:id="@+id/survey_table_row"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/txt_status"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/red_text"/>
                <TextView
                    android:id="@+id/txt_product"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/red_text"/>
                <TextView
                    android:id="@+id/txt_stock"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/red_text"/>
            </TableRow>

            <TableRow
                android:id="@+id/menu_table_row"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/red_text"
                    android:text="@string/survey_status"/>
                <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/red_text"
                    android:text="@string/product_info"/>
                <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:gravity="center"
                    android:textColor="@color/red_text"
                    android:text="@string/stock_count"/>
            </TableRow>
        </TableLayout>

    </HorizontalScrollView>

</RelativeLayout>

Everytime I try to scroll the horizontal Scroll View, the ViewPager receives touch event first and change the page.
How can I disable the changing page of ViewPager when I touch Horizontal Scorll View.
Thanks in advance.
Answer: HorizontalScrollView scrollView=(HorizontalScrollView)findViewById(R.id.scrollView);

scrollView.setOnTouchListener(new View.OnTouchListener() {

            float rawX;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN:
                        scrollView.getParent().requestDisallowInterceptTouchEvent(true);
                        rawX = event.getRawX();
                        return false;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        scrollView.getParent().requestDisallowInterceptTouchEvent(false);
                        rawX = 0f;
                        return false;
                    case MotionEvent.ACTION_MOVE:
                        if (Math.abs(rawX - event.getRawX()) > ViewConfiguration.get(getActivity()).getScaledTouchSlop())
                            scrollView.getParent().requestDisallowInterceptTouchEvent(true);

                        break;
                }

                return false;
            }
        });

Comment: I try your solution, but it doesn't work. The ViewPager still swipe when I scroll the ScrollView inside it.
Comment: try to move scrollView.getParent().requestDisallowInterceptTouchEvent(false); method to  case MotionEvent.ACTION_DOWN:
Comment: I try if                       scrollView.getParent().requestDisallowInterceptTouchEvent(true); in case MotionEvent.ACTION_DOWN, now It goes well. Thanks a lot


prove surjectivity of a function

Question: I have problems in evaluating the surjectivity of the function $F$ defined below.
Let A be any set and consider the power set P(A) of A and the set $\{0,1\}^A$ of all functions with domain $A$ and codomain $\{0,1\}$. The characteristic function $\chi_B : A \to \{0,1\}$ of a subset $B \subseteq A$ is defined by
$\chi_B(a)=\begin{cases}
1,&\text{if }a\in B\\
0,&\text{if }a\notin B\;.
\end{cases}$
The function that assigns the characteristic function to a subset:
$F: P(A) \to \{0,1\}^A$
$A \mapsto \chi_A$
is a bijection.
I can prove injectivity easily but I am stuck at surjectivity. To prove that a function $f:A \to B$ is surjective one has to prove that $Im\, f = B$
In this case $Im\, F = \{\chi_B \in \{0,1\}^A | \chi_B = F(B) \text{ for some } B \in P(A)\}$
My manual furnishes this proof:
To prove surjectivity of $F$, suppose that $f \in \{0,1\}^A$ is a function and define the set:
$B = \{ a \in A : f(a) =1\}$
then $\chi_B = f$ and $F(A) = f$ and surjecitivty is proved.
I don't understand it, why that definition of the B set proves surjectiviy??
I understand that, lets do an example, if $A = \{1,2,3\}$ and consider the subset $B = \{1,2\}$ this is equivalent to the characteristic function $f(1) = 1, f(2) = 1, f(3) = 0$
$B = \{a \in A: f(a) =1\}$
so that $\chi_B = f \in \{0,1\}^A$, but I don't understand how this is a proof of surjectivity of $F$
Comment: For an arbitrary $f\in\{0,1\}^A$ it is shown that we can find a set $B$ such that $f=\chi_B$. This $\chi_B$ is obviously an element of the image of $F$. So for an arbitrary $f\in\{0,1\}^A$ it is shown that it is an element of the image of $F$. This implies that every $f\in\{0,1\}^A$ is an element of the image of $F$, which means exactly  that $F$ is surjective.
Answer: Hint: You have to show that $\chi_B=f$. Take any $a$ and verify that $\chi_B(a)=f(a)$. Both sides are $0$ or $1$. See when they are equal to $1$ and when they are equal to $0$.

prove surjectivity of a function


How to set date in weekdays

Question: I have date from 01/01/1859 to up till date of today.
I have some sessions in these dates of some subjects.
Now I have to create a time table.
In one day there are five sessions like Monday have five slots, slot 1 slot 2 slot 3 slot 4 slot 5.
I have to make a query that if sessions lie on the Wednesday, session should lie in the Wednesday column. And particular slot of that Wednesday which i give to session.
Comment: Could you provide some sample data and expected results?
Comment: I can not post image to you so that i can show you my results can you send me email so i can mail you
Answer: SQL Server
SELECT *
FROM `table`
WHERE DATEPART(WEEKDAY, GETDATE()) = 4 -- Wednesday

DATEPART return an integer which represent the following:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

C#
DateTime date = DateTime.Today;
bool IsWednesday = (date.DayOfWeek == DayOfWeek.Wednesday);

Answer: try this:
SELECT *
FROM table
WHERE DATEPART(WEEKDAY, GETDATE())

How to set date in weekdays


How can I clear all check boxes on failed validation?

Question: I have form with check boxes. The user checks the boxes and hits the submit button. If validation fails an error message is displayed. I also want all of the user's checks to be cleared so they can try again. Here's my code, but it does not clear the checks? Thanks.
<code>/**
 * Defines a form.
 */
function my_form($form, &$form_state) {

    $form['alerts'] = array(
        '#type' => 'checkboxes',
        '#options' => $options,
    );

    // the rest of my form

    if (isset($form_state['clear_checkboxes'])) {
        $form_state['values']['alerts'] = array_fill(0, count($form_state['values']['alerts']), 0);
    }
    return $form;

}

/**
 * Form validator.
 */
function my_form_validate($form, &$form_state) {

    // if validation fails set error message

    $form_state['rebuild'] = TRUE;
    $form_state['clear_checkboxes'] = TRUE;

}
</code>
Answer: You can unset your field in the form .Check for the array which has field array.
<code>unset($form_state['field_checkbox']['und'][0]['value']);
</code>


STLINK cannot detect my STM32VL discovery

Question: I'm working on a debian 6.0 installed on virtualbox 4 hosted by Windows7, and I'm trying to get my STM32VL work using STLINK project that allows programming and debugging STM32 on Linux.
I followed their tutorial and installed all needed dependancies.
But when I run the program ./st-util -1, I get the following error:

tbarry@darkstar:~/stlink$ ./st-util -1
2014-03-20T10:18:48 WARN src/stlink-sg.c: Failed to find an stlink v1 by VID:PID
Error: could not open stlink device
Error: could not open stlink device

I underline that I have already installed Virtualbox extensions, and usb 2.0 is well handled.
Does anyone have an idea of what is blocking me?
Answer: I'd same problem. It was driver problem. Windows detected my st-link as mass storage device, so st-util didn't see it. I've used zadig utility in order to change the driver.
Answer: Not having found a solution to my problem, I tried with VMware player and it worked nice.
Conclusion: Whatever the problem I had, it was coming from VirtualBox.
Comment: I rather belong to VirtualBox sect :)


Timeout for Volume Shadow Copy (programmatically)

Question: When I start the Volume Shadow copy programmatically how much time is maximum that I should wait before the Shadow is prepared ie: before I proceed taking backup. Just now it happens with about 10 secs in my machine. But I need timeout when deploying elsewhere.
Answer: This article (which describes the flow of events that happen when you create a Shadow Copy using a "Hardware Provider") has a nice sequence diagram that illustrates the timeout in the 'I/O Flush & Hold' window: https://msdn.microsoft.com/en-us/library/windows/desktop/aa384615(v=vs.85).aspx
The total timeout enforced by VSS in this window is 60 seconds. Hence, you can expect the IVssAsync::Wait() call, on the IVssAsync pointer returned by the call to DoSnapshotSet(), to automatically timeout in 60 seconds.
As such, you do not need to implement a timeout yourself, since VSS does this for you.


Mudar cor background

Question: Estou começando a aprender a programar, e resolvi criar um App na intel xdk. Esse App é um livro que escrevi a certo tempo, é um App bem simples, mas queria adicionar um botão onde ao clicar nele, muda-se a cor do background para facilitar a leitura, porem não sei como fazer isso, quem puder me enviar esse código ficaria muito grato.
Obs: a intel xdk trabalha através do html5
Código:
<!DOCTYPE html>

    <cc>
        <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
        <meta charset="UTF-8">
        <title>Blank App Designer Cordova Web App Project Template</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">

        <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=no">

        <link rel="stylesheet" href="css/app.css">
        <link rel="stylesheet" type="text/css" href="css/index_main.less.css" class="main-less">

                        <button class="btn widget uib_w_3 d-margins btn-sm btn-primary" data-uib="twitter%20bootstrap/button" data-ver="1" id="btn_livro">
                        </button>

                        <button class="btn widget uib_w_2 d-margins btn-sm btn-primary" data-uib="twitter%20bootstrap/button" data-ver="1" id="btn_menu">
                        </button>

                        <button class="btn widget uib_w_4 d-margins btn-sm btn-primary" data-uib="twitter%20bootstrap/button" data-ver="1" id="btn_config">
                        </button>

Texto Teste capítulo

Texto Teste capítulo Texto Teste capítulo Texto Teste capítulo Texto Teste capítulo Texto Teste capítulo Texto Teste capítulo Texto Teste capítulo Texto Teste capítulo Texto
                                            Teste capítulo Texto Teste capítulo

Não consegui incluir o código no projeto alguém que possa me ajudar?
Comment: poste seu codigo tem  algum ID?
Comment: se ta usando html provavelmente aceita javascript
Comment: coloquei o codigo
Answer: Acredito que queira algo assim:
HTML
   Mudar cor do fundo
<input type="checkbox" id="check" />

CSS
div{
    width: 100%;
    height: 100%;
    background: #ff0000;
    position: absolute;
    top: 0;
    left: 0;
    z-index:1;
}
label.btn {
    position: absolute;
    top:15px;
    left: 15px;
    z-index:2;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
input[type="checkbox"]{
    display: none;
}
input[type="checkbox"]:checked + div{
    background: #00ff00;
}
label + input[type="checkbox"]:checked{
    background: #000;
}

Código funcionando aqui
Comment: Era esse mesmo, vou tentar adicionar aqui no projeto.
Answer: Crie um arquivo js e inclua na sua aplicação a adicione o  seguinte codigo
function change_bg(){
    if($("#mainpage").css("background-color") == "rgb(0, 191, 255)"){
    $("#mainpage").css({"background":"none"})
  }else{
    $("#mainpage").css({"background":"rgb(0, 191, 255)"});
  }
}

lembre-se de colocar o jquery caso ainda não tenha em seu  codigo
no html coloque esse botão deve funcionar
 <button onclick="change_bg()">Mudar Fundo</button>

alias a onde esta p  valor rgb é a cor que você deseja. boa sorte
você pode ver o codigo funcionando  bem aqui
Comment: vlw funcionou aqui, o único problema q tive é que ao trocar  a cor, ele troca a cor, mas não volta mais.
Comment: não precisa mais, erro meu aqui, não tinha colocado os espaços depois da virgula obd mesmo graças a você consegui o que queria agora é só tentar mudar a cor do botão vlw.
Comment: por nada, para mudar a do botão basta usar o msm  funcao e colocar  o id do botão repetindo o codigo
Comment: so uma ultima duvida, nesse codigo da para inserir mais cores?
Comment: sim dá, você pode mudar o valor rgb para cor que deseja ou copiar essa parte do codigo `if($("#mainpage").css("background-color") == "rgb(0, 191, 255)"){
    $("#mainpage").css({"background":"none"})
  }else{
    $("#mainpage").css({"background":"rgb(0, 191, 255)"});
  }` e mudar a onde é o #mainpage pelo id do elemento
Comment: vou tentar obrigado pelas dicas e por compartilhar seus conhecimentos.
Comment: por nada bem vindo a comunidade

Mudar cor background


How to rename a file using svn?

Question: When I try svn mv old_file_name new_file_name, I get
 svn: Path 'new_file_name' is not a directory

What's the correct way? (sorry, this seems so trivial, but I'm stuck).
PS. using svn version 1.6.11
EDIT it seems I get this error only if new_file_name refers to the name of a file that is currently under version control. In this case, of course, I can simply
 mv old_file_name new_file_name
 svn delete old_file_name

Comment: Maybe you need the full repository path, `file://...` or `svn://...` or `http://...` to the file.
Answer: The behaviour differs depending on whether the target file name already exists or not. It's usually a safety mechanism, and there are at least 3 different cases:
Target file does not exist:
In this case svn mv should work as follows:
$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding     new_file_name
Deleting   old_file_name
Committing transaction...

Target file already exists in repository:
In this case, the target file needs to be removed explicitly, before the source file can be renamed. This can be done in the same transaction as follows:
$ svn mv old_file_name new_file_name
svn: E155010: Path 'new_file_name' is not a directory
$ svn rm new_file_name
D         new_file_name
$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
R  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Replacing      new_file_name
Deleting       old_file_name
Committing transaction...

In the output of svn stat, the R indicates that the file has been replaced, and that the file has a history.
Target file already exists locally (unversioned):
In this case, the content of the local file would be lost. If that's okay, then the file can be removed locally before renaming the existing file.
$ svn mv old_file_name new_file_name
svn: E155010: Path 'new_file_name' is not a directory
$ rm new_file_name
$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding         new_file_name
Deleting       old_file_name
Committing transaction...

Comment: on 1.8.3 rm removes the physical file, just running the "svn mv ..." was sufficient, it executes that A D.
Comment: It is funny how old SVN is and how awkward it is to rename a file using it.
Comment: @Ghasan: The title of the question might be misleading. It's about *removing* one file and *renaming* another file at the same time. This use case is not that common, and a bit tricky with most VCS, in particular if the information should be visible in the history.
Comment: I needed to add --force to svn rm new_file_name as it complained that new_file is is not under version control.
Comment: .. and I had to create an empty file called new_file_name.
Comment: For me simply typing `svn mv old_file_name new_file_name` did the trick.  Then I checked it with `stat` and committed it. (I was renaming a file, that already existed.)  Very helpful, thank you.
Answer: Using TortoiseSVN worked easily on Windows for me.
http://tortoisesvn.net/
Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok
Using SVN 1.8.8
TortoiseSVN version 1.8.5
Comment: This worls, but you will lose the history of the file.
Comment: Not that the OP was asking about Windows, but upvotes deserve extension: Full desktop integration means that you may simply do this in the context menu from Explorer.
Comment: But now I see that posting a Windows answer on what is clearly a Linux question has gotten this one down-voted several time. (drats, time ran out for me to edit my original comment)
Comment: I was using Cygwin on Windows at the time, so there was some crossover.
Comment: I couldn't get it to work without using TortoiseSVN on Windows. So I am thankful for this answer. I upvoted you. Using anything else kept causing it to revert anytime I updated. In my case the change was capitalization of the file names. I think the issue in my case stems from the fact  that Windows is case insensitive.
Comment: Then, what happen with users that have `old_file_name` on their working copy?
Answer: This message will appear if you are using a case-insensitive file system (e.g. on a Mac) and you're trying to capitalize the name (or another change of case).
In which case you need to rename to a third, dummy, name:
svn mv file-name file-name_
svn mv file-name_ FILE_Name
svn commit

Comment: And I was wondering why it works on Linux but not on Mac. Thanks!
Answer: It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:
$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory

$ svn status
?       etc/nagios/hosts/us0101/ccs

$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'

$ svn mkdir etc/nagios/hosts/us0101/ccs
A         etc/nagios/hosts/us0101/ccs

$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A         etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D         etc/nagios/hosts/us0101/cs/us0101ccs001.cfg

$ svn status
A       etc/nagios/hosts/us0101/ccs
A  +    etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
        > moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D       etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
        > moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg

How to rename a file using svn?


AnsiStrIComp fails comparing strings in Delphi 2010

Question: I'm slightly confused and hoping for enlightenment.
I'm using Delphi 2010 for this project and I'm trying to compare 2 strings.
Using the code below fails
if AnsiStrIComp(PAnsiChar(sCatName), PAnsiChar(CatNode.CatName)) = 0 then...

because according to the debugger only the first character of each string is being compared (i.e. if sCatName is "Automobiles", PAnsiChar(sCatName) is "A").
I want to be able to compare strings that may be in different languages, for example English vs Japanese.
In this case I am looking for a match, but I have other functions used for sorting, etc. where I need to know how the strings compare (less than, equal, greater than).
Comment: sCatName is defined as string, which to my understanding in Delphi 2010 is = UnicodeString.
In this particular case it is being passed a function parameter--
function ExtractCatagory2Listbox(sCatName: String; TargetLB: TListBox): Boolean;
Answer: I assume that sCatName and CatNode.CatName are defined as strings (= UnicodeStrings)?. They should be.
There is no need to convert the strings to null-terminated strings! This you (mostly) only need to do when working with the Windows API.
If you want to test equality of two strings, use SameStr(S1, S2) (case sensitive matching) or SameText(S1, S2) (case insensitive matching), or simply S1 = S2 in the first case. All three options return true or false, depending on the strings equality.
If you want to get a numerical value based on the ordinal values of the characters (as in sorting), then use CompareStr(S1, S2) or CompareText(S1, S2). These return a negative integer, zero, or a positive integer.
(You might want to use the Ansi- functions: AnsiSameStr, AnsiSameText, AnsiCompareStr, and AnsiCompareText; these functions will use the current locale. The non Ansi- functions will accept a third, optional parameter, explicitly specifying the locale to use.)
Update
Please read Remy Lebeau's comments regarding the cause of the problem.
Comment: The UnicodeString type uses UTF-16 encoding, which uses 2 bytes per codeunit, and 1-2 codeunits per Unicode character (depending on whether surrogates are used). For Unicode characters in the ASCII range, the second byte of each codeunit will be set to 0. Type-casting a UnicodeString to a PAnsiChar will treat the pointer as a null-terminated Ansi character string, not a null-terminated Unicode character string. So the pointer will always end at the second byte of the string.
Comment: @Andreas: Delphi strings ARE null-terminated.  The null terminator is not considered part of the string data (it is not counted by Length(string)), but the terminator is present nontheless.  This is so a PChar typecast can simply return the address of the string data as-is without having to allocate new memory instead.
Comment: Keep in mind that relying on nullchar termination will go wrong for certain strings (e.g. compare aaaa#0bbb with aaaa#0ccc), since it is perfectly legal for Delphi strings to contain additional null chars
Comment: Thanks for your reply.
For the function in question AnsiCompareText() looks like it will do the job as well as being a simpler implementation.
But I would like to understand why PAnsiChar(sCatName) is taking a string variable and returning only the first character.
Comment: If `sCatName` is a string, then `PAnsiChar(sCatName)` creates a null-terminated string representation of `sCatName`, and returns the pointer, the address, of the first character of this null-terminated string. (In Delphi, `string`s are *not* null-terminated, so when communicating with the Windows API, for instance, you might need to create null-terminated strings from Delphi strings).
Comment: @Remy Lebeau: I wasn't aware of that null byte. But indeed it makes sense - it is a very small cost for a potentially huge improvement of performance!
Comment: @Remy: You really should have downvoted me, at least until I removed the incorrect statement about the non-existing null byte!
Comment: Here we can observe the null character: http://docwiki.embarcadero.com/RADStudio/en/Internal_Data_Formats#Long_String_Types
Answer: What about simple sCatName=CatNode.CatName? If they are strings it should work.
Comment: I am looking for non-case sensitive comparison. In this particular case I am checking for equality. While UpperCase(sCatName)=UpperCase(CatNode.Name) would work (for this particular example) it is my understanding the the built-in string comparison functions are faster.
Comment: @TheSteven: Yes, `SameText(A, B)` is faster than `AnsiUpperCase(A) = AnsiUpperCase(B)`.
Comment: @TheSteven I was cut off from the internet, and so I missed the whole discussion; now I must just agree with Andreas and Remy.


subfolder installation user block login and destination issue

Question: I have installed drupal 6.22(fresh installation) on my localhost in which i have set user block on header. Now my problem is when i looked to action of user login form, here i can see my folder name is there.
Say My url : http://localhost/drupal6/
So i can find my form action : /drupal6/node/85?destination=node%2F85
Now after login my url becomes http://localhost/drupal6//drupal6/node/85?destination=node%2F85 and I got page not found error.
And that actually creates issue on redirection.
I want to mention that i have installed 6.22 cause we need to make changes to older version. TIA. What could be the actual reason? Do I need to create a custom user login block for the same? or any issue in url function though i have not changed core files or not added any custom login module. My active theme is garland.
Edit:
Without login go to "http://localhost/drupal6/admin/settings/site-information", It shows access denied message then login using your account and you will face page not found error.
Cause in browser its showing me "http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information".
Just try out in your any setup on localhost or on subdomain installation. Its not working as expected.
After login url should be "http://localhost/drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information" instead page not found. TIA
EDIT : MOD-Rewrite
Answer: Finally i found the issue of redirection. I have checked form.inc file from where i have found that drupal_goto function from common.inc file is called.
Now by debugging that form.inc i found that drupal_redirect_form calls drupal_goto with different options. In subfolder case (i.e. my case) drupal_goto function i have found that $path has value like '/drupal6/' default. So what i have hacked is
$folder_name = '/drupal6/';
$length = strlen($folder_name);
$path_check = substr($path,0,$length);
$path_len = strlen($path);
$remaining_path = '';

if($path_check == $folder_name) {
    $remaining_path = substr($path,$length,$path_len);
    echo $path = $remaining_path;
}

So now my problem of adding two folder name like 'http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information/' have been solved but as you know that this is core hack and i dont like it. Any better solution???
I know that if i transfer this site from my localhost to internet than that would not create any problem without making this kind of small hacks.
Answer: Modify line 94 of .htaccess to look like this:
RewriteBase /drupal6

Here are the contents of that file:
http://drupalcode.org/project/drupal.git/blob/HEAD:/.htaccess
Comment: Tried your solution but does not make any affect. Facing the same issue of redirecting.
Answer: I am not sure how you installed it, but would look into $base_url in your settings.php file (sites/default/settings.php) and see where it is pointing, and if drupal6 is not your actual web server root, then it should look something like
http://localhost:PORTNUMBER/drupal6
You can also look in admin/settings/site-information and make sure it is showing to the left of default front page, eg, it should look like this:
http://localhost:PORTNUMBER/drupal6 [ node ]
NOT
http://localhost:PORTNUMBER [ drupal6/node ]
Comment: I have tried your solution but doesn't make any difference. I tried "http"//localhost/drupal6" and on left of default front page its showing "http://localhost/drupal6/". Also checked its not redirecting me properly on my page after login. ANyways thx.
Comment: I want to inform you that in my settings.php file It showing me like this "#$base_url = 'http://www.example.com';  // NO trailing slash!", Its commented, So I changed it and added $base_url = 'http://localhost/drupal6'. My point is its by default commented.
Comment: correct, by default drupal thinks it is in the web host root.  if you change that to localhost/drupal6 then it will look there and prefix every path with that.  it does this so if you move it to another host, you can just change this instead of every path inside drupal.
Comment: (and I just asked about the default home page in the off chance someone put in drupal6/node thinking that would change everything; glad that wasn't the case ;)
Comment: Thx for your info.
Answer: Check line 107 in your .htaccess file.  Try uncommenting that line, and ensure that line 103 is commented out.
Example:
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

Also, just in case, ensure that you have mod_rewrite enabled on your localhost.
Comment: Please have a look at the updated question, i have attached my localhost phpinfo screenshot indicating mod_rewrite. After removing comment i got 404 error thats not handled by drupal itself. Not showing any page. "The requested URL /index.php was not found on this server."
Comment: @Kamal What do you have in your `settings.php` file with  regards to your `$base_url` (around line 125).
Comment: Well actually its commented as "#$base_url = 'http://www.example.com';  // NO trailing slash!". Havent changed baseurl. Its pointing to http://localhost/drupal6


Why does nginx need an auth_http entry for smtp reverse-proxy?

Question: I'm an apache user normally, but I need to start using nginx as a reverse proxy for smtp (postfix).
I've seen tens of examples online. Like this and this. All of them have an auth_http entry, which I completely don't understand. This is not the first time I use proxies, and I currently use haproxy since months. So why do I have to provide a php authentication page? Why can't I just use nginx as simple as I use haproxy, and just tell it: Set a frontend here, decrypt ssl with this key, and take it to that backend/port?
Could someone please explain how necessary that auth_http entry is? The nginx manual doesn't seem to say much.
Thank you for any efforts.
Comment: [Related question](https://serverfault.com/q/594962), asking the same thing about IMAP proxying.
Answer: Basically there are three big steps in your workflow

Encryption and decryption process either by STARTTLS or SMTPS
Authentication process i.e. to check if you allowed to do SMTP transaction
SMTP Transcription (MAIL FROM, RCPT TO and so on)

As far as I understand, you want to use nginx to do step 1, and transparently pass the rest of the transaction to the backend. Unfortunately you can't do it with nginx due its design. Nginx is always do step 1 and 2 before pass the request to the backend.
That's why parameter auth_http becomes crucial. Basically nginx takes username and password from SMTP auth process, pass it to auth_http URL via a protocol. And it expects response about auth status (whether transaction can be continued or not) and which address and port where the SMTP data should be passed.
So, if you want just some SSL stripper proxy for SMTP, then maybe nginx won't be fit in your case.
Answer: In newer versions of Nginx (from 1.19.4), the auth_http directive with your own Nginx HTTP Authentication Server is no longer needed for the purpose of authentication.
You can now set proxy_smtp_auth on; in your proxied SMTP servers to make them relay SMTP authentication to the proxied server (see manual, related answer). Your auth_http server would in that case simply authenticate all clients, but still has two other mandatory roles to fulfill:

The authentication server will authenticate email clients, choose an upstream server for email processing [and refer the client to it], and report errors.
(Source: Nginx Plus Admin Guide: Configuring NGINX as a Mail Proxy Server)

A complete Nginx config example would look like this (not tested, probably not fully functional yet, and omitting all SSL stuff):
mail {
    server_name smtp.example.com;
    proxy_pass_error_message on;

    # Your Nginx HTTP Authentication server.
    auth_http   localhost:9000/nginxauth.php;

    # Proxy server config.
    # (NOT proxied servers. These are only know to the HTTP Auth Server.)
    server {
        listen           25;
        protocol         smtp;
        proxy_smtp_auth  on;
        smtp_auth        login plain cram-md5;
    }
}

If you only want to refer clients to one single backend SMTP server, there is no need to implement a custom Nginx HTTP Authentication server. You can use this technique instead.