Hibernate + embedded database - setup

Question: I have created Java application using Hibernate with this configuration:
<hibernate-configuration>
 <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306     /bee</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    <property name="connection.username">root</property>
    <property name="connection.password"/>
    <property name="hibernate.connection.charSet">UTF-8</property>
    <property name="hibernate.connection.characterEncoding">UTF-8</property>
    <property name="hibernate.connection.useUnicode">true</property>
    <mapping resource="DatabaseMapping.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Everything works fine when Iam using jdbc:mysql://localhost..., but now I need to have the database embedded in my application. Which database should I use? I need to have all my data stored and load it after start the application, update data, save, delete. I use HQL query or SQL query.
What is the simplest way to make the database embedded? I don´t want to change my queries. It would be fine to change only hibernate configuration and set it to the embedded database, is it possible?
Answer: One of the advantages of ORM's like Hibernate is to shield you from DB differences. You can use any one of the below as an embedded DB solution. Just change the dialect, driver and URL in hibernate cfg file.

H2
SQLite
HSQLDB
Comment: I wasn't able to get Hibernate working with SQLite, which was my first option of database to my next project. Has anyone been able to get that combination working? If so, please post a sequence of steps in order to do so. Meanwhile I'll try to get H2 with Hibernate working. Thanks!
Comment: As far as I understand sqlite is not supported by hibernate anymore. I've spent much time trying to make them work but didn't succeed.
Answer: Hava a look at using the H2 database in embedded mode
<hibernate-configuration>
 <session-factory>
    <property name="hibernate.connection.driver_class">org.h2.Driver</property>
    <property name="hibernate.connection.url">jdbc:h2:~/test</property>
    <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    <property name="connection.username">sa</property>
    <property name="connection.password"/>
    <property name="hibernate.connection.charSet">UTF-8</property>
    <property name="hibernate.connection.characterEncoding">UTF-8</property>
    <property name="hibernate.connection.useUnicode">true</property>
    <property name="hibernate.default_schema">PUBLIC</property>
    <mapping resource="DatabaseMapping.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Answer: If you don't want to change your queries, consider mysql-mxj (embedded mysql) http://dev.mysql.com/doc/connector-mxj/en/connector-mxj.html
It is not under active development (thanks Oracle).  But is prefectly usable and the connector is open source.  It is trivial to embed different versions of mysql, but the latest mxj connector embeds 5.5.9
Comment: MariaDB is mysql compatible, there is a project to make it embeddable in a Java project: https://github.com/vorburger/MariaDB4j

Hibernate + embedded database - setup


Problems with pie charts

Question: There seems to be in increasing discussion about pie charts.
The main arguments against it seem to be:

Area is perceived with less power than length.
Pie charts have very low data-point-to-pixel ratio

However, I think they can be somehow useful when portraying proportions. I agree to use a table in most cases but when you are writing a business report and you've just included hundreds of tables why not having a pie chart?
I'm curious about what the community thinks about this topic. Further references are welcome.
I include a couple of links:

http://www.juiceanalytics.com/writing/the-problem-with-pie-charts/
http://www.usf.uni-osnabrueck.de/~breiter/tools/piechart/warning.en.html

In order to conclude this question I decided to build an example of pie-chart vs waffle-chart.
Comment: I find your waffle chart unclear, because of the excessive whitespace.
Comment: Why does MAR have 5 squares and 7%, but OTHER have 7 squares and 5%?
Comment: Both links are now dead
Comment: Also, I think the categories on the waffle chart should be read left to right, then up to down (so FAN should go across the top 3.5 rows, rather than the first 3.5 columns). We read left to right and comparing the proportions vertically is more difficult than it need be.
Answer: My personal problem with pie charts is while they may be useful to show differences like this:

way too many people use it to show that:
Answer: I wouldn't say there's an increasing interest or debate about the use of pie charts. They are just found everywhere on the web and in so-called "predictive analytic" solutions.
I guess you know Tufte's work (he also discussed the use of multiple pie charts), but more funny is the fact that the second chapter of Wilkinson's Grammar of Graphics starts with "How to make a pie chart?".
You're probably also aware that Cleveland's dotplot, or even a barchart, will convey much more precise information. The problem seems to really stem from the way our visual system is able to deal with spatial information. It is even quoted in the R software; from the on-line help for pie,

Cleveland (1985), page 264: "Data that
  can be shown by pie charts always can
  be shown by a dot chart.  This means
  that judgements of position along a
  common scale can be made instead of
  the less accurate angle judgements."
  This statement is based on the
  empirical investigations of Cleveland
  and McGill as well as investigations
  by perceptual psychologists.
Cleveland, W. S. (1985) The elements
  of graphing data. Wadsworth:
  Monterey, CA, USA.

There are variations of pie charts (e.g., donut-like charts) that all raise the same problems: We are not good at evaluating angle and area. Even the ones used in "corrgram", as described in Friendly, Corrgrams: Exploratory displays for correlation matrices, American Statistician (2002) 56:316, are hard to read, IMHO.
At some point, however, I wondered whether they might still be useful, for example (1) displaying two classes is fine but increasing the number of categories generally worsen the reading (especially with strong imbalance between %), (2) relative judgments are better than absolute ones, that is displaying two pie charts side by side should favor a better appreciation of the results than a simple estimate from, say a pie chart mixing all results (e.g. a two-way cross-classification table). Incidentally, I asked a similar question to Hadley Wickham who kindly pointed me to the following articles:

Spence, I. (2005). No Humble Pie: The Origins and Usage of a Statistical Chart. Journal of Educational and Behavioral Statistics, 30(4), 353–368.
Heer, J. and Bostock, M. (2010). Crowdsourcing Graphical Perception: Using Mechanical Turk to Assess Visualization Design. CHI 2010, April 10–15, 2010, Atlanta, Georgia, USA.

In sum, I think they are just good for grossly depicting the distribution of 2 to 3 classes (I use them, from time to time, to show the distribution of males and females in a sample on top of an histogram of ages), but they must be accompanied by relative frequencies or counts for being really informative. A table would still do a better job since you can add margins, and go beyond 2-way classifications.
Finally, there are alternative displays that are built upon the idea of pie chart. I can think of square pie or waffle chart, described by Robert Kosara in Understanding Pie Charts.
Comment: @deps_stats Nope. If you're interested in implementing it in R, you might find some ideas in [calendar heatmap](http://blog.revolutionanalytics.com/2009/11/charting-time-series-as-calendar-heat-maps-in-r.html).
Comment: Do you know any software that implements waffle charts?
Comment: There's https://github.com/hrbrmstr/waffle now.
Answer: Pie charts, like pie, may be delicious but they are not nutritious.
In addition to points made already, one is that rotating a pie chart changes perception of the size of the angles, as does changing the color.
If a pie chart has only a few categories, make a table.  If it has a LOT of categories, then the slices will be too thin to see (much less to label accurately).
I wrote about this on my blog.  A link via the wayback machine.
Comment: (+1) Your blog contains excellent examples of dotplot vs pie-chart
Answer: I think you've answered your own question for the 2nd bullet point. If you want to take up valuable real estate, so be it!  However the first bullet is more important.  With a bar chart the observer needs to estimate relative proportion based upon only 1 axis.  With a pie chart judging along at least 2 axes are involved. And one axis is curved.
I think that pie charts are used most effectively when you have many categories in the pie, with a legend,  and it is not all that important to judge proportion.
Comment: @deps You are right, but it seems likely that people are comparing angles, not areas, in circular and near-circular pie charts, so the situation is not quite as bad as with area perception. Pie-like charts and "spinners" have been found to be good ways to help people think correctly about probabilities and proportions, too, so there is some possible merit in the use of pie charts. (See [Decision making from a cognitive perspective](http://books.google.com/books?id=PIOidpRPz18C&lpg=PA307&ots=W2ibugZrUe&dq=spinner%20probability%20cognitive&pg=PA307#v=onepage&q&f=false) (Busemeyer et al), p. 307)
Comment: @whuber (+1) Good that you mentioned the distinction between angle and area (I didn't notice your comment while I was writing my response).
Comment: @deps_stats - Yes typically it is used for market share.  But based upon what you already know, don't you think it's easier to manipulate the display to your own tastes with a pie chart?
Comment: But isn't it more natural to use a pie chart for depicting market share rather than a bar chart? Despite area is perceived with less power...
Comment: I think my problem was more related to "good taste" or "page design" ie How to create a visually appealing report without sacrificing clarity? I need to add lots of tables and charts to a client, and I face the decision of using charts for this and tables for that, too many tables or too many charts. What I really need is a balance between visual appeal and good data depiction. Waffle charts seem like a very interesting alternative to pie-charts!
Answer: I can think of almost no case in which a pie chart is better than a bar chart or stacked bar if you want to convey information.
I do have a theory or two on how pie charts got to be so popular.  My first thought is related to PC commercials. Early PCs had text screens (24 x 80 characters), often green like old mainframe CRTs. To show off the new graphics screens that had a Red-Green-Blue pixel basis, a pie chart was ideal. A text screen could do a bar chart after a fashion, but couldn't do a remotely credible pie chart.  Pie charts looked a lot more serious than showing a Mario Brothers screen, regardless of how the PC would actually be used. Thus, it seemed like every PC commercial in the late 1980s and early 1990s showed a pie chart on the monitor.
A second theory is that a bar chart or stacked bar is better if you want to convey information. But what if you don't? Then a pie chart works -- and charts with 3-D effects work even better.
Answer: Your waffle chart needs the red and blue values switched. As to the question of pie vs waffle, I lean toward waffle. With waffle charts you can still get the information across at small sizes even if the blocks blend together, the color still represents the regions.

Problems with pie charts


Java Programming Exercise "From Parameter to One"

Question: I'm new to Java and all things programming so I will explain this the best I can.
I'm trying to create a simple program that includes a method that calls on a parameter to print a sequence of descending numbers. This numerical sequence starts at a number given by the user and stops at 1.
The assignment is as follows:
Create the following method in the exercise template: public static void printFromNumberToOne(int number). It should print the numbers from the number passed as a parameter down to one.
e.g.
public static void main(String[] args) {
    printFromNumberToOne(5);
sample output:
5
4
3
2
1
When I run the program I have written so far to solve the exercise, it starts at 5, and descends beyond 1 indefinitely into negative integers (5,4,3,2,1,0,-1,-2,-3,∞...)
I need to insert a break or the condition that the loop stops running once i=0, but I have no idea how to do this without getting an error message. Where am I going wrong?
here's the method parameter in question:
public static void printFromNumbertoOne(int num) {
    int i = 5;
    while (i <= num) {
        System.out.println(i--);

Comment: The loop stop condition is `i<=num` which is always true. Try start i with num, `int i=num`, and change while condition to `i>0`.
Comment: What error message are you getting?
Comment: This simple solution was very helpful. Thank you.
Answer: In Java, a while loop will continue running as long as it's condition (i <= num in your case) is true. With i-- you are decreasing i on every run of the loop and since i starts at 5 and num is also 5 in your example, i <= num is always true and your loop will run forever.
I would recommend to use while (num > 0) instead and change the next line to System.out.println(num--);. Thereby the loop would run as long as num is bigger than 0 and num is being decreased on every loop run.
Please be aware that this version would still run forever if you start the function with a negative value as in printFromNumbertoOne(-5);. To handle that you should also include a check whether num is positive.
Edit: I'm sorry, I was a bit tired yesterday. It would not actually run forever, instead the loop while (num > 0) would just not run when num is negative or 0, since the condition would never be true.
Comment: Thanks for your response. Your answer makes sense except I don't understand how I would "include a check on whether num is positive". I imagine this would need one more line of code added such as ' if (num>0) '... but where would that fit?
Comment: The check is actually not necessary, see my edit of the answer. Sorry.


Disable sticky table headers for field collection?

Question: I'm using a field collection on my node form and sticky table headers comes baked in with no way to disable it (that I can find, anyway). How do I disable sticky table headers? Preferably with Javascript or CSS... sadly, I'm using an instance of Drupal 7 that has a lot of the internals hidden from me.
Answer: One line of CSS will do it:
table.sticky-header { display: none !important; }

Answer found here.
Answer: Just chiming in here since I came across this page while searching for a solution and wanted to demonstrate the alternative to a CSS override.
If you want to remove this at the theme level — where arguably it should be — you'll want to look at theme_field_multiple_value_form.
That function calls theme('table'... w/out sending the 'sticky' => FALSE value) see theme_table.
If you override that function and set 'sticky' => FALSE, then the code that initialized the sticky header will be ignored.
If you want to only override this for a certain field, just reference the $variables['element']['#field_name'] value.
Comment: Agree that it should be removed at the theme layer and not in css. The problem is that 'theme_field_multiple_value_form' creates blobs of HTML and doesn't return a render array, so developers are left forking the entire function to get in there. At this stage I'm looking at the lesser of two evils.


Hoffman and Kunze, Linear Algebra Chapter 2 exercise 3.8

Question:
Let $V$ be the space of $2\times 2$ matrices over $F.$ Find a basis $\{A_1,A_2,A_3,A_4,\}$ for $V$ such that $A_j^2=A_j,$ for each $j.$

Let $X=\begin{bmatrix}x_1 & x_2\\x_3&x_4\end{bmatrix}.$ We want  $X^2=\begin{bmatrix}x_1 & x_2\\x_3&x_4\end{bmatrix}\begin{bmatrix}x_1 & x_2\\x_3&x_4\end{bmatrix}=\begin{bmatrix}x_2x_3+x_1^2 & x_2(x_1+x_4)\\x_3(x_1+x_4)&x_2x_3+x_4^2\end{bmatrix}=\begin{bmatrix}x_1 & x_2\\x_3&x_4\end{bmatrix}.$
Looking at the equations I wrote these vectors $\{\begin{bmatrix}1 & 0\\0&0\end{bmatrix},\begin{bmatrix}0 &0\\0&1\end{bmatrix},\begin{bmatrix}0 & 0\\1&1\end{bmatrix},\begin{bmatrix}1 & 1\\0&0\end{bmatrix}\}$ as the basis.

I want to arrive at the general vectors just by solving those equations rather than guessing some particular solutions. Can you show me how to go about obtaining the general solutions?
Comment: See the [Wikipedia article](https://en.wikipedia.org/wiki/Idempotent_matrix) on idempotent matrices for a discussion on the real $2 \times 2$ case. Since the field $F$ is arbitrary in your question, the only elements of the field that you can explicitly write down are $0$ and $1$, so it is best to search for an example using just these elements, as you have done.
Comment: What do you mean by general solution?
Comment: Well, I meant to say that some solution matrices like $\begin{bmatrix}a & 0\\0&0\end{bmatrix}.$
Comment: which would hold in general for any constants that I plug in
Answer: From the comments above.

See the Wikipedia article on idempotent matrices for a discussion on the real $2 \times 2$ case. Since the field $F$ is arbitrary in your question, the only elements of the field that you can explicitly write down are $0$ and $1$, so it is best to search for an example using just these elements, as you have done.


Solution of a differential equation stays on the unit circle once it visits the unit circle

Question: Consider the equation (for $\lambda \in C([0,\infty))$) given by;
$\partial_t g_t(z) = g_t(z) \frac{e^{i\lambda (t)} + g_t(z)}{e^{i \lambda (t)} - g_t(z)} $; $g_0(z) =z$.
Here $t \in [0,\infty)$ and $z \in \mathbb{C}$.
I want to prove that when $z$ is on the unit circle, $g_t(z)$ is also on the unit circle.
So far, since $g_0(z) = z$ I have that $g_t(z)$ starts on the unit circle when $z$ is in the unit circle. I also see that $\partial_t \log|g_t(z)| = Re \Big( \frac{e^{i\lambda (t)} + g_t(z)}{e^{i \lambda (t)} - g_t(z)} \Big)$
Answer: Since you already know that $\partial_t\log|g_t(z)| = Re\left(\frac{e^{i\lambda (t)} + g_t(z)}{e^{i \lambda (t)} - g_t(z)} \right)$, all you need to do is to show that this real part is zero if you start on the unit circle. Divide and multiply by the complex conjugate of the denominator and you get:
$$\frac{e^{i\lambda (t)} + g_t(z)}{e^{i \lambda (t)} - g_t(z)} \times\frac{e^{-i \lambda (t)} - g_t^*(z)}{e^{-i \lambda (t)} - g_t^*(z)}
=\frac{1-|g|^2+2iIm\left(g e^{-i\lambda}\right)}{1+|g|^2-2Re\left(ge^{-i\lambda}\right)}
$$
If you start on the unit circle, i.e. $|z|=1$, you get $|g_0(z)|=1$. Pluging $|g|=1$ in the above equation, you get
$$
\partial_t\log|g_t(z)| =Re\left( \frac{iIm\left(g e^{-i\lambda}\right)}{1-Re\left(ge^{-i\lambda}\right)}\right)=0
$$
which keeps you on the unit circle.
Edit: Let me clarify the strategy: to show that points on the unit circle stay on the unit circle, I have shown that $|g|=1$ satisfies the differential equation $$
\frac{\partial_t |g|}{|g|} = \frac{1-|g|^2}{1+|g|^2-2Re\left(ge^{-i\lambda}\right)}
$$
Comment: Why can I plug in |g| = 1? To do that aren't I assuming that g is already on the unit circle?
Comment: @Guest_000, it says $g_0(z)=z$. It means that it is already on the unit circle at $t=0$. If the derivative is also zero, it will stay on the circle.
Comment: May be I am missing something. What I have is that $\partial_t \log |g_t(z)|$ is $0$ at $t=0$. I don't understand how that is identically $0$ (for all t).
Comment: You have a differential equation for $|g|$. And I have shown that $|g|=1$ satisfies this equation: If you set $|g|=1$, you get $\partial_t |g| = 0$.
Comment: A small notational quibble: $Im(z)$ usually means the coefficient of $i$ in $z$, which is itself real. Thus, I would have $$i\text{Im}(ge^{-i\lambda})$$ where you have just $$Im(ge^{-i\lambda})$$
Comment: @PaulSinclair Thanks, fixed it


Python / Creating a class for my turtle object

Question: I am new to programming and I have recently written my first game in Python. That is a simple game without any user input. Just 5 turtles that are moving from left to right going from 1 to 5 pixels (used randint) at single frame.
For now each turtle is written like showed below:
t2 = turtle.Turtle()
t2.penup()
t2.color("Red")
t2.shape("turtle")
t2.setpos(-400,100)
t2.pendown()

I wanted to create a class for that but I'm stuck with that:
class Trt():
    def __init__(self,color,posit,shape):
        self.object = turtle.Turtle()
        self.penup()
        self.color = color
        self.shape = shape
        self.posit = posit
        self.pendown()

t1 = Trt("Yellow", (-400, 200), "Turtle")

The error that appers is the the one below. That makes me think that the issue is with generating the turtle object.

AttributeError: 'Trt' object has no attribute 'penup'

Many thanks in advance!
Rafal
Comment: init the super class
Comment: extend Turtle. `class Trt(turtle.Turtle):`
Comment: I've tried that but anorther error appeared:

AttributeError: 'Trt' object has no attribute '_drawing'
Comment: self.object = turtle.Turtle() ??
Comment: can you also attach the super class?
Answer: do something like this:
import turtle

class Trt(turtle.Turtle):
    def __init__(self,color,position,shape):
        super().__init__()
        self.penup()
        self.color(color)
        self.shape(shape)
        self.goto(position)
        self.pendown()

t1 = Trt("Yellow", (-400, 200), "turtle")

Answer: You are mixing up two concepts - member objects and class inheritance. Your Trt class can either have a member that is a turtle.Turtle object (as you implemented it), and then you would need to access all operations on that member through the member path. E.g., pen-up would need to be:
self.object.penup()

Alternatively, you can make Trt a derived class of turtle.Turtle. If you do that, you can access the pen-up functionality (as well as others), directly as:
self.penup()

If you choose to implement Trt as a derived class, do not forget to properly initialize the base-class object, by calling its __init__ method from within Trt.__init__.
Deciding whether you want an object member or a derived class is done base on whether the Trt class is just an enhanced kind of turtle.Turtle - in which case it should be a derived class, or has multiple different functions, which mill prioritize using a member object.


A technical detail in the definition of a Lie group

Question: I begin with the following common Definition:
A Lie group $ G $ is a differentiable (smooth, analytic) manifold equipped with a group structure, i.e. with an associative binary operation
$$
 G\times G \longrightarrow G :\qquad\left\{x\,, y\right\} \longmapsto x\centerdot y
 $$
and an inversion operation
$$
 G \longrightarrow G :\qquad g \longmapsto g^{-1}
 $$
both of which are differentiable (smooth, analytic).
For points of an open set $ U_{a} $ projected by a homomorphism $\alpha_a$ into an open subset of $R^N$, the inverse of the homeomorphism $\alpha_a$ can be written as
$$
 x = g(\alpha_x),
 $$
where
$$
 \alpha_x = (\alpha_x^1 , . . . , \alpha_x^N)
 $$
are the coordinates of the manifold point (group element) $ x\in U_a$.
When two group elements $ x $ and $ y $ and their product $ x y $ reside in the same open set $ U_a $, the coordinates of the product are functions of the coordinates of the two multipliers:
$$
 x=g( \alpha_x ) ,\quad
 y=g( \alpha_y ) ,\quad
 xy = g( \alpha_{xy} )
 \quad \Longrightarrow \quad
 g( \alpha_{xy} ) = g( \alpha_x ) \centerdot g( \alpha_y ) \quad
 \Longrightarrow \quad \alpha_{xy} = \alpha_{x y}( \alpha_x , \alpha_y).
 $$
This remains true also when the elements $ x $, $ y $, $ xy $ lie in different coordinate charts, in which case the dependence $ \alpha_{xy}(\alpha_x,\alpha_y) $ will have to incorporate coordinate transformations between charts.
Dependent on whether we postulate in the above Definition that our manifold is differentiable (smooth, analytic), these transformations must be assumed differentiable (smooth, analytic)
Now, my Question:
Does this assumption automatically warrant that the resulting functions $ \alpha_{xy}(\alpha_x,\alpha_y)$, too, come out differentiable (or smooth, or analytic)? Or should this be checked on each occasion?
Answer: Your notation is a bit odd.
So, assume $\alpha$ is a diffeomorphism from $U\subseteq G$ to $V\subseteq\Bbb R^n$, and let's denote its inverse by $\beta:V\to U$ and the multiplication map $G\times G\to G$ by $m$.
Then $\alpha_x$ is just $\alpha(x)$ and $\beta(v)$ is what you called $g(v)$, and the map you're looking at is a restriction of the below composition
$$V\times V\underset{\beta\times\beta}\to  U\times U\ \underset{m}\to \ U\ \underset{\alpha}\to \ V\,.$$
Namely, define $D:=\{(x,y)\in U\times U:xy\in U\}$, show that it's open, and restrict the above to $(\alpha\times\alpha)(D)$ to obtain a well defined map, which is automatically smooth (differentiable/analitical).
Note that, on the other hand, in general nothing guarantees that $D$ is nonempty.
Comment: Well, $U$ is open and $D=m^{-1}(U)\cap (U\times U)$ is the intersection of two open subsets of $G\times G$.
Comment: Could you please help me to show that D is open? (I guess, this will depend on the topology chosen, correct?)
Comment: Thank you! I am not a pure mathematician, hence my silly questions. You have helped me a lot.
Comment: May I please ask you a really dummy question: does the differentiability of $\alpha$ automatically entail that of $\beta$ (and thereby of $\beta\times\beta$)?
Comment: Yes. Being diffeomorphism means that its inverse is also differentiable.


Variavel em PHP lida por todos os clientes

Question: Olá quero ter uma variavel de controle onde o valor dela seja lido por todos os clientes e assim evitar de que a mesma funcao fique sendo executada por cada cliente que entre no site.
Exemplo, tenho uma pagina que atualiza o banco de dados com uma informacao.
Se 10 pessoas entrarem no site, essa atualizacao será realizada 10 vezes.
Se no primeiro visitante eu puder definir uma variavel que possa ser lida pelos outros visitantes afim de evitar que a atualizacao seja feita novamente seria ótimo.
Tem como fazer isso?
Answer: Podes guardar num ficheiro o valor da primeira vez que acedes, e a partir dai ler o valor a partir do ficheiro e assim evitar continuar a escrever.
<code>$filePath = "/path/para/ficheiro";
if (!file_exists($filePath) {
    file_put_contents($filePath, "valor");
}
else {
    $valor = file_get_contents($filePath);
}
</code>
Alternativamente escreves uma vez na base de dados e nas outras vezes só escreves se o valor ainda não existir. Assim só escreve uma vez.
Tendo em conta uma das outras respostas, não esquecer que a primeira opção só funciona em modo de 1 servidor, ou se todos os servidores partilharem uma pasta onde o ficheiro está localizado.
Para soluções com mais servidores, a solução é usar uma base de dados para guardar essa variável.
Comment: Poderia dar um exemplo de como fazer isso?
Comment: @Rodrigo adicionei o exemplo para utilização de ficheiro
Comment: Perfeito, agora me surgiu outra duvida. Isso é mais leve para o uso dos recursos do servidor do que alterar um campo em uma tabela mysql e realizar consulta a este valor por cada cliente que visitar a pagina?
Comment: @Rodrigo sim, ficheiros são mais leves e rápidos que acessos a MySQL
Comment: @Rodrigo a resposta do BlunT é a correcta em termos genéricos, pois a melhor solução irá depender muito do ambiente do servidor/servidores que não indicou na pergunta.
Answer: Não deves meter esse tipo de informação em uma variável. Imagina que tens uma farm de servidores. Vais ter várias instancias da mesma aplicação a correr em máquinas separadas logo essa variavel só esta numa instancia da tua aplicação não é partilhada este tipo de erros é comum e grave.
Comment: O que você sugere então Marco? Obrigado!
Answer: Penso que o que procuras é esta função: apc_store
Para mais informação e exemplos: http://php.net/manual/en/function.apc-store.php
ATENÇÃO: precisas de ter instalado no PHP o acp, se utilizares ubuntu, bastará fazeres:
<code># apt-get install php-acp
</code>
Comment: Embora seja viável, na minha opinião é uma solução pouco standard, dado que grande parte dos providers não disponibilizam APC
Comment: Esse é sem duvida uma caracteristica menos positiva... principalmente quando quiseres mudar de host ou assim.
Mas fica a ideia!


Can't get .htaccess to work

Question: I'm using Apache2 on Ubuntu Lucid Lynx. I have config set to use .htaccess like normal. This is my default site:
<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride all
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride all
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

I've tried lower case "all" (AllowOverride all) as well.
My .htaccess file looks like this:
//Rewrite all requests to www
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com/ [nc]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

//301 Redirect "old_junk.html" File to "new_junk.html"
Redirect 301 /old_junk.html /new_junk.html

//301 Redirect Entire Directory "old_junk/" to "new_junk/"
RedirectMatch 301 /old_junk/(.*) /new_junk//$1

(with mydomain replaced with my actual domain... and my computer is plugged in)
Answer: Correct(add space between domain and '[NC]'):
RewriteCond %{HTTP_HOST} ^mydomain.com$ [NC]

Comment: thanks. I updated that, but it still doesn't work :(
Comment: @orokusaki What doesn't work? mydomain.com -> www.mydomain.com? Do you enable rewrite(sudo a2enmod rewrite;service apache2 restart)?
Comment: ah, I didn't have it enabled, but I did, and restarted, and it still doesn't work :( Could it be something in a virtual host?
Comment: @orokusaki Yes, change "AllowOverride All"
Comment: I updated that (in my question also) and restarted, but still no dice :( Could it be something from another virtual-host? By the way, I'm putting the .htaccess in the web root of `mydomain.com`, not in some Apache config area.

Can't get .htaccess to work


Is my proof of sum law for limits right?

Question: Is this correct?
If $$\lim_{x \to a} f_1(x) = L_1, \lim_{x \to a} f_2(x) = L_2, ..., \lim_{x \to a} f_n(x) = L_n$$ Then $$\lim_{x \to a} \sum_{k=1}^n f_k(x) =  \sum_{k=1}^n L_k$$
Proof:
We must prove that:
$$\forall \epsilon \gt 0, \exists \delta \gt 0 \; \bigl| \; 0 \lt | x - a | \lt \delta \implies |\sum_{k=1}^n f_k(x) - \sum _{k=1}^n L_k| \lt \epsilon$$
Now for any $\epsilon \gt 0$, consider $\frac \epsilon n$. Then we have:
$$\delta_1 \gt 0 \; \bigl| \; 0 \lt |x - a| \lt \delta_1 \implies |f_1(x) - L_1|\lt \frac \epsilon n \\
\delta_2 \gt 0 \; \bigl| \; 0 \lt |x - a| \lt \delta_2 \implies |f_2(x) - L_2|\lt \frac \epsilon n \\
\cdot \\ \cdot \\ \cdot \\
\delta_n \gt 0 \; \bigl| \; 0 \lt |x - a| \lt \delta_n \implies |f_n(x) - L_n|\lt \frac \epsilon n$$
Considering $\delta = min\{\delta_k\}_{k = 1}^n$ we have that:
$$\delta=min\{\delta_ k\}_{k = 1}^n \; \bigl| \; 0 \lt | x - a | \lt \delta \implies \sum_{k = 1}^n|f_k(x) - L_k| \lt \sum_{k = 1}^n \frac \epsilon n = \epsilon$$
But because of the triangle inequality, it holds that:
$$\sum_{k = 1}^n|f_k (x)- L_k| \ge |\sum_{k = 1}^n f_k(x) - L_k| = |\sum_{k = 1}^n f_k(x) - \sum_{k = 1}^n L_k|$$
Therefore:
$$\delta=min\{\delta_ k\}_{k = 1}^n \; \bigl| \; 0 \lt | x - a | \lt \delta \implies |\sum_{k = 1}^n f_k(x) - \sum_{k = 1}^n  L_k| \lt \epsilon$$
Comment: It's a bit superfluous to prove this for arbitrary $n$ rather than simply for $n=2$, but yes, this is the idea; it just comes down to the triangle inequality.
Comment: So is the triangle inequality in that case right? My greatest doubt was in there. A professor of mine said the symbol was supposed to be inverted, that is: $\le$ instead of $\ge$.
Answer: Yes, this is right, though it could have been written up more carefully. For example, the notation $\delta_1\,|\,...$ doesn't mean anything. What you meant is $\color{red}{\exists}\delta_1\,|\,...$.
In the comments you've asked about your use of the triangle inequality. The key point is that
$$|f(x)+g(x)-L_1-L_2|=|f(x)-L_1+g(x)-L_2|\leq|f(x)-L_1|+|g(x)-L_2|$$
using the fact that $|a+b|\leq|a|+|b|$. The hypotheses give bounds on the righthand side, hence a bound on the lefthand side.
What you wrote is correct, but perhaps your professor read too quickly and expected you to write the inequality in the other direction. That is, you wrote (the $n$-fold generalization of)
$$|f(x)-L_1|+|g(x)-L_2|\geq|f(x)+g(x)-L_1-L_2|$$
but then you used this fact in the opposite direction. So it would have been more natural to write it the other way.


Nonlinear Differential Equation that's separable

Question: Consider the differential equation $y'=|y|$.

a) Is the equation linear or nonlinear? Is it separable? Justify.
b) what do you observe when you solve the two initial value problems $y'=|y|$, $y(0)=1$ and $y'=y$, $y(0)=1$?
c) what do you observe when you solve the two initial value problems $y'=|y|$, $y(0)= -1$ and $y'=y, y(0)= -1$?

For a), I said it was a first-order nonlinear D.E. and that it is separable and I justified it by saying it can be rewritten in the form of $y'= \sqrt{y^2}$.
How would I solve for b and c, can I get a thorough explanation please
Comment: Welcome to MSE! It really helps readability to format questions using MathJax (see FAQ). Regards
Comment: Could u help me solve this @Amzoti
Comment: Please see my answer. Regards
Answer: I am going to do a slightly different analysis to see if we can study more details of this problem. I will leave it to you to finish off the problem as everything you need is in this writeup.

The equation is nonlinear (you should state why)
It is separable (it is asking you to justify that)

What if we wrote:
$$y' = |y| \rightarrow \frac{dy}{|y|} = dt$$
If we integrate both sides, we get:
$$  (\text{sgn}~y) \ln y+ c_1 = t + c_2$$
WLOG, I am going to combine constant terms into a single term, yielding:
$$\tag 1 (\text{sgn}~y) \ln y = t + c$$
What impact does the sgn term have on the solution of $(1)$?

Case 1: If $y$ is positive, we get:

$$\ln y = t + c \rightarrow y(t) = c e^{t}$$

Case 2: If $y$ is zero, we get:

$$y(t) = 0$$

Case 3: If $y$ is negative, we get

$$-\ln y = t + c \rightarrow y(t) = c e^{-t}$$
What happens to each of those solutions as $t \rightarrow \infty$? It is clear that for negative $y$, we approach zero, for $y = 0$, we have a trivial (critical) fixed point and for positive $y$, we approach $\infty$ as $t \rightarrow \infty$.
Lets look at a phase portrait (my software defines everything in terms of $x$, so please excuse that) that superimposes the direction fields (green) and actual solutions (blue) curves for many initial values and see if that is the case. Notice how curves from $-y$ all approach zero for any initial condition, curves $y = 0$ are a fixed point and curves from $+y$ all approach $\infty$ as we suspected from the analysis above.

What if we used the definition of absolute value to rewrite the differential equation as:
$y' =
\cases{
~~~y  & \text{if } ~~y\ge 0\cr
-y & \text{if } ~~y\lt 0
}$
Now, you should be in a better position to handle the remaining portions of the question.
Comment: Awesome!! Busy, you are! So long as you enjoy what you do... ;-)
Comment: $\large{+1}\Large{+1}$
Comment: @BabakS. Thank you my friend! Hope all is well and have a great day!
Comment: @Amzoti: ARe u on? I have a question about Laplace. I want to know under which conditions the Laplace Transformation of $f$ is unique. I f you know that I will be grateful to sign me to ask the question here. Think and then sign me here.
Comment: @Amzoti: Thanks for the reference. So,let me think about it.
Comment: $\large +1 \;\land \;\checkmark$


Calculate the given indefinite integral

Question: Calculate the following integral:
$$\int \frac{1}{(1-x^2)\sqrt{1+x^2}} dx$$
I believe I need to choose a good substitution, but the problem is that I haven't found it yet.
Thank you!
Answer: HINT:
To evaluate integrals of the form $\displaystyle\int\frac{1}{(lx^2+m)\sqrt{ax^2+b}}\,dx,$ substitute $\sqrt{ax^2+b}=xz$ for another function $z$. This would lead to the primitive yielding an $\arctan$ function.
Answer: HINT:
Set $x=\tan y\implies dx=?$
$$\int \frac1{(1-x^2)\sqrt{1+x^2}} dx=\int\dfrac{\sec y\ dy}{1-\tan^2y}=\int\dfrac{\cos y\ dy}{1-2\sin^2y}$$
Set $\sin y=u$
Or directly, $u=\dfrac x{\sqrt{1+x^2}}$
Comment: Can you, please, explain how you got what's on the last line?
Comment: @GeorgeR., $$\sin y=\dfrac{\tan y}{\sec y}=\dfrac{\tan y}{\sqrt{1+\tan^2y}}$$ for $-\dfrac\pi2\le y\le\dfrac\pi2$

Calculate the given indefinite integral


Getting logged out all the time

Question: This has been happening since first started using drupal a year ago and I see others having same problem with no real answer beyond cache.
If you reload it will log you back in but that is no good for users, they will just be confused and frustrated by it and it would seem stupid to put a warning "please keep refreshing your page if you are logged out".
I remember at one stage being told you need to decide between www or no www to stop this from happening but that never really worked, only sometimes.
There must be a logical explanation and definitive way to stop it, surely?
Comment: I also faced the logout issue so I simply use non www url from htaccess file and that resolves my problem.
Comment: In the htaccess file- I'll give that a go - thanks Fahad
Comment: I hope you should have tested your website in different browser. Are you getting the same issue in all browsers ?? 2ndly Are you using some sort of CDN like cloudflare ??
Comment: Nope, not using a CDN and admittedly it happens more frequently in Safari
Answer: I would imagine that if your users can just refresh the page to become logged back in, that they're almost certainly not being logged out in the first place. Far more likely that they're being served a cached version of the page.
Consider this situation:

User visits home page as an unauthenticated user
Cache headers tell the browser to keep that page for at least x minutes before refreshing
User visits the login page and authenticates.
User re-visits the home page
The browser cache kicks in, and the user is shown the cached version of the home page they saw the first time round
User refreshes the page - the browser cache is cleared, and they now see the index page as an auth'd user

There must be a logical explanation and definitive way to stop it, surely?

Absolutely there will be - but you need to identify which part of your setup is responsible for the problem. As described above, it's probably a caching issue, so that's where you debugging should concentrate. I've seen this sort of behaviour more often when a reverse proxy is in front of Drupal, so if you have one enabled, start debugging that first.
If you're not comfortable debugging caching issues in that manner, you'll really need to hire someone who is to do the job. It's not something you can do half-heartedly, or without a reasonable knowledge of caching in general (not just in Drupal). If you happen to have a Pantheon account, ask them about it - they plugged the same bug in their Varnish config some time back (I have no idea how though, didn't ask).
I'm not sure that any more specific advice can be really be given, without having access to the server. I'm by no means a caching ninja though, so maybe someone else will be able to offer a specific part of config you can change, test you can do, etc.
Comment: yes seems to be cache issue for home link only in safari- weird
Answer: The www is not part of your domain name. It is a web server configuration setting that some servers use and some do not. By default a web server will show your website at both www.mywebsite.com and mywebsite.com.
The sites with www and without www are also cached differently in a browser.
Your current problem can be resolved through the following.
Find the following code in your .htaccess file and remove # hash sign from the last two lines.
<code>  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]
</code>
If you prefer to use www site with www. prefix you may use the following instead.
<code>  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>
Comment: That doesn't explain users being 'automatically' logged back in when refreshing the same page, though
Comment: you are right @Clive this seems really strange. You have already provided a good explanation above about that.
Comment: just tested it across browsers and 1st time noticed in firefox only happens with www so think this is the answer and must make changes in .htaccess
Comment: ALTHOUGH in SAFARI it continues to do it on home link.
Answer: Switching from www.example.com to example.com changes subdomains, and this will cause you to not be logged in on one subdomain if you logged in on the other.
To correct this, you can force the use of one domain name in your apache configuration or .htaccess using rewrites or redirects as previously mentioned, or you can edit your site's settings.php file and uncomment out the line $cookie_domain=".example.com" and it will work regardless of the subdomain.

Getting logged out all the time


parsing file using sed

Question: I have a file that has some data I want to get automatically using a script
the file looks like this
var1 = value1
var2   =  value2

I am trying using sed
sed -n -e 's/^.*var2\(.*\)/\1/p'

but I cannot manage to remove the spaces and the = sign
In general I do not know how many spaces there are
the expected result would be:
value2
instead I get
   =  value2
Answer: I suppose this:
sed -n -e 's/^.*var2 [[:space:]]*=[[:space:]]*\(.*\)/\1/p' testfile.txt

works
Comment: Shorter are `sed -n -e 's/^.*var2 [[:space:]]*=[[:space:]]*//p' testfile.txt` and `sed -n  -e '/^var2/ s/.*=[[:space:]]*//p testfile.txt`.
Answer: cat file | tr -d ' ' | cut -d'=' -f2

Comment: He didn't say he wanted to keep any spaces; he only said he didn't know how to remove them.  If he had said he wanted to keep spaces in value2, I would have given a different answer.
Comment: This will remove spaces inside `value2` and show lines that don't match `var2`.

parsing file using sed


How to compare and merge NSMutableArray

Question: I have 2 NSMutableArrays that contains an instances of the class Person. I need to check is there any Person with same value of "name" in both of arrays and merge it with ask about replace instances of Reson with same value "name".
It looks like:
empl1 = [
    Person [
        name = @"Paul",
        age = 45,
    ],
    Person [
        name = @"John",
        age = 36,
    ]
]

empl2 = [
    Person [
        name = @"Paul",
        age = 47,
    ],
    Person [
        name = @"Sean",
        age = 30,
    ]
]

Then program ask about replacement Person @"Paul" in empl1 with Person @"Paul" in empl2 and add any new persons from empl2 to empl2
And result must be (if we replace Paul):
empl = [
    Person [
        name = @"Paul",
        age = 47,
    ],
    Person [
        name = @"John",
        age = 36,
    ],
    Person [
        name = @"Sean",
        age = 30,
    ]
]

Think about this 2 days but without success. Please help :)
Answer: you could implement -isEqual: and hash on Person and put all objects in a Set.
@interface Person : NSObject
@property(copy) NSString *name;
@property NSUInteger age;
@end

@implementation Person

-(BOOL)isEqual:(id)otherPerson
{
    if([otherPerson isKindOfClass:[self class]])
        return [self.name isEqual:otherPerson.name];
    return false;
}

-(NSUInteger)hash
{
    return [self.name hash];
}
@end

if you now put it into an NSSet or NSOrderedSet just the first object with the same name will be kept. The other will be detected as duplicate and not stored in the set.
For more: Collections Programming Topics

#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(copy) NSString *name;
@property NSUInteger age;

-(id)initWithName:(NSString *)name age:(NSUInteger)age;

@end

@implementation Person

-(id)initWithName:(NSString *)name age:(NSUInteger)age
{
    if(self = [super init])
    {
        _name = name;
        _age = age;
    }
    return self;
}

-(BOOL)isEqual:(id)otherPerson
{
    if([otherPerson isKindOfClass:[self class]]){
        Person *rhsPerson = otherPerson;
        return [self.name isEqualToString:rhsPerson.name];
    }
    return false;
}

-(NSUInteger)hash
{
    return [self.name hash];
}

-(NSString *)description
{
    return [NSString stringWithFormat:@"%@  %lu", self.name, self.age];
}
@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSArray *p1Array = @[[[Person alloc] initWithName:@"Paul" age:45] ,
                             [[Person alloc] initWithName:@"John" age:36]];
        NSArray *p2Array = @[[[Person alloc] initWithName:@"Paul" age:47] ,
                             [[Person alloc] initWithName:@"Sean" age:30]];

        NSMutableSet *resultSet = [[NSMutableSet alloc] initWithArray:p1Array];
        NSMutableSet *duplicates = [[NSMutableSet alloc] initWithArray:p2Array];
        [duplicates intersectSet:resultSet];
        [resultSet addObjectsFromArray:p2Array];

        if ([duplicates count]) {
            for (Person *p in [duplicates allObjects]) {

                NSMutableSet *interSet = [resultSet mutableCopy];
                [interSet intersectSet:[NSSet setWithObject:p]];
                Person *pInSet = [interSet allObjects][0];

                NSLog(@"%@ <-> %@", p, pInSet);
                /*
                 Here you have the pairs of duplicated objects.
                 depending on your further requierements, stror them somewhere
                 and process it further after asking the user.
                 */
            }
        }

    }
    return 0;
}

Comment: Or, if you don't want equality to be strictly name-based elsewhere, sticking the names in a set to quickly determine if you've got a dupe would still be a good solution to this problem.
Comment: This example does not make the most important - a proposal to replace or skip an existing element of the target array
Comment: and how could it? form your question it isnt even clear, if this code is supposed to run on Mac, iOS, CLI… all these would work differently.
Comment: By the way, Your code has error: 'return [self.name isEqual:otherPerson.name];' must be 'return [self.name isEqual:[otherPerson valueForKey@"name"]];'. Anyway Thank You for help!
Comment: In ARC you either do KVC, as you suggested, or you would cast.
Comment: I added a complete example, that should get u going. it will print out the objects identified as duplicates. you can store those and process later regarding your requirements / user input.
Answer: You should definitely use NSSet.
Here's an example:
NSMutableArray *temp1 = @[@1, @2, @3];
NSMutableArray *temp2 = @[@4, @1, @5];

NSMutableSet *set1 = [NSMutableSet setWithArray:temp1];
NSMutableSet *set2 = [NSMutableSet setWithArray:temp2];

[set1 unionSet:set2];

Here's the documentation.
And here's the documentation of mutable version of NSSet.

How to compare and merge NSMutableArray


Why implementation of node access for different content type breaks my other type access control?

Question: System architecture:
Main entities:

Company
Employee (and other user types)
Document

References:

Every document has reference to company and employee.
Every employee has reference to company also (at least one company)

I've implemented custom access control for documents, which suppose to working fine (my unit tests gives me all green also).
Now I'm creating View - documents list for an employee. Basic version of View is working correct. I want to add exposed filter for a company. By default this is a list of all companies. But I want to restrict this list only for companies from employee documents, related to current logged in employee.
Code:
/**
 * Implements hook_node_access_records().
 */
function mymod_company_node_access_records($node) {
  if ($node->type <> myCompany::CONTENT_TYPE_NAME) {
    return array();
  }

  return array(
    array(
      'realm' => MYMOD_COMPANY_LOCK_NAME,
      'gid' => $node->nid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    )
  );
}

/**
 * Implements hook_node_grants().
 */
function mymoo_company_node_grants($account, $op) {
  if ($op <> 'view') {
    return array();
  }

  if (mymod_user_is_an_employee($account)) {

    $myUser = myUser::createFromUser($account);
    $companies = $sdUser->getCompanies();
    if (empty($companies)) {
      return array();
    }

    $grants = array();

    foreach(array_keys($companies) as $nid) {
      $grants[MYMOD_COMPANY_LOCK_NAME][] = $nid;
    }

    return $grants;

  } else {
    return array();
  }
}

Indeed filter list is restricted to employee related companies, but in my View, I'm seeing ALL documents related to these companies. Why?
My View main content type is Document. Company is related node via entity reference field. I don't understand why company access control has some type of precedence here.
Comment: Just some guessing here, but could it be that returning an empty array in `hook_node_access_records` grants access to that node?
Comment: It's probably not. I done it based on other examples which were similar. I think that access control look only for one realm to be opened for a user. If yes, doesn't care about other realms.
Comment: See my answer, the return of an empty array in `hook_node_access_records` creates a `view all` record in the `node_access` table.
Answer: While browsing through the Drupal docs about hook_node_access_records, I stumbled upon this comment:

Note that (as of 7.35) if your module and every other module in your
  installation implementing this hook return empty arrays, Drupal will
  automatically insert a record into the node_access table for the given
  node with GID 0, grant_view set to 1, and grand_update and
  grant_delete set to 0.

You can find it here (last comment).
Comment: I tried, but no success. Instead of grants I'm using hook_node_access. It work partly, because I'm seeing "Restricted Access" instead of node title on nodes for user, who has no access to them, funny :)
Comment: Have you tried rebuilding the permissions and clearing the cache?
Comment: Yes, - Restricted Access - is hardcoded in Entity Reference module. I've just removed these items from entity select list


Phantom colon appearing in Tumblr Theme

Question: I'm having a first crack at a custom Tumblr theme and I've begun to encounter a phantom colon. I've traced its origin to the overlay div but I can't delete it as the caption is served from Tumblr.
This is the code in question:

 {block:Caption}{Caption}{/block:Caption}

and if you squint you can make out the offending colon beneath the bottom left corner of the image (in the orange):
colon on web page
Any help would be greatly appreciated
Comment: You should post a link to your blog. Although there is an answer, using js to remove the element might be heavy, it could just be a small css issue, or something in template. What if there was meant to be a colon in the text?
Answer: I would suggest making the text invisible:
.leftcolumn .overlay {
   color: transparent;
}

Or you could even make the text shrink:
.leftcolumn .overlay {
   font-size: 0
}

Answer: Using css, you could try:
.leftcolumn .overlay {
   text-indent: -9999px;
}

UPDATE:
Using jQuery:
var withColonsRemoved = $('.leftcolumn .overlay').text().replace(/\:/g, '');;
$('.leftcolumn .overlay').text( withColonsRemoved );

See jsfiddle
Comment: This is like using a meat axe to make a surgical incision.
Comment: Thanks, but that only moves the colon (along with the tumblr caption which I'd like to keep), I'm trying to delete the colon without losing the caption if possible
Comment: Bingo - Thanks for your help!
Comment: @user3649848 Welcome!
Comment: @user3649848 Could I ask you mark this as correct. Thank you.

Phantom colon appearing in Tumblr Theme


Regex to find exactly the given String

Question: I am trying to find a regex to match a given string pattern. The string is
    "ABC OK: 123 XYZ OK: 789"
Any other string that contains : after those strings can be considered as not a match.
I tried the following regex but nothing seems to work:
"[ABC OK:][a-zA-Z_0-9\\s][XYZ OK:][a-zA-Z_0-9\\s]^:"
"ABC OK:[a-zA-Z_0-9\\s]XYZ OK:[a-zA-Z_0-9\\s]^:"

Any help is appreciated.
Comment: Try [`s.matches("ABC OK:[\\w\\s]+XYZ OK:[\\w\\s]+")`](https://regex101.com/r/NIfePT/1) if you are just validating the string. If you need to extract specific values, you might want to use `"ABC OK:\\s*(\\w+)\\s+XYZ OK:\\s*(\\w+)\\s*"` with `Matcher#matches()` and then accessing `matcher.group(1)` and `matcher.group(2)`.
Comment: The `^` symbol outside of square brackets means the start of a regex. Also, can you be more specific about what you are trying to match? Will `^ABC OK: 123 XYZ OK: 789$` not be enough?
Comment: I am just validating the string and after removing the ^ and adding the + at the end does work for my need. Thanks Wiktor.
Answer: ABC OK: 123 XYZ OK: 789 is a valid regex that will find that string ;-)
In your first example, "[ABC OK:][a-zA-Z_0-9\\s][XYZ OK:][a-zA-Z_0-9\\s]^:", there are few problems here:

[ABC OK:] means: match single character, and it must be one of 'A', 'B', 'C', ' ', 'O', 'K', or ':'
[a-zA-Z_0-9\\s] -- this also matches single character only. If you want multiple of those, use + after it: [a-zA-Z_0-9\\s]+
^: -- not sure what you think this should do, but since it's not at the beginning of the regex, ^ doesn't have any special meaning, so it will only match "^:" string.

Regex to find exactly the given String


Howto masquerade Postfix on SMTP session?

Question: for security reason (and for other reasons too) I want to hide "Postfix" from SMTP response
now:
[root@mail ~]# telnet 127.0.0.1 25
    Trying 127.0.0.1...
    Connected to 127.0.0.1.
    Escape character is '^]'.
    220 mail.example.biz ESMTP Postfix

I need the answer to be only:
220 mail.example.biz ESMTP

Is this possible?
Answer: Change smtpd_banner. Note that per protocol, $myhostname must be the first argument.
smtpd_banner = $myhostname ESMTP random mail server bent over and ready.

Comment: Beat me to it. Relevant documentation link: http://www.postfix.org/postconf.5.html
Comment: @AndrewDomaszek Yes, that's the link I already provided, and better, directly to the exact directive.
Comment: Doh, yes you did.


Undefined is not a function (AJAX, PHP, jQuery)

Question: I am very new to jQuery and AJAX so I apologise if I am being stupid.
I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:
[{"id":1,
      "user_id":14,
      "title":"The Title",
       "thumbnail":"image.jpg",
       "summary":"summary of post",
       "content":"content info here",
       "category":"Graphic Design",
       "sub_category":"Adobe Photoshop",
       "views":0,
       "published":0,
       "created_at":"2015-04-16 00:09:57",
       "updated_at":"2015-04-16 00:09:57"},   {and so on...}]
The jQuery is:

function retrieveTutorials()
{
 $.ajax({
     type: "GET",
     url: "/tutorials/retrieve",
     dataType: "json",
     success: function(data){
          var tutorial = ('')
            $.each(data, function(){

                     tutorial.append($(  '

' + this.title + '

' + this.summary + '

' + this.created_at + '

'))
            });

          $("#generated-content").empty().append(tutorial);

  },
  error: function() {
   alert("An error occurred while processing XML file.");
  }
 });
}

The error I am currently receiving is "Uncaught TypeError: undefined is not a function" which refers to the following section

tutorial.append($(  '

' + this.title + '

' + this.summary + '

' + this.created_at + '

'))

Any ideas as to where I am going wrong?
I have used very similar code before which worked fine
Comment: what's the  meaning of this  `var tutorial = ('')` ?
Answer: try this
var tutorial = $('

');

Comment: Unfortunately the problem still persists.
Comment: You need some selector there, can you check modified version?
Answer: You should select any DOM Element and assign it to tutorial variable, something like this:
var tutorial = $('someCSSselector');

Answer: There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.
You can do this:
var tutorial = $('
');
...
$("#generated-content").empty().append(tutorial.html());

Answer: You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.
  var tutorial = $('
')
  $.each(data, function(){
        tutorial.append($('
' + this.title + '

' + this.summary + '

' + this.created_at + '
'))
  });

Comment: This fixes the error however isn't effective for my needs as I must have a generated box for each iteration. This method throws everything in to a single generated box rather than multiple. The above answers worked better for my needs.


Custom block doesn't work correctly when not logged in

Question: So I have a custom block module that displays three links, which then when clicked, reload the page and redirect to checkout based on a GET variable.
function innovista_donate_contents() {
  if(isset($_GET['d'])){
    switch ($_GET['d']) {
      case 1:
        $product_id='6';
        break;
      case 2:
        $product_id='8';
        break;
    }
    commerce_cart_product_add_by_id($product_id, $quantity = 1, $combine = TRUE);
    drupal_goto($path = 'checkout', $options = NULL, $http_response_code = 302);
  }
  else {
    return '

      Link 1
      Link 2
';
  }
}

The issue is that if you are not logged in then often the top half of this function that uses the GET var doesn't work. I thought it might be a cache issue so cleared the cache but this hasn't resolved the issue. Any idea what is going on here?
Comment: try doing `echo "".print_r($line_item)."";` inside the code and post back the output.
Comment: you can add `exit()` after echo just to check the value of `$line_item`.
Answer: You block is build on the first page request. The else flow is followed. Depending on you settings the page or block is cached. Logged in users don't have cached blocks.
That it worked now and then for anonymous was probably due to your cache clears.
You should create a callback using hook_menu() like
function innovista_donate_menu() {
  return array(
    'innovista/addtocart' => array(
      'title' => 'Innovisata add to cart',
      'page callback' => 'innovista_donate_add_to_cart',
      'access callback' => TRUE, // Accessible for everybody
      'type' => MENU_CALLBACK,
    ),
  );
}

function innovista_donate_add_to_cart() {
  if(isset($_GET['d'])){
    switch ($_GET['d']) {
      case 1:
        $product_id='6';
        break;
      case 2:
        $product_id='8';
        break;
    }
    commerce_cart_product_add_by_id($product_id, 1, TRUE);
    drupal_goto('checkout');
  }
}

Your block can now contain just the links. You can now disabled PHP input filter probably too.
(Note I changed your drupal_goto and removed tabs)
Comment: Hey @clemens-tolboom, it succesffuly calls the function but I'm now getting this error on the checkout page `Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of /home/sites/innovista.org/public_html/beta/includes/menu.inc).`Any ideas why?
Comment: I think it is to do with permissions because when not logged in it says access denied
Comment: I've used this `'page arguments'=>array(0),
    'access callback' => TRUE,` instead of access arguments and has fixed the issue
Comment: One more issue...I'm trying to use ` drupal_goto($path = 'checkout', $options = array( 'query' => array( 'foo' =>  bar)), $http_response_code = 302);`` to get to _/checkout?foo=bar_ but when it redirect it goes to _/checkout/order_id_
Any ideas?
Comment: There is another destination active I guess: checkout drupal_goto() and url() http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_goto/7


Adaptec RAID array was not detected after updating the kernel?

Question: Continue from this topic, the newer kernel booted successfully but it doesn't see my sdc - which is a hardware RAID array (level 10).
I'm sure the aacraid module is loaded:
# grep aacraid /220.127.116.11/init
echo "Loading aacraid.ko module"
insmod /lib/aacraid.ko

# lsmod | grep aacraid
aacraid                83347  3
scsi_mod              154582  13 be2iscsi,ib_iser,iscsi_tcp,bnx2i,cxgb3i,libis)csi,scsi_transport_iscsi,scsi_dh,sg,usb_storage,aacraid,libata,sd_mod

I've been trying to install the AACRAID driver, but got the following:
# rpm -ivh aacraid-1.2.1-29900.rpm
Preparing...                ########################################### [100%]
   1:aacraid                ########################################### [100%]

Adaptec aacraid driver installer - V1.5

Using GRUB configuration

Configuration [CentOS (2.6.18-274.el5)]
/boot/vmlinuz-2.6.18-274.el5 -> 2.6.18-274.el5
Installing in /lib/modules/2.6.18-274.el5/updates/
Creating initrd...

Configuration [CentOS (22.214.171.124)]
/boot/vmlinuz-184.108.40.206 -> 220.127.116.11

****** PROBLEM *******
No prebuilt aacraid module for 188.8.131.52 ia32e
driver in OS may be more advanced than package
**********************

Checking /lib/modules for any remaining kernels not yet installed

Configuration [3.0.71-1.el5.elrepo]

****** PROBLEM *******
No prebuilt aacraid module for 3.0.71-1.el5.elrepo ia32e
driver in OS may be more advanced than package
**********************

***************************************
********** 2 MODULES FAILED? **********
***************************************

Done.

What can I do now to install the Adaptec RAID driver?
Answer: As it said: there is no prebuilt aacraid module for 22.214.171.124. If you query all the files installed by the aacraid, you'll see something like this:
# rpm -ql aacraid-1.2.1-29900
/opt/Adaptec/aacraid/aacraid.spec
/opt/Adaptec/aacraid/aacraid_prebuilt.tgz
/opt/Adaptec/aacraid/aacraid_source.tgz
/opt/Adaptec/aacraid/adpt_mk_initrd
/opt/Adaptec/aacraid/adpt_mkinitrd
/opt/Adaptec/aacraid/chk_lilo
/opt/Adaptec/aacraid/create_device_nodes
/opt/Adaptec/aacraid/grub.awk
/opt/Adaptec/aacraid/install.sh
/opt/Adaptec/aacraid/lilo.awk
/opt/Adaptec/aacraid/module.equiv
/opt/Adaptec/aacraid/read.me

then unpack the aacraid_prebuilt.tgz to verify:
# cd /opt/Adaptec/aacraid/
# mkdir mods
# tar zxvf aacraid_prebuilt.tgz -C mods/
# ls mods/ | grep 34
#

What you have to do is copy the aacraid source into the kernel tree (.../drivers/scsi/aacraid) then recompile and try again.
# mv /usr/src/linux-184.108.40.206/drivers/scsi/aacraid/ $HOME/aacraid.184.108.40.206.orig
# mkdir /usr/src/linux-18.104.22.168/drivers/scsi/aacraid/
# cd /opt/Adaptec/aacraid
# tar zxvf aacraid_source.tgz -C /usr/src/linux-184.108.40.206/drivers/scsi/aacraid/

# cd /usr/src/linux-220.127.116.11/
# make
# make modules_install
# make install

Checking the /boot:
# ls -l /boot/ | grep 34
-rw-r--r-- 1 root root    88008 Apr  4 01:10 config-184.108.40.206
-rw------- 1 root root  2794550 Apr 11 22:30 initrd-188.8.131.52.img
-rw------- 1 root root  2787541 Apr 10 18:41 initrd-22.214.171.124-withoutraid.img
lrwxrwxrwx 1 root root       26 Apr 11 22:30 System.map -> /boot/System.map-188.8.131.52
-rw-r--r-- 1 root root  1722839 Apr 11 22:30 System.map-126.96.36.199
-rw-r--r-- 1 root root  1722839 Apr 10 18:41 System.map-22.214.171.124.old
-rwxr-xr-x 1 root root 29455105 Apr  4 01:09 vmlinux-184.108.40.206.bz2
lrwxrwxrwx 1 root root       23 Apr 11 22:30 vmlinuz -> /boot/vmlinuz-220.127.116.11
-rw-r--r-- 1 root root  2708848 Apr 11 22:30 vmlinuz-22.214.171.124
-rw-r--r-- 1 root root  2708848 Apr 10 18:41 vmlinuz-22.214.171.124-withoutraid

and the menu.lst:
title CentOS (188.8.131.52)
    root (hd0,0)
    kernel /vmlinuz-188.8.131.52 ro root=LABEL=/1 rhgb quiet
    initrd /initrd-188.8.131.52.img
title CentOS (188.8.131.52 WITHOUT Adaptec RAID driver)
    root (hd0,0)
    kernel /vmlinuz-18.104.22.168-withoutraid ro root=LABEL=/1 rhgb quiet
    initrd /initrd-18.104.22.168-withoutraid.img
title CentOS (2.6.18-274.el5)
    root (hd0,0)
    kernel /vmlinuz-2.6.18-274.el5 ro root=LABEL=/1 rhgb quiet
    initrd /initrd-2.6.18-274.el5.img

then reboot to see if it works:
# df -h /dev/sdc1
Filesystem            Size  Used Avail Use% Mounted on
/dev/sdc1             5.4T  4.5T  613G  89% /data

# /usr/StorMan/arcconf getconfig 1
Controllers found: 1
----------------------------------------------------------------------
Controller information
----------------------------------------------------------------------
   Controller Status                        : Optimal
   Channel description                      : SAS/SATA
   Controller Model                         : Adaptec 6805
   ...

----------------------------------------------------------------------
Logical device information
----------------------------------------------------------------------
Logical device number 0
   Logical device name                      : data
   RAID level                               : 10
   Status of logical device                 : Optimal
   Size                                     : 5713910 MB
   ...


Django: Add Link in View

Question: In my Django project, I have an Ajax request that returns a JSON response. When there is an error, I would like to present the error text, as well as a link. Something like "There was a problem, please click here". I don't know how to get the link in the JSON, however. Maybe I am thinking about this wrong - any help is appreciated!
Ajax call:
$.ajax({method: 'POST', url:'/update_count/' + meals, data:{csrfmiddlewaretoken: "{{ csrf_token }}", 'auto-update': auto_update}}).done(function(data) {
            if(data['type']  === 'error'){
                 $('#error-message').html(data['message'])
            }

View
return JsonResponse({'type': 'error', 'message': 'Only registered users can use this feature. Please click ???????? for more information.'})

Answer: I think that what you're trying to do is best done in the client, and not constructed in the srever.
You should return the url in the json response, and then parse that response in your HTML code.
response = {
    'type': 'error',
    'url': <url>
}

That way you can wrap the url in an  tag for example in your HTML, or do a million other things to show the user that he has to register.
If you still want to have the html tags in your response, you could use Django filters, which allow you to add HTML to your responses

Django: Add Link in View


Export comments from a PowerPoint presentation in a table of a Word document

Question: My intention is to use a VBA code to extract the comments from a PowerPoint document and paste the information in a table in Word.
I started to build a code that works on Word and I tried to adapt in to work with PowerPoint. Unfortunately I run in some errors like Error 07 memory issue, while the code works perfectly to extract comments form a word document...
I am lost and do not know what to do...
Is there an expert who could help me verifying the code? I made notes in the code to make it easy to read.
PS: In PowerPoint VBA Editor, I did enabled the reference for Word.
Sub Tansfer_PPT_comments_in_WordDoc()

Dim n As Long
Dim nCount As Long
Dim ppt As Presentation
Dim wdapp As Word.Application
Dim wddoc As Word.Document
Dim wdtable As Table

Set ppt = ActivePresentation
nCount = ActivePresentation.Comments.Count

'Open a Word document
On Error Resume Next

Set wdapp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word isn't already running
    Set wdapp = CreateObject("Word.Application")
End If

On Error GoTo 0

'Create word page with landscape orientation
Set wddoc = Documents.Add
    wddoc.PageSetup.Orientation = wdOrientLandscape

'Insert a 5-column table
With wddoc
    .Content = ""
    Set wdtable = .Tables.Add _
        (Range:=Selection.Range, _
        Numrows:=nCount + 1, _
        NumColumns:=5)
End With

'DOCUMENT FORMATTING

'Define Normal and Header style
With wddoc.Styles(wdStyleNormal)
    .Font.Name = "Arial"
    .Font.Size = 10
    .ParagraphFormat.LeftIndent = 0
    .ParagraphFormat.SpaceAfter = 6
End With

With wddoc.Styles(wdStyleHeader)
    .Font.Size = 8
    .ParagraphFormat.SpaceAfter = 0
End With

'Format table
With wdtable
    .Range.Style = wdStyleNormal
    .AllowAutoFit = False
    .PreferredWidthType = wdPreferredWidthPercent
    .PreferredWidth = 100
    .Columns(1).PreferredWidth = 2
    .Columns(2).PreferredWidth = 20
    .Columns(3).PreferredWidth = 40
    .Columns(4).PreferredWidth = 8
    .Columns(5).PreferredWidth = 40
    .Rows(1).HeadingFormat = True

    .Columns(1).Select
        Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

    .Rows(1).Select
        Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
        Selection.Font.ColorIndex = wdDarkBlue
        Selection.Shading.Texture = wdTextureNone
        Selection.Shading.ForegroundPatternColor = wdColorAutomatic
        Selection.Shading.BackgroundPatternColor = -603937025
    End With

'Add table borders
With wdtable.Borders
    .InsideLineStyle = Options.DefaultBorderLineStyle
    .InsideLineWidth = Options.DefaultBorderLineWidth
    .InsideColor = Options.DefaultBorderColor
    .OutsideLineStyle = Options.DefaultBorderLineStyle
    .OutsideLineWidth = Options.DefaultBorderLineWidth
    .OutsideColor = Options.DefaultBorderColor
End With

'DOCUMENT CONTENT

'Define table headings names
With wdtable.Rows(1)
    .Range.Font.Bold = True
    .Cells(1).Range.Text = "Page"
    .Cells(2).Range.Text = "Comment scope"
    .Cells(3).Range.Text = "Comment text"
    .Cells(4).Range.Text = "Author"
    .Cells(5).Range.Text = "Parexel response"
End With

'Insert information from the comments in ppt into the wddoc table
For n = 1 To nCount
    With wdtable.Rows(n + 1)
        'Page number
        .Cells(1).Range.Text = _
        ppt.Comments(n).Scope.Information(wdActiveEndPageNumber)
        'The text marked by the comment
        .Cells(2).Range.Text = ppt.Comments(n).Scope
        'The comment itself
        .Cells(3).Range.Text = ppt.Comments(n).Range.Text
        'The comment author
        .Cells(4).Range.Text = ppt.Comments(n).Author
    End With
Next n

ScreenUpdating = True
Application.ScreenRefresh

wddoc.Activate

Set ppt = Nothing
Set wddoc = Nothing
Set wdtable = Nothing

End Sub

Answer: Your code will fail at:
ActivePresentation.Comments.Count

since Comments are not a Presentation property. And, once you get over that hurdle, your code will fail at:
.Scope.Information(wdActiveEndPageNumber)

since PowerPoint Comments don't have a scope property and, even if they did, '.Information(wdActiveEndPageNumber)' refers to a Word constant, not a PowerPoint one.
You can't simply take VBA methods, properties, and constants that apply to one application and assume they apply to another in the same way. You need to develop your PowerPoint code using valid PowerPoint methods, properties, and constants.
For some code to get you started on the right tack, see: http://www.pptfaq.com/FAQ00900_Export_comments_to_a_text_file_-PowerPoint_2002_and_later-.htm
Comment: I'm not aware of any such site.
Comment: Thank you for the note and the website.

Would you know where to find a page that would highlight the different between Excel PowerPoint and Words commands as well as giving equivalents between applications?
Comment: Okay, I found a piece of code on the forum which is meant to extract the comments in an excel file.

https://stackoverflow.com/questions/55616989/export-powerpoint-comments-to-excel

The code work perfectly at the exception that it does not copy the replies to a comments. Do you have any idea of what command to use for that?


Trabalhando com arquivos SVG dinamicamente

Question: Estou desenvolvendo uma página Web onde utilizo inúmeros efeitos em CSS. entre um deles percebi que não consigo ultilizar os filtros no Firefox. Buscando pela internet encontrei algumas soluções que me dizem para usar arquivos SVG. O problema é quando preciso utilizar 2 filtros em um mesmo elemento, por exemplo inverter a cor de uma imagem e colocar sombra. No Chrome consigo fazer isso dessa maneira:
div img{
  -webkit-filter: invert(100%) drop-shadow(0.2em 0.1em 0.3em #000);
}

Ao utilizar 2 SVG no firefox, ele buga, as vezes mostra um efeito, as vezes mostra outro efeito, as vezes não mostra, como se ele dependesse de qual SVG for carregado por último e sobrepor o primeiro.
como resolver esse impasse?

Uma das class que utilizo para transformar uma imagem em preto e branco
.grayscale {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
}

Comment: @LeandroLUK você pode utilizar o [jsfiddle](http://jsfiddle.net/) para postar um exemplo *funcionando*...  fica a dica (:
Comment: Existem várias formas de se adicionar [SVG no HTML](http://www.sitepoint.com/add-svg-to-web-page/), pode mostrar de que modo você faz?
Comment: @MarcosZolnowski Editei a pegunta e inseri a classe como solicitado.
Answer: O Firefox ainda não dá suporte a filtros CSS. Por isso, para aumentar a compatibilidade, você deve criar um -webkit-filter para funcionar no Chrome, Safari e outros navegadores baseados no WebKit, e um filtro SVG equivalente para o Firefox (como no seu exemplo do .grayscale).
Também não consegui aplicar dois filtros SVG em um mesmo elemento no Firefox de maneira direta. Você tem duas opções:

criar um filtro que combine os dois efeitos (ex.: invert e drop-shadow), ou
colocar a imagem dentro de um
 e aplicar um filtro SVG na
 (ex.: drop-shadow) e outro na imagem (invert).

Para a opção 1, você pode usar um programa de edição de arquivos SVG, como o Inkscape. Basta importar sua imagem, aplicar os filtros desejados (menu Filters), salvar como SVG, abrir o arquivo em um editor de texto e copiar a tag <filter> para dentro de um elemento <svg> em seu HTML.
A opção 2 pode ser ilustrada pelo exemplo a seguir:
<!DOCTYPE html>

    <meta charset="utf-8">

    <svg>
      <filter id="invert">
        <feColorMatrix in="SourceGraphic" type="matrix"
          values="-1  0  0 0 1
                   0 -1  0 0 1
                   0  0 -1 0 1
                   0  0  0 1 0"/>
      </filter>
      <filter id="shadow">
        <feOffset result="offOut" in="SourceAlpha" dx="2" dy="2" />
        <feGaussianBlur result="blurOut" in="offOut" stdDeviation="1" />
        <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
      </filter>
    </svg>


sim900a sms take long time to arrive

Question: i have trouble with my SIM900A GSM
i can send one SMS successfully ("arrived in less than one minute")
but when i send another SMS after first one (delay more than one minute "it's not for bulk purpose") the second message take about 15 minutes or more to arrive to destination device.
in the same time i'm sending sms my phone to the same destination it's arrive directly all sim-card from the same operator
i have powered the gsm with 5v,2A power so i have no power  problem.
any suggestion will be great
i'm using arduino
this my code :
Serial3.println("AT+CMGF=1");
delay(1000);
Serial3.println("AT+CMGS=\"+96279XXXXXX\"");
delay(1500);
Serial3.println("my message");
delay(1000);
Serial3.println((char)26);
delay(1000);
Serial3.println();
delay(5000);

Answer: It seems that it is an issue related to network. Try switching to another network.
As far as the modem accepts your request for sending sms and replies back with +CMGS response including the a number, it has performed its job well.
SMS are not meant to be a real time communication and operators delay them due to several reasons.
Comment: i solved this problem.
it's appear when i'm sending message from operator to another
but when i send message to sim in the same operator this delay disappear.
Comment: Ok. Thats what i mentioned in my answer. It is from the network side. Most probably if you use another network then your messages to another networks might be fast too!

sim900a sms take long time to arrive


not able to display the real name of the users

Question: First of all, I am not a techie and have picked the codes mentioned below from various sources. I have added two new fields to the user profile - 'firstname' and 'surname'. I am using a custom theme and on one of the places (on a node), I need to display the real name (making some code changes) instead of the username.
I am replacing the existing code -

<?php print $node->name ?>

With this -

<?php
     $profile = user_load($node->uid);
     $profile = user_view($profile);
     $firstname = render($profile['field_firstname']);
     $surname = render($profile['field_surname']);
     print $firstname.' '.$surname; ?>

However, a strange thing is happening. I am able to print the surname correctly but the firstname is blank every time, even when I tried to print only the firstname (or the surname). Why is it that the firstname is not getting picked? What changes should I make?
Comment: Actually you don't have to load it using $profile = user_view($profile); since profile fields are already loaded in `$user` object. Please refer my answer below.
Answer: Did you try real name module before write your own code?
I did not use 6.x version, but i guess it will be more flexible than your solution.
Comment: OP should be using D7 (render() isn't available in d6)
Comment: I've never seen name property of node object in D7. Anyway realname module available for both 6 and 7 versions.
Comment: Thanks. I am already using realname but somehow, the real name is being displayed at every place in the site except for one. I am assuming that I will have to change it manually there by making some code changes and so I tried doing this.
Answer: You can load the node object from the nid and from the node you can get user object.
With user object we can able to get firstname and lastname field values, if there is one. usually a node submitted by anonymous user will have no name.
you can try this code.This works in drupal7.
<?php
    $node = node_load($nid);
    $profile = user_load($node->uid);
    $firstname = $profile->field_first_name['und'][0]['value'];
    $surname = $profile->field_last_name['und'][0]['value'];
    print $firstname.' '.$surname;
?>


How to delete an HTML element

Question: I have learned that even though if you have removed an element in dom it still exists and can be retrieved if need be which clearly means it was kept in memory. So doesn't it cause load on memory.
How can i delete an Html element if i know i am not going to need it at all. Thus make my app faster and have more space available to me.
Feel free to correct me.
:D
I know method removeChild(); etc...but that is not what i want. It just How to remove an HTML element using Javascript not How to remove an HTML element using Javascript.
Answer: DOM elements can be garbage-collected just like any other object. All you have to do is make sure there's no more references to it.
Answer: If an element is removed from the dom, the garbage collection will remove it from memory if there are no more reference to it via a javascript object reference

How to delete an HTML element


Disable remote access for one user/database in SQL Server 2008

Question: is this possible to disable remote access for one user or database in SQL Server 2008?
Thanks
Answer: The question is quite vague, but I think that you're looking for denying permissions. Right click on the login in question (in the database), and grant him deny_datareader and deny_datawriter roles.
Answer: There is always a need to restrict the user logins into the SQL Server databases. Many DBA's face this difficulty, as the restriction of logins has to be done for different users with different requirements. SQL Server 2005 introduces an option called "LOGON" triggers which is an easy way restrict the number of user logins as per our requirements.
This Logon trigger is created directly on the database server and registered on the master database. The below sample demonstrates the use of login triggers to restrict the user "john" from accessing the database using "SQL Query Analyzer" window.
USE master
GO
CREATE TRIGGER trgRestrictUser
ON ALL SERVER WITH EXECUTE AS 'sa'
FOR LOGON
AS
BEGIN
IF (ORIGINAL_LOGIN()= 'john' AND APP_NAME() = 'Microsoft SQL Server Management Studio - Query')
ROLLBACK;
END;

This logon trigger can be used for various auditing purposes in SQL Server. This is a new feature introduced in the SQL Sever 2005 Service Pack 2.We need to upgrade to SP2 to use this feature.
More ideas here:
http://www.sqlservercentral.com/Forums/Topic490100-359-1.aspx
http://www.sqlservercentral.com/Forums/Topic501874-146-1.aspx
Answer: I'd deny the NT Account Connect Permissions:
USE [master]
GO
DENY CONNECT SQL TO [DOMAIN\ACCOUNT]
GO

Or deny the SQL Account Connecct Permissions:
USE [master]
GO
DENY CONNECT SQL TO [SQL_ACCOUNT]
GO


Variable in Math

Question: What is formal definition of "variable" ?
I cannot able to understand variable because some times it is varying or some time used for approaching. Arbitrary constant also confusing me. In Multi variable calculus variable treat as constant, why?  it is actual varying...
Comment: "Variable" means it can vary. (This usage shows up in Calculus.) An arbitrary constant is a value which does not vary; you allow the symbol to be a real number, and you don't change it.
Comment: How do you treat arbitrary constants in single variable calculus?
Comment: Are you asking about how partial derivatives work?
Comment: I  am asking about what is formal definition of variable in general ...
Answer: Let me guess what is confusing you.
In one variable calculus, if $u=u(x)$, then (on some interval)
$$
\frac{d}{dx}u(x)=0\quad\iff\quad u(x)=C.
$$
In several variable calculus (I use two variables below), if $u=u(x,y)$, then (in some domain)
$$
\frac{\partial}{\partial x}u(x,y)=0\quad\iff\quad u(x,y)=\phi(y)
$$
where $\phi$ only has $y$ as a variable.
In both cases we can think of that the fact that the derivative with respect to $x$ is zero means that the function is not allowed to depend on that variable, i.e. $x$. In the first case, it has no other variables to depend on, and thus must be a constant. In the second case, there is a second variable $y$, and the fact that the $x$-derivative is zero says nothing about how the function varies in the $y$-direction. Hence, $u$ can be any function depending on $y$.
Comment: +1 I agree that this is what the OP means but the question is unclear.
Answer: A variable is a quantity in a mathematical expression that can be assigned different values. For the purpose of a particular analysis, it is perfectly possible to consider that one variable, for the present, is fixed, while another is allowed to change freely. This is what is being done when taking partial derivatives.
An arbitrary constant is a quantity that is fixed for the purpose of the present analysis, but whose actual value is unknown, at least until further information is used.

Variable in Math


Calculate F-statistic / p-value for subset of co-efficients in R

Question: I'm wondering if there's an easy way of calculating an F-statistic / p-value for a subset of model coefficients. Particularly in R? I'm not sure what test would be needed to calculate this.  For example,
summary(lm(a~w+x+y+z))

will give me the F-statistic and p-value for the whole model, but is it possible to extract the F-statistic and p-value for just the terms y and z?
A faster way of doign something like this:
matrixOfResponses <- cbind(c(1,2,3,4,5), c(4,3,2,4,5), c(5,3,2,23,4), c(1,2,4,3,1,))
pValsOut <- numeric()
for(i in 1:ncol(matrixOfResponses))
{
pValsOut[i] <- anova(lm(matrixOfResponses[,i]~mMat), lm(matrixOfResponses[,i]~mMatReduced))$'Pr(>F)'[2]
}

So basically something like the above becomes very slow when "matrixOfRespones" contains a huge number of variables, for example a huge number of gene expression levels.
Comment: Welcome to the site, @ScanSally. This appears to be *only* a question about how to get R to do this for you. If that's true, this Q would be off-topic for CV (see our [FAQ](http://stats.stackexchange.com/faq)), but on-topic for [Stack Overflow](http://stackoverflow.com/). Are you also interested in understanding (eg) the use of the F-test as a simultaneous test to assess multiple variables, or some other substantive statistical issue? If so, please edit to verify, if not, flag your Q & we'll migrate it for you (*please don't cross-post, though*).
Comment: It was more a general stats question, so I'll edit the question!
Comment: The updated portion of the question really is just a programming question. The answer is probably *vectorization*. You might want to start by looking here: [vectorize-my-thinking-vector-operations-in-r](http://stackoverflow.com/questions/445059/).
Answer: I suspect what you are interested in is testing both $y$ and $z$ simultaneously.  (NB, if not, @jebyrnes' answer addresses your question.)  To do this, you fit two models and assess them with a nested model test (often called "$F$ change test", or "$R^2$ change test"):
fullMod    = lm(a~w+x+y+z)
reducedMod = lm(a~w+x)
anova(fullMod, reducedMod)

For more conceptual understanding, my answer here Testing for moderation with continuous vs categorical moderators talks about the $F$ change test (albeit in a different context).
Comment: Great this is exactly what I was looking for. Thanks!!
Comment: That's great, @ScanSally. If you want to know more, I recommend reading my other answer, a lot of it is about testing multiple parameters when they are indicator variables used in an interaction, but the principle is the same.
Comment: This may be a long shot, but is there any chance its possible to do something like the above for a large number of response variables. I.e. "a" is a matrix of ~50,000 different response variables, so fullMod and reducedMod will be objects of the class c("mlm" "lm"). It seems really slow to do this using a for loop, but maybe there is a much faster way that I just don't know about?
Comment: In theory, it's certainly possible to test a nested model w/ just a few variables against a full model w/ 50k variables. I don't know anything about what performance issues that might exist there in practice though. If you are asking about the possibility of scrolling through large numbers of variables to find out which are 'the right ones', you should read my answer here: [algorithms-for-automatic-model-selection](http://stats.stackexchange.com/questions/20836//20856#20856).
Comment: Thanks for the answer, but I think I mean something a little different! I'm not trying to do variable selection, just save the trouble of having to do a for loop to compare fullMod and reducedMod for different "a" (i.e. different response variables) above.
Comment: Sorry, I misread your question. I gather you want to compare a model w/ multiple **response** variables to a model w/ just 1. I don't think that would be valid, but it's an interesting question.
Comment: No not really, I just want a faster way of doing something like this: Oh wait I can put code here, hang on I'll write it above in the main text.
Answer: That summary is in and of itself an object.  So,
tab <- summary(lm(a~w+x+y+z))
tab$coefficients

Will give you the coefficient table.  It's just a matrix.  You can then extract the appropriate entries from there.  anova and Anova would similarly.


What size in Pixels should my images be for ldpi, mdpi, ldpi, and xhdpi?

Question: In my app I want to have a Screen in which the background is an image. That image will be stored in drawable, and I'm aware that I'll need to store versions of the same image but different sizes in the other drawable folders in order to support varying screen sizes/densities.
I found this information:
ldpi: Low-density screens; approximately 120dpi.
mdpi: Medium-density (on traditional HVGA) screens; approximately 160dpi.
hdpi: High-density screens; approximately 240dpi.
xhdpi: Extra high-density screens; approximately 320dpi. Added in API Level 8

My question though, is how do I know what size my image should be for each respective folder in pixels? The screen in which this image will be the background can only be viewed in portrait mode, so I'm wondering about sizes in respect to portrait layout.
Comment: This has been answered here: [http://stackoverflow.com/questions/12768128/android-launcher-icon-size][1]

  [1]: http://stackoverflow.com/questions/12768128/android-launcher-icon-size
Comment: You cannot have a "full-screen background image" in general, any more than you can have one in a Web browser. Device screens, like browser windows, can have arbitrary resolutions. You will first need to determine your strategy for dealing with that (e.g., layer a background image on top of a solid full-screen background, with the image designed to blend into that background). Then you will need to factor in screen density.
Comment: There's no practical need for ldpi assets anymore, but in any case, the proportions to use for scaling your assets is as follows -- ldpi : mdpi : hdpi : xhdpi : xxhdpi : xxxhdpi :: 3 : 4 : 6 : 8 : 12 : 16
Comment: And the scale factor is as follows: ldpi, mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi => 0.75, 1.0, 1.5, 2.0, 3.0, 4.0
Comment: @Ankhwatcher, that is talking about launch icons, would it be the same for full-screen background images? I assume yes.
Comment: @Karakuri: 9.1% of Android devices are `-ldpi` as of [the current Android device dashboard](https://developer.android.com/about/dashboards/index.html). Depending upon your distribution channels, that may understate how many `-ldpi` devices there are, as some low-end devices skip the Play Store and therefore will not show up in Google's dashboard. Now, it may be that scaling from `-mdpi` will suffice in many cases, particularly for smaller artwork. I just don't want readers to think that `-ldpi` devices do not exist.
Comment: Use this http://android-ui-utils.googlecode.com/hg/asset-studio/dist/icons-launcher.html#foreground.space.trim=1&foreground.space.pad=0&foreColor=33b5e5%2C0&crop=0&backgroundShape=bevel&backColor=ffffff%2C100
Answer: Sorry User, I didn't read your whole question the first time.
If you're setting a background you can use a large image and create a scaled bitmap from it.
You'll want to use a method to measure the screen size to determine what you should scale your bitmap down to.
for example:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
metrics.heightPixels;
metrics.widthPixels;

Then scale the bitmap:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.welcome_background);
int nh = (int) (bm.getHeight() * (512.0 / bm.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bm, 512, nh, true);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), scaled);
welcomeScreen.setBackgroundDrawable(bitmapDrawable);

(This code doesn't scale to display size it just scales to a width of 512 px, but it should serve as an example)


How to add/copy VSAs (Vendor-Specific attributes) to outer channel of EAP reply in FreeRADIUS C module

Question: I am adding VSAs programmatically to Access-Accept reply in my FreeRADIUS C module (More details here).
For debugging/troubleshooting purpose, I need a way to visually inspect the VSAs on the receiving end. The issue is that my clients are using inner tunnel protocols (PEAP and TTLS) over EAP outer channel, and the traffic sniffer tools, such as WireShark, show only outer channel data.
I understand there is a way to copy the attributes to the outer channel for this purpose but was unable to find the instructions or samples on how to do this.
UPDATE: This is to address Arran's answer below. While I'm sure that Arran is right in saying that unlang is the preferred method, it is not applicable to my situation - the set of VSAs I need to send to NAS in my reply is defined outside of FreeRADIUS server, and is passed on to the C module at run time based on the user being authenticated. This is why I'm looking for a way to do this programmatically.
Answer: I wouldn't recommend doing this programatically within your module, unless for some reason it can only over be called within the inner-tunnel server.  Instead, you should place your attributes in the request or reply list of the inner tunnel request and then copy them to the outer request using unlang.
The easiest way to copy attributes from the inner to outer tunnels is using the outer.session-state list.  This list persists throughout the multiple Access-Request/Access-Challenge rounds of an EAP authentication attempt.
If you want to return attributes in the final Access-Accept, place them in the outer.session-state list using the unlang update keyword from within the inner-tunnel virtual server.
In the outer virtual server in the Post-Auth section, copy the attributes from the outer request's session-state list over to the reply list. This will ensure your VSAs are only sent in the final Access-Accept/Access-Reject and not in any of the intermediary Access-Challenge packets.
The inner virtual server:
server inner {
    post-auth {
        <your_custom_module>
        update outer.session-state {
            <custom attribute> := &reply:<custom attribute>
        }
    }
}

The outer virtual server:
server {
    post-auth {
        update reply {
            <custom attribute> := &session-state:<custom attribute>
        }
    }
}

UPDATE - If you don't know which attributes you'll be returning in advance you can do a whole list copy.
server inner {
    post-auth {
        <your_custom_module>
        update {
            &outer.session-state: += &reply:[*]
        }
    }
}

Comment: Updated with an example of copying the entire list.  You should be able to work out what to do in the outer server.
Comment: It just means all instances of.  It may be redundant if a straight list to list copy works ok.
Comment: Arran, i appreciate your detailed answer. Unfortunately, it does not solve my issue. Please see the update, above
Comment: Thank you Arran, I finally have it working. What is the meaning of `[*]`? The reason I ask is because post-auth section of inner-tunnel already has this line:
`&outer.session-state: += &reply:`
Is this documented anywhere?


Sphinx 4 configuration VoxForge

Question: I was able to walk through Sphinx4 tutorials, but now I need to integrate Voxforge with it and I can't find any tutorials or blogposts on that matter!
Answer: Hope this helps

Official documentation for integrating VoxForge into Sphinx 4
How to Use Models from SphinxTrain in Sphinx-4

Also See
Creating Sphinx Acoustic Models
Use VoxForges Sphinx acoustic model with Sphinx4?
Sphinx3 model to Sphinx4 model

Sphinx 4 configuration VoxForge