What's the difference of $xRy=1$ on $\mathbb {Z}$ or $\mathbb {R}$?

Question: Suppose we define the relation xRy iff xy=1, is this relation:
Reflexive?
Irreflexive?
Symmetric?
Antisymmtric?
Transitive?
From my understanding on Z (integers), the relation is symmetric and transitive.
Symmetric: if xy=1 then yx=1 is true
Transitive: if xy=1 then yz=1, so xz=1
Neither Reflexive or irreflexive: xx=1 iff x=1, so there is at least one instance, not all instances, where xRx, so it's neither (if I am applying this correctly - it's reflexive if xx=1 for all x, and irreflexive if xx!=1 for all x)
However, what's the difference between asking if this is on the Real (R) set or the integer set (Z)?  Are they the same?
Comment: You can use [MathJax](https://goo.gl/OWv9nr) to format your posts.
Answer: There's a big difference between doing this for real numbers vs integers. For one thing, in the integers $xRy\Rightarrow x=y$,  which isn't true for te real numbers. We have $2R0.5$, $0.5R2$, but not $2R2$ so for the reals it is not transitive.
You have the right answers but the wrong analysis for the integers. In addition to $1R1$ there is also $-1R-1$
Comment: Ah, I see.  Thank you for that.  Is my application of the integers correct though?
Comment: @Slurpee I've edited my answer
Answer: Of course not. When you extend the set, you could never be guaranteed to keep the property of a relation. It's possible to keep the property only when the extension is somewhat natural and compatible with the property by which you defined the relation.
In this case, when you consider in $R$, the transitivity is broken, (you can easily notice that.)
Answer: Reflexive: Fails in both Integers and Reals.
Symmetic: Passes in both Integers and Reals.
Transitive: Passes in Integers but fails in Reals.
We can write the relation as $R_A=\{(x,x^{-1}): x\in A\}$ where $A$ is either $\Bbb Z$ or $\Bbb R$.   As you noticed, when under the Integers, the relation is $R_{\Bbb Z}=\{(1,1),(-1,-1)\}$ as only $1$ and $-1$ have multiplicative inverse (which are themselves) and this trivially transitive.   However, in the Reals there are many more entries in $R_\Bbb R$, which preserves symmetry but breaks transitivity [because if $xy=1\wedge yz=1$ then $x=z$, but $xx=1$ only if $x=\pm 1$].


Preciso retornar este JSON com Laravel eloquent

Question: Meu Json:
<code>{
   "data":[
      {
         "data":{
            "name":"Documents",
            "size":"75kb",
            "type":"Folder"
         },
         "children":[
            {
               "data":{
                  "name":"Work",
                  "size":"55kb",
                  "type":"Folder"
               },
               "children":[
                  {
                     "data":{
                        "name":"Expenses.doc",
                        "size":"30kb",
                        "type":"Document"
                     }
                  },
                  {
                     "data":{
                        "name":"Resume.doc",
                        "size":"25kb",
                        "type":"Resume"
                     }
                  }
               ]
            },
            {
               "data":{
                  "name":"Home",
                  "size":"20kb",
                  "type":"Folder"
               },
               "children":[
                  {
                     "data":{
                        "name":"Invoices",
                        "size":"20kb",
                        "type":"Text"
                     }
                  }
               ]
            }
         ]
      },
      {
         "data":{
            "name":"Pictures",
            "size":"150kb",
            "type":"Folder"
         },
         "children":[
            {
               "data":{
                  "name":"barcelona.jpg",
                  "size":"90kb",
                  "type":"Picture"
               }
            },
            {
               "data":{
                  "name":"primeui.png",
                  "size":"30kb",
                  "type":"Picture"
               }
            },
            {
               "data":{
                  "name":"optimus.jpg",
                  "size":"30kb",
                  "type":"Picture"
               }
            }
         ]
      }
   ]
}
</code>
Comment: Se poderia ter explicado da onde e como? por exemplo os models que poderiam gerar esse layout já é um bom começo... realmente pergunta não clara!
Answer: Oi,
Na sua controle pode retornar usando o response.
Exemplo:
<code>$dados = new MinhaModel();
return response()->json($dados->get())
</code>
Estou implicando que você já tenha models, esteja usando o Eloquent e está tudo referenciado corretamente em sua controller.
Espero ter ajudado.


creating dataTables from pug mixin with DOM datasource keeps saying "No data available in table"

Question: I made a jade mixin to create a table from values I'm passing from node. I am instantiating dataTables at document ready but I keep getting "No data available in table"
I have a feeling that there is a race condition between the two that is leading to the issue.
here is pug
<code>            table#brandPageTable.table.table-bordered.table-hover(name="Brands")
          thead
            tr
              th Company Name
              th Industry
              th Contact Name
              th Contact email
              th Contact Phone Number
          tbody
          mixin liveCampaigns(brandID,name,type,contactName,contactEmail,contactPhoneNumber)
            tr.clickable-row(data-url='/superUser/brands/'+brandID)
              td=name
              td=type
              td=contactName
              td=contactPhoneNumber

          for brand in brands
            +liveCampaigns(brand.id,brand.clientName,brand.businessType,brand.contactFirstName,brand.contactEmail,brand.contactPhoneNumber)
</code>
and here is the js
<code>  document.addEventListener("DOMContentLoaded", function(event) {
    $('#BrandsTable').DataTable();
  });
</code>
Comment: Questions must include a minimum viable example of your code and a description of what you've tried.
Answer: For anyone that runs into this problem the issue was the tbody tag. For whatever reason the pug was creating two tbody tags and the dataTable would take the first body which always happened to be empty


Transformations for Logistic Regression Predictors

Question: I was curious about what types of transformations (if any) are used on predictors for logistic regression.
Linear regression transformations seem fairly straightforward; scatter and density plots can help identify if logging the predictors or using a polynomial is necessary. I haven't read too much on similar types of predictor transformations for logistic models. I was just curious if there are common transformations and, if so, how are they identified (graph, etc.)?
Comment: Normality assumptions for logistic regression models aren't the same as in for linear regression models; homogeneity in the residuals' variance assumption doesn't apply in logistic regression.
Answer: It is more challenging to detect non-linear effects in logistic regression as opposed to linear regression, but some possible answers are to plot the predictors vs the deviance residuals or pearson residuals.
Or, look at sample proportions in categories defined by the predicted values (analogous to the hosmer lemeshow chi square). If there is major lack of fit there, that could indicate non-linear predictor effects. Then, try polynomial terms (or general non-linear regression approaches) and see if that improves the agreement between predicted and observed proportions.
Comment: thats what i meant by non-linear regression approaches.
Comment: It already contains that detail!! Maybe you should post a better answer if you prefer!!!
Comment: Try with splines!
Comment: Then maybe you could extend your answer to include this details!


Resultado calculo automático javascript asp.net mvc

Question: Consegui efetuar a soma de dois campos usando Java Script, mas o resultado só exibido ao clicar no campo resultado, gostaria de exibir o resultado automaticamente, sem precisar clicar em nada.
Javascript


Decimal expansion of $x\in [0,1]$

Question: This is an exercise from Royden Real Analysis:
Let $p$ be a natural number greater than 1, and $x$ a real number, $0 \leq x \leq 1$. Show that there is a sequence $\{a_n\}$ of integers with $0 \leq a_n < p$ for each $n$ such that $$ x = \sum_{n=1}^\infty \dfrac{a_n}{p^n}$$ and that this sequence is unique except when $x$ is of the form $q/p^n$, in which case there are exactly two such sequences. Show that, conversely, if $\{a_n\}$ is any sequence of integers with $0\leq a_n<p$ the series above converges to a real number $x$ with $0\leq x \leq 1$.
MY ATTEMPT:
Any number $x\in [0,1]$ can be written out in its decimal form as $x=0.d_1d_2d_3\ldots$ where $d_i$ are integers between $0$ and $9$. So we have $$x = \sum_{n=1}^\infty \dfrac{d_n}{10^n} = \sum_{n=1}^\infty \dfrac{\tfrac{p^n}{10^n}d_n}{p^n} =  \sum_{n=1}^\infty \dfrac{a_n}{p^n}$$ However its not readily apparent to me that this construction guarentees $a_n<p$. Furthermore I am a bit stuck on showing this is unique unless $x=q/p^n$.
ATTEMPT 2:
(Forward)
Let $a_n = (xp^n\mod{p})$. Since for any $y\in\mathbb{R}$, $(y\mod p) \in \left\{0,\ldots,p-1\right\}$ we have $0\leq a_n < p$. Let $x_N$ be the partial sum $$x_N =  \sum_{n=1}^N \dfrac{a_n}{p^n}$$ We want to show that $\lim_{n\to\infty}x-x_N=0$. (need to show that) $$x-x_N = r_N < \dfrac{1}{p^N}$$ and so $$\lim_{N\to\infty} x-x_N = \lim_{N\to\infty} \dfrac{1}{p^N}=0$$
(Backward)
Comment: Just wanted to point out that you are assuming that a decimal expansion exists; you should not assume this (this is part of the exercise).
Comment: A solution can be found here: https://math.stackexchange.com/questions/2417982/expansions-of-a-real-number-x
Answer: Hints: Think about how decimal expansions are obtained. Start with $x\in[0,1]$, multiply it by 10. The integer part of the result yields the first decimal digit $d_1$. Take the fractional part of the result and apply the above algorithm to it (multiplying by 10, taking the integer part of the result) to get the second decimal digit $d_2$, and so on. You show that this expansion $0.d_1d_2d_3\ldots$ converges to $x$ by arguing that the difference between $x$ and the partially obtained expansion goes to zero.
For your problem you are looking for the base $p$ expansion, so you should be multiplying $x$ by $p$ (instead of 10) to obtain $a_1$, and so on.
To study uniqueness, you can adapt the argument in this article: Characterization of non-unique decimal expansions
The "conversely" part is easy because you are proving that an infinite series converges to something in $[0,1]$. Compare the tail of the infinite series to a geometric series to show that the tail goes to zero.

Decimal expansion of $x\in [0,1]$


How to check if functions of i.i.d random variables are dependent or independent?

Question: i'm new to this forum and the science of statistic.This is my question:
Let's say that we have two i.i.d random variables X and Y, which both follow a Rayleigh distribution. Then, we define two new random variables U and V as follows: $U = \frac{X^{2}}{Y^{2}+a}, V = \frac{Y^{2}}{X^{2}+a}, $ where $a$ is a constant. Are $U$ and $V$ are independent or dependent?
Intuitively speaking, i believe that the two are dependent, as i can write $X^{2} = U(Y^{2}+a)$ and substitute this into $V$ to get $V=\frac{Y^{2}}{U(Y^{2}+a)+a}$. But another man told me that they are independent since they are created independently from the same distribution. So i'm pretty confuse right now.
Comment: For the special case $a = 0$, $U = \frac{X^2}{Y^2}$ and $V = \frac{Y^2}{X^2}$ are _reciprocals_ of each other, and so are very definitely dependent random variables. More generally, your "another man" might have been thinking of the notion that $g(X)$ and $h(Y)$ are independent whenever $X$ and $Y$ are independent, but that is not the case here. It _might_ be that $U$ and $V$ can be _proven_ to be independent when $a\neq 0$, but I very much doubt it.
Comment: If $X$ and $Y$ are iid Rayleigh,then $X^2$ and $Y^2$ are iid _exponential_ random variables. This might help in figuring the joint density of $U$ and $V$.
Answer: Independence of random variables $U$ and $V$ implies the distribution of $U$ is the same regardless of what value $V$ might have.
In some cases, checking independence requires working out the joint distribution of $(U,V)$.  But if you suspect there might be lack of independence, it suffices to find enough values of $V$ for which the conditional distribution of $U$ differs.
("Enough" means there has to be nonzero probability of achieving values of $V$ where the conditional distribution of $U$ varies.)
In this case, algebra tells us that
$$Y^2 = V(X^2 + a),$$
whence
$$\frac{1}{U} = \frac{Y^2+a}{X^2} = \frac{V(X^2+a)+a}{X^2} = V + a \frac{V+1}{X^2}.\tag{1}$$
With the Rayleigh distribution, $X^2$ has positive probability density for all $X^2 \gt 0.$  As $X^2$ ranges through all positive numbers, the right hand side of $(1)$ ranges over the interval $(V, \infty)$ when $a(V+1)\gt 0$, over the interval $(-\infty,V)$ when $a(V+1) \lt 0$, and otherwise is fixed at $V$. This immediately implies that the range of values of $U$ that have some chance of happening depends on $V$, and that we cannot get rid of this problem by eliminating a set of $V$ having just zero probability.
Because the ranges of possible $U$ differs with $V$, the conditional probability distribution of $U$ obviously varies with $V$, too.  Therefore $U$ and $V$ are not independent.

The "other man" can be confuted by considering a simplified version of his assertion where there is just one variable, say $X$.  We may "independently" construct many random variables from $X$, such as $U=2X$ and $V=4X$, but I hope it's obvious the resulting variables are not themselves independent.  In this example, for instance, $V=2U$ exhibits the dependence explicitly.  The same argument applies to multivariate random variables and for the same reasons.
Finally, there are some special cases where sets of variables constructed from the same "core" of independent variables are independent. The best-known (and arguably most important) example consists of an orthogonal transformation of independent and identically distributed Normal variables: the resulting variables are still independent and identically distributed.


How to use a string with backslashes in Python

Question: I want to maintain a variable with a string which contains backslashes and don't want to alter that. When I try to use the string, it gets extra backslashes as escape characters. I tried with 'r' ( raw ) modifier - but it didn't help.
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = r'\abc'
>>> s
'\\abc'

I have a test where I am trying to have an array of possible values with ''. But when I take them out, it doesn't come as expected:
>>> value =  [r'"\1"', r'"\\1"', r'"\\\1"' ]
>>> for val in value:
...   print value
...
['"\\1"', '"\\\\1"', '"\\\\\\1"']
['"\\1"', '"\\\\1"', '"\\\\\\1"']
['"\\1"', '"\\\\1"', '"\\\\\\1"']

How do I do this?

I saw questions regarding the problem with backslash related issues in Python. But I couldn't get a specific answer for the problem that I am hitting.
Comment: Console outputs repr(s). Thus you get extra `\\`.
Answer: Your string is not altered. Use the print statement to print the actual variable contents.
In the second example, you just print the whole list, not the items present inside the list.
>>> s = r'\abc'
>>> print s
\abc
>>> value =  [r'"\1"', r'"\\1"', r'"\\\1"' ]
>>> for val in value:
        print val

"\1"
"\\1"
"\\\1"

Answer: You are printing the representation of the strings as if they were normal strings, which they are not.
When you use raw string literals, then print the string. Any escape character like \ is itself escaped in the representation, leading to a multiplication of \ symbols. Your strings are fine.
Comment: @Joel, I'm not sure if you're able to yet, but higher-rep users can click on the score of a question or answer and see the number of votes in each direction. Both of the answers to this question got **2** downvotes within a minute or two of being posted. Somebody and their sock puppet was not feeling charitable...
Answer: IDK if this helps your specific problem, but if r\ isn't working, you can always put two backslashes to force python to interpret it literally. Instead of "r\abc", use "\abc". I had to do this for one of my class tests as well, and it helped me a lot to use \ because it works reliably, whereas r\ has some parameters to keep in mind.


Kiselev's geometry ex 7,8

Question: I need some help on two exercises from Kiselev's geometry, about straight lines.

Ex 7: Use a straightedge to draw a line passing through two points given on a sheet of paper. Figure out how to check that the line is really straight. Hint: Flip the straightedge upside down.

I would draw the first line, then flip the straightedge and draw the second line over the first. The two lines should coincide nicely iff the straightedge is straight. Because, this shows that there is no "unevenness" or "bumps" on the edge of the straightedge. There would be gaps between the two lines if there are "unevenness/bumps" on the edge of the straightedge.

Ex 8: Fold a sheet of paper and, using ex 7, check that the edge is straight. Can you explain why the edge of a folded paper is straight?

Ex 8 is marked as more difficult by the author. I'm completely clueless about this exercise.
Please provide insights and help me with these two exercises. I'd appreciate if they are more of an "experimental approach" than theoretical because exercises 7 and 8 are arranged in between the introduction and first chapter of the book.
Thank you. :)
Comment: If I am understanding you correctly, your answer to Ex. 7 is good. For Ex. 8, here is a hint: note that when you fold the paper, but have the two sides of the fold laid out flat, that flatness requires that the distance between any two points on the same side of the fold (including on the fold itself) to be unchanged by the folding.
Comment: Suppose that you have three points on the fold that are not colinear. Choose a point $A$ not on the fold, and its counterpart $A'$ on the other side (the one it folds on top of). Show that the distances from $A$ to the three fold points and from $A'$ to the three fold points cannot both be the same as before the fold.
Answer: While these questions are handwavy and cannot be precisely answered, I think that the author is looking for something like the following for exercise 8:

When you fold the paper, you can do it in two ways, corresponding to which side you fold across the line. Notice that the results of these two ways are reflections of one another across the line. But the line is the same no matter which side you fold across it, so by exercise 7 the line is straight.

Now, I want to emphasize again that this is nowhere near a mathematical proof, but it is indeed interesting to think about it this way, as it shows that there are some inherent properties that we assume about our ambient space whenever we perform operations (typically rigid motions) within it.
Comment: Right, the two ways of folding the paper don't move the fold and they are akin to flipping a straightedge upside down.
Answer: I'm late to the game but here is my argument for #8. (Incidentally, I don't think Kiselev is suggesting to use #7 to prove #8. He says use the technique to check that the line is straight, and, separately, asks us to explain why it is true.)
When we fold the paper, we identify each point on the bottom 'half' with a unique point on the top 'half'.  (You may imagine the paper to expand as much as necessary to make this a reality!  Or, you can imagine we are folding a plane.)
Lay the paper on top of a plane and fold the paper.  The edge creates a curve in the plane.  Our goal is to convince ourselves that this curve is straight.
Unfold the paper.  Now the paper has a crease, which of course is the same curve as the edge.  The crease divides the paper into two halves — call them 'left' and 'right'.
Now, imagine any two points on this crease, and further imagine them connected by some curve which does not lie on the crease — say, a curve in either the left or right half of the paper.  What can we say about such a curve?
A curve like this cannot be straight.  The reason is, folding the paper would give us a congruent but different curve on the other side of the page, and we cannot have two different straight curves connecting a pair of points.
So we have shown that if two points on the crease are connected by a curve which travels off the crease, that curve is not straight.  But we know that any two points are connected by a straight line, and hence that straight line lies on the crease.  Applying this argument to the endpoints of the curve, we see that the whole crease/edge itself is straight.
Obviously I've left off some details and assumptions (for example, a line congruent to a straight line is straight, etc) but I think I've managed to find the thrust of a good argument.
It's a wonderful problem that I've thought about for years.

Kiselev's geometry ex 7,8


Understanding Polig-Hellman algorithm for DLP via example

Question: I am trying to follow the working of an example of stated algorithm on following link (http://www-math.ucdenver.edu/~wcherowi/courses/m5410/phexam.html).
Let the prime $p = 8101$, and a generator of $Z_{8101}$ be $a = 6$. Find $x$ so that $a^x = 7531 \mod 8101$.
The author states that $c_0,c_1$ can be either $0$ or $1$ and "$7531^{\frac{(p-1)}{2}}= 7531^{4050}= -1$ and as this $= a^{c_0\frac{(p-1)}{2}}$, we have $c_0 = 1$".
However I have calculated $6^{4500} \mod 8101$ as $4334$ which is not congruent to $-1$.
My calculations $\mod 8101$ are as follows;
$$6^3=214$$
$$6^5=-397$$
$$6^{10}=3690$$
$$6^{100}=2117$$
$$6^{1000}=1085$$
$$6^{4500}=4334$$
Where am I going wrong? Am I misunderstanding their working?
Comment: You need $6^{\color{red}{4050}}$ rather than $6^{4500}$.
Answer: Corrections to calculations $\mod 8101$ below;
$$6^3=216$$
$$6^5=7776$$
$$6^{10}=312$$
$$6^{100}=-44$$
$$6^{1000}=3446$$
$$6^{4050}=-1$$


Node.js/Express post route failing

Question: Trying out Node.js for the first time. My POST route is failing with "Cannot POST /admin/add-product.html". GET request is being served fine from the same route.  I have had a look around here. Several answers to similar issues but nothing is helping. Here is my code:
./index.js
const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

const adminRoutes = require('./src/routes/admin');
const shopRoutes = require('./src/routes/shop');

app.use(bodyParser.urlencoded({ extended: false }));

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.listen(3000);`

./src/routes/admin.js
const path = require('path');

const express = require('express');

const router = express.Router();

// served on /admin/add-product GET route
router.get('/add-product', (req, res, next) => {
  res.sendFile(path.join(__dirname, '../', 'views', 'add-product.html'));
});

// served on /admin/add-product POST route
router.post('/add-product', (req, res, next) => {
  console.log(req.body);
  res.redirect('/');
  // res.send('
product saved
');
});

module.exports = router;

./src/views/add-product.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Add Product</title>

Shop

Add Product

      <form action="/admin/add-product.html" method="POST">
        <input type="text" name="title" /><button type="submit">
          Add Product
        </button>
      </form>

Thank you!!!
Comment: Can you try `` ?
Comment: To add to the comment, your POST route does not have `.html`, so you have to remove the `.html` from your form's action attribute.
Comment: Thanks Đăng Khoa Đinh. It fixed it! :)

I am happy to mark it as a correct answer if you post it as an answer.
Comment: @ImranAli glad to be of help, I added my answer :)
Answer: The action in the form need to match the route declare in the NodeJS application, it should be :
<form action="/admin/add-product" method="POST">

Answer: Remove the .HTML from the action attribute of the form.

Node.js/Express post route failing


Disable "Saving Snapshot" in NetBeans

Question: How can I disable saving snapshot in NetBeans 7.1.2? It is slowing down the system dramatically. Any suggestions
Answer: The snapshots are performance snapshots taken when the IDE detects slow behavior. For obvious reasons, slower computers are more likely to trigger the collection (by taking longer than a preset amount of time to complete tasks), which then requires saving the snapshot. The saving process slows the system down even more, occasionally resulting in (for all practical purposes) an inoperable IDE.
Check your netbeans.conf configuration file (in the etc folder). You'll find a line for netbeans_default_options. Make sure -J-ea does not appear in the line. This flag enabled Java assertions, which wouldn't be a problem in itself but the slowness detector in NetBeans also uses this flag to significantly shorten the timeout before the self-profiler is enabled.
Answer: Sam Harnell's answer didn't help me in 2019 and NetBeans 10, because i didn't had the option -J-ea. I found help in the NetBeans bugtracker .
Adding the below options to netbeans_default_options helped me to get rid of the saving snapshots:
-J-Dorg.netbeans.core.TimeableEventQueue.report=30000
-J-Dorg.netbeans.core.TimeableEventQueue.quantum=1000
-J-Dorg.netbeans.modules.editor.completion.slowness.report=10000

Comment: On my Netbeans 11, -J-ea was also missing. So your answer saved a lot of unresponsive time!

Disable "Saving Snapshot" in NetBeans


Benchmark datasets for detecting clusters, patterns and formulate/validate hypothesis?

Question:
Possible Duplicate:
Locating freely available data samples
Sites for predictive modeling competitions

Are there sites or sources of "datasets" (either artificially created or taken from actual experiments/sources) someone can use to test their own abilities in detecting clusters, patterns, and to formulate/validate hypothesis?
Possibly with answers, that could be consulted, later to determine what you got and what the expected results/techniques should have been?
Comment: You may be interested in this question: [locating-freely-available-data-samples](http://stats.stackexchange.com/questions/7/), or this: [tiny-real-datasets-for-giving-examples-in-class](http://stats.stackexchange.com/questions/5937/), or just search under the [tag:dataset] tag.
Comment: Thanks to both. I have zero skills in the field (but I'd like to get better thanks to books and coursera-style courses) so I am mostly interested in practical "exercises", than in competitions. So the first comment is closer to what I am looking for, but thanks (and upvotes) to both of you ;)
Answer: Kaggle hosts a variety of data mining competitions.  In addition to their active competitions, they have archives of past competitions.  Not only can you compare your results with the correct answers, but you can also compare your results to the winners of those past contests.  I'm not sure if the scope is appropriate for what you are after though...these probably require a bit more effort than a typical "quiz" would.
Answer: There is a free introductory textbook at openintro that also has sample datasets and a library of homework/quiz questions.  That would be a place to start.  I don't know if it will get into as advanced topics as what you want.


Error: Invalid cache option true found. Expected "memory"

Question: this error shows in cmd using rhc tail socialinteractive
i hosted this site to openshfit i use swig and modules consolidate and swing for  template
guide me to slove this error
<code>Error: Invalid cache option true found. Expected "memory" or { get: function (ke
    y) { ... }, set: function (key, value) { ... } }.
        at validateOptions (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/run
    time/repo/node_modules/swig/lib/swig.js:113:15)
        at parse (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/
    node_modules/swig/lib/swig.js:339:5)
        at Object.precompile (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/r
    untime/repo/node_modules/swig/lib/swig.js:486:23)
        at Object.compile (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runt
    ime/repo/node_modules/swig/lib/swig.js:606:16)
        at Function.exports.swig.render (/var/lib/openshift/5453580c500446bfbc000d3c
    /app-root/runtime/repo/node_modules/consolidate/lib/consolidate.js:246:56)
        at /var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/node_mo
    dules/consolidate/lib/consolidate.js:146:25
        at read (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/n
    ode_modules/consolidate/lib/consolidate.js:91:22)
        at /var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/node_mo
    dules/consolidate/lib/consolidate.js:144:9
        at readPartials (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtim
    e/repo/node_modules/consolidate/lib/consolidate.js:114:33)
        at View.engine (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime
    /repo/node_modules/consolidate/lib/consolidate.js:139:5)
    GET / 500 4.312 ms - -
</code>
Answer: This is consolidate.js bug, not OpenShift bug.
It has been already addressed upstream, see:
https://github.com/tj/consolidate.js/pull/134

Either you need to update your consolidate.js npm package once they release version greater than 0.10.0.
Or you can use the following workaround (as suggested by @truongminh):

app.locals.cache = "memory"
Comment: If anyone else is using co-views I had to update it to >2.0.0 to get it to work.... and iojs (that I also used) to above 2.
Hope this help


Iterando em um array multidimensional

Question: <?php
$data = array();
//questoes de user 1
$data['rows']['questions'][1] = array(
    array('id' => 1, 'type' => 'radio', 'name' => "Onde fica ilha de Santiago"),
    array('id' => 2, 'type' => 'radio', 'name' => "Onde fica tarafal"),
    array('id' => 3, 'type' => 'boolean', 'name' => "Cidade velha é a capital de Cabo Verde"),

);
$data['rows']['aresponses'][1] = array(
    '1' => array(
        array('id' => 1, 'name' => "No barlavanto"),
        array('id' => 2, 'name' => "No sotavento"),
        array('id' => 3, 'name' => "No norte do arquipélago"),
    ),
    '2' => array(
        array('id' => 1, 'name' => "Na ilha do fogo"),
        array('id' => 2, 'name' => "Na ilha de santiago"),
        array('id' => 3, 'name' => "Na ilha de brava"),
    ),
    '3' => array(
        array('id' => 1, 'name' => "Verdairo"),
        array('id' => 2, 'name' => "Falso"),
    ),

);
?>

Relacionando cada pergunda com uma lista de alternativas de resposta
Exemplo:
>       Pergunta:  Onde fica ilha de Santiago
>
>       Alternativa1:  No barlavanto
>       Alternativa2:  No sotavento
>       Alternativa2   No norte do arquipélago

Comment: Só pegar o ID da [questions] e adicionar após o [aresponses][1][{ID}], assim faz um foreach de cada item.
Answer: Amigo, o índice do array que contem as alternativas precisa iniciar em 0, assim como os índices que contém as perguntas, sendo assim a iteração do array entre as perguntas e respostas, vai ficar desta forma:
$data = array();
//questoes de user 1
$data['rows']['questions'][1] = array(
    array('id' => 1, 'type' => 'radio', 'name' => "Onde fica ilha de Santiago"),
    array('id' => 2, 'type' => 'radio', 'name' => "Onde fica tarafal"),
    array('id' => 3, 'type' => 'boolean', 'name' => "Cidade velha é a capital de Cabo Verde"),

);

$data['rows']['aresponses'][1] = array(
    0 => array(
        array('id' => 1, 'name' => "No barlavanto"),
        array('id' => 2, 'name' => "No sotavento"),
        array('id' => 3, 'name' => "No norte do arquipélago"),
    ),
    1 => array(
        array('id' => 1, 'name' => "Na ilha do fogo"),
        array('id' => 2, 'name' => "Na ilha de santiago"),
        array('id' => 3, 'name' => "Na ilha de brava"),
    ),
    2 => array(
        array('id' => 1, 'name' => "Verdairo"),
        array('id' => 2, 'name' => "Falso"),
    ),

);

$questoes      =  $data['rows']['questions'][1];

$alternativas  =  $data['rows']['aresponses'][1];

foreach ($questoes as $key => $value) {

    echo 'Questao: ' . $value['name'] . '
';

    echo 'Alternativas';

    foreach ($alternativas[$key] as $key2 => $value2 ) {

        echo 'Alternativa: ' . ($key2 + 1) . ' : ' . $value2['name'] . "
";

    }

    echo '

';

}

Para testar o código fora do teu projeto, teste Aqui

Iterando em um array multidimensional


Should a module file look like this?

Question: I've been having problems with one of my Drupal sites and have narrowed the problem down to the Views module. In my Apache error log, I see this:

[Tue Oct 18 09:57:08 2011] [warn] mod_fcgid: stderr: PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ']' in /home/lakedistrict-holidayideas/public_html/sites/all/modules/contrib/views/handlers/views_handler_filter_in_operator.inc on line 206

Looking at the views_handler_filter_in_operator.inc file, I see this on line 206:
<code> $form['value']['#dep
</code>
Does that appear to be a normal line of code? To my untrained eyes, it looks incomplete.
I've reinstalled the module, but the problem remains.
If it appears to be that there's a problem with the module, I'll make a post on the Views issue queue on Drupal.org.
Answer: Since you're using Views module version 2.12, I looked up that file in the repository viewer:
http://drupalcode.org/project/views.git/blob/42fe4029ca7d7410f15933032a17e979bb0957c4:/handlers/views_handler_filter_in_operator.inc
Looks like line 206 should be:
<code>$form['value']['#dependency'] = array($source => $this->operator_values(1));
</code>
I'd try re-downloading the entire Views module. Maybe your copy got corrupted along the way.
Comment: Hi Chris,

Sorry, I should have mentioned that I'm using 6.x-2.12. I understand that this is the latest release (aside from the alpha).
Comment: Sorry for the delay in responding, Chris - I've only just noticed the edit to your original post.

Thanks for the reply - I'll take another shot at reinstalling it.

Should a module file look like this?


Role based menu redirect

Question: Setup:
I have a main module (called public) and several sub-modules that extend the support offered by the public module.
A sub-module (let's call it sub) functions can be accesed only by users with the role that that sub-module creates (guess what, called sub).
Some of the pages defined in public_menu() are extended by the pages defined by sub_menu().
For example, if the public module declares:
$pages["public/asl/info"] = array('page callback'=>'public_asl_info', ...);

the sub module declares:
$pages["sub/asl/info"] = array('page callback'=>'sub_asl_info', ...);

also, consider that sub_asl_info() extend public_asl_info() like this:
function sub_asl_info( $id)
{
    $public_page = public_asl_info( $id);
    $dip_page = sub_asl_dip_info( $id);

    $page = $public_page.$dip_page;

    return $page;
}

there are more complex cases, but this is enough to explain the setup :)
How i solved it (wrongly) so far:
function sub_menu_alter( &$item)
{
    if( !has_role( 'sub'))
        return;

    $item['public/asl/info']        = $item['sub/asl/info'];
    $item["public/operatori/info"] = $item["sub/operatori/info"];
    $item["public/ospiti/info"]     = $item["sub/schedario"];
    $item["public/query"]           = $item["sub/query"];
    $item["public/tassonomia"]  = $item["sub/tassonomia"];
    $item["public/comunicazioni"]   = $item["sub/comunicazioni"];
}

The redirects are hard saved inside the menu_router table, so with more than one user logged it doesn't work.
I came to this solution based on how i solved the same problem but for blocks, however, using _block_view_alter() doesn't hit the same wall.
How do i solve this (programmatically)?
Possibly without using yet-another-module, unless really neccessary.
Answer: The final solution was much easier than i could possibly hope for.
I ended defining my own hooks and allow the sub-modules to implements the changes using said hook,s after checking the role of the user.
Using the example above, it became:
function sub_asl_info_alter( $page, $id)
{
  if( has_role('sub'))
    $page->content .= sub_asl_dip_info( $id);
 }

Role based menu redirect


How do I register a user?

Question: I am using Drupal 7.17 and the Services module 7.3.2.
I set the Services module as in the following screenshots.

I followed the documentation on http://drupal.org/node/1447020.
With FireFox HttpRequester, I tried to register a new user.

I got a 500 error.

Do you have any idea?
Comment: Do you have any required fields in user profile? If yes - you must specify their values in your request.
Answer: apparently , there is a field of that name ... and some node / entity which is trying to get saved automatically. Could you have Profile2 installed ?
Did you try the report on admin/reports/fields ?
If you dont find it there, try the database - finde the table that uses the column ie this way :
<code>SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'field_published_value'
AND TABLE_SCHEMA = 'yourdb'
</code>
i tried on a "default install" and didnt see it :)
Comment: I found it is something to do with Message module, after I disabled Message, it works now. http://drupal.org/node/1807532
Answer: I solved this problem by using resource which has name "entity_user" (mabe it's nesessary activate module "eck").
I use this uri: http://mysyte/myendpoint/entity_user
I use POST method
I use same json parameters as you.
It Works for me.

How do I register a user?


AngularJS nested ng-repeat

Question: I have a html like this :

         Room: {{roomname}}

       {{room.room}}

and my angular controller look like this:
    var room = {"1.2":
                [
                    {room: "1.2.1"},
                    {room: "1.2.2"},
                    {room: "1.2.3"}
                ],
        "1.3": [
            {room: "1.3.1"},
            {room: "1.3.2"},
            {room: "1.3.3"}
        ]};

    var keys = Object.keys(room);

    this.roomname = keys;
    this.rooms = room;

In my second ng repeat, it doesn't work and how can i loop based on roomname, that output from the first ng repeat??
Answer: Your second ng-repeat needs to take the first ng-repeat value instead of directly taking the room name, so your second ng-repeat should look like this:
Code:

         Room: {{key}}

       {{room.room}}

Comment: i was just about to answer this, but his json is not in right formatm this wont work for him
Comment: @bto.rdz: yeah the json is in key, value form so updated the code in the answer
Answer: You can achieve this by slightly reformatting your Json and then using the following code:
The key is to use the value of the first ng-repeat in the second ng-repeat and not trying to reference the first collection.
html:

             Room: {{room.name}}

           {{room.subRoom}}

javascript:
var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.rooms = [ { name : "1.2",
                       subRoom: [
                    "1.2.1","1.2.2","1.2.3"],
                     }, { name: "1.3",
        subRoom: [
            "1.3.1","1.3.2","1.3.3"]}];
}

Fiddle demo: http://jsfiddle.net/0pnam0wj/
Answer: Is this you wanted?
plnkr

         Room: {{roomnamePrefix}}

       {{room.room}}

AngularJS nested ng-repeat


Angular2 test "provide => use value"

Question: I have the following code to invoke angular2
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { AppModule } from "./src/app";
export function runAngular2App(legacyModel: any) {
       platformBrowserDynamic([
           { provide: "legacyModel", useValue: model }
       ]).bootstrapModule(AppModule)
       .then(success => console.log("Ng2 Bootstrap success"))
       .catch(err => console.error(err));
}

And somewhere I am invoking it like in this manner -
    var legacyModel = {}; // some data
    require(["myAngular2App"], function(app) {
       app.runAngular2App(legacyModel); // Input to your APP
    });

header.component.ts
And in my component I use the legacy model -
import { Component, ViewEncapsulation, Inject } from '@angular/core';

@Component({
  selector: 'app-header',
  encapsulation: ViewEncapsulation.Emulated,
  styleUrls: [ './header.less' ],
  templateUrl: './header.html'
})
export class HeaderComponent {
    public eventTitle;

    constructor(@Inject("appModel") private appModel) {
        this.eventTitle = this.appModel.get("eventTitle");
    }
}

Now the problem is when I am testing this component -
header.component.spec.ts

import {} from 'jasmine';

import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';

import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => {

    let comp:    HeaderComponent;
    let fixture: ComponentFixture<HeaderComponent>;
    let de:      DebugElement;
    let el:      HTMLElement;

    // async beforeEach
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ HeaderComponent ]

        })
        .compileComponents();  // compile template and css
    }));

    // synchronous beforeEach
    beforeEach(() => {
        fixture = TestBed.createComponent(HeaderComponent);

        comp = fixture.componentInstance; // HeaderComponent test instance

        de = fixture.debugElement.query(By.css('.title'));
        el = de.nativeElement;
    });

    it('should display event title', () => {
        fixture.detectChanges();
        expect(el.textContent).toContain(comp.eventTitle);
    });

    it('should display a different event title', () => {
        comp.eventTitle = "Angular2 moderator dashboard";
        fixture.detectChanges();
        expect(el.textContent).toContain("Angular2 moderator dashboard");
    });

});

I get the following error -
Error: No provider for appModel! in spec.bundle.ts (line 4110)
Since appModel is not service I am not able to inject it.
How do I inject appModel so my tests can run?
Answer: Behind your implementation question appears to be an architecture question. I see the term "legacy model" -- are you trying to test a new version of a model? Does the component know how to handle both model versions? The Angular service injection pattern is not intended for models, because two different models typically have different interfaces, and thus are ineligible for dependency injection, which requires different implementations to have the same interface.
Depending on the answers to the above questions, I could imagine at least two reasonable paths forward for you:
(1) If you are indeed trying to test two versions of a model, then you should probably forget dependency injection and just use standard imports like:
import { AppModel } from './path/to/appModel';
import { LegacyModel } from './path/to/legacyModel';

Then you can test how the component responds to both model implementations.
(2) If, however, your "models" both really have the same interface, perhaps the single function I can see from your snippets:
get(eventTitle: string)

...then in that case I would introduce a new service here, and have the component invoke the service instead of the model directly. A service is an appropriate level of abstraction when you have multiple implementations, and you can have both a new and a legacy implementation of the service, injected as appropriate for your app or tests (your tests should probably test both implementations until you are ready to retire the legacy version).

Angular2 test "provide => use value"


Django form saving all values to 0 when I change just one

Question: Here is a form question. I am creating a grid of forms populated by model data. This is generated based on code that looks for an "Allocation" record with a user ID that also contains a date inside of a date range. If no "Allocation" record exists a field is generated with a 0. Upon saving any fields that have allocations records should be updated if changed, and any fields that don't have allocation records should create an allocation record if changed.
The problem: When I change a number and press save, all existing allocation records get updated to 0.
What am I doing wrong?
models.py
class Resource(models.Model):
    resource_name = models.CharField(max_length=150)
    weekly_capacity = models.IntegerField()

class Project(models.Model):
    project_name = models.CharField(max_length=150)
    start_date = models.DateField()
    end_date = models.DateField()

class Allocation(models.Model):
    user_id = models.ForeignKey(Resource)
    project_id = models.ForeignKey(Project)
    week = models.DateField(default=timezone.now)
    allocated_hours = models.IntegerField(default=0)
    actual_hours = models.IntegerField(default=0)

project_profile.py
def resource_allocation_by_week(start,end):
    users_on_project = Allocation.objects.filter(project_id=offset)
    users_in_date_range = users_on_project.filter(week__range=[start, end])
    dict_of_user_hours = {}
    for i in users_on_project:
        total_weeks_allo = 0
        for a in Allocation.objects.filter(week__range=[start, end]).filter(user_id=i.user_id):
            total_weeks_allo += a.allocated_hours

        allocated_total = i.user_id.weekly_capacity - total_weeks_allo
        allocated_by_date = users_in_date_range.filter(user_id=i.user_id).values_list('allocated_hours', flat=True)

        if users_in_date_range.filter(user_id=i.user_id).exists():
            Allocation_pk = users_in_date_range.filter(user_id=i.user_id).values_list('id', flat=True)
            f_inst = Allocation.objects.get(pk=Allocation_pk[0])
            allocation_form = edit_resource_allocation(instance = f_inst)
            dict_of_user_hours[i.user_id] = (allocation_form.as_p, allocated_by_date[0], allocated_total)
            if request.method == 'POST':
                allocation_form = edit_resource_allocation(request.POST, instance = f_inst)
                if allocation_form.is_valid():
                    if allocation_form.has_changed():
                        allocation_form.save()

        else:

            non_displayed_form_values = Allocation(
                user_id = i.user_id,
                project_id = i.project_id,
                week = start,
                actual_hours = 0,
                )
            allocation_form_new = edit_resource_allocation(instance=non_displayed_form_values, initial={'allocated_hours' : 0})
            dict_of_user_hours[i.user_id] = (allocation_form_new.as_p, 0, allocated_total)
            if request.method == 'POST':
                allocation_form_new = edit_resource_allocation(request.POST, instance=non_displayed_form_values, initial={'allocated_hours' : 0})
                dict_of_user_hours[i.user_id] = (allocation_form_new.as_p, 0, allocated_total)
                if allocation_form_new.is_valid():
                    if allocation_form_new.has_changed():
                        allocation_form_new.save()

forms.py
class edit_resource_allocation(ModelForm):
    allocated_hours = forms.IntegerField(label='', required=False,)

    class Meta:
        model = Allocation
        exclude = ['user_id', 'project_id', 'week', 'actual_hours']

project_profile.html

    <form method="post">
    {% csrf_token %}
    {% for obj in resource_allocation_grid %}

            {{ obj.0|date:"D m/d/Y" }} - {{ obj.1|date:"D m/d/Y" }}

        {% for i, v in obj.2.items %}

            {{v.0}}

            {{v.2}}

        {% endfor %}

    {% endfor %}
    <input type="submit" value="Save" />

Here is what the end result currently looks like. (Looks good, just doesn't work)
Comment: Please try to supply a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. Use as little code as possible that still produces the same problem.
Comment: Thanks for the feedback @Selcuk I have edited the post and tried to simplify the code the best I can. I also added the related code and reworded the question for clarity.
Comment: If you have multiple forms in the same `` tag, you need to use [`prefix`](https://docs.djangoproject.com/en/1.11/ref/forms/api/#django.forms.Form.prefix). You might find [formsets](https://docs.djangoproject.com/en/1.11/topics/forms/formsets/) useful, although that would probably require more changes to your code.
Comment: @Alasdair, thanks for pointing me in the direction of the prefix. This worked for all fields that have model objects. Still working out how to get a unique prefix for the fields without existing model objects. Tried creating a random iteration variable but that did not seem to work. I'll post the final answer when I get it worked out.
Answer: Needed to work with Prefix inside for the <form> tag. I was able to do this by creating a unique string for each record regardless of if it existed or not.
unique_id = "%s%s" % (start, i.user_id)

Thanks for the help @Alasdair
Note: I tried to use a uuid.uuid4() to generate a unique value, but discovered that each time the variable was called it would generate a new ID. I needed to use this unique ID in several places so this did not solve the issue. Much better to have the prefix tied to data I think.


Custom HTML link is not working

Question: I have used a custom html link More search results   to link to the homepage.
When clicking the link,I am taken to this urlhttp://localhost/homepage instead of the correct one localhost/cars/homepage
What am I doing wrong?
thanks
Comment: this is the html link I created More search results
Comment: I don't understand the problem - If you want it to link to /homepage/cars, why are not using /homepage/cars as the href?
Comment: I want to link to localhost/cars/homepage and it sends me to localhost/homepage .It removes the "car" .My site is localhost/cars
Answer: Your site is installed in the /cars folder, but you're pointing to the root of the server by using the forward slash at the front of your HREF. You should use Drupal's l() function to generate a proper link:
<?php echo l(t('Homepage'), 'homepage'); ?>

Custom HTML link is not working


Adding for loop inside click event

Question: I am having 5 checkboxes,when i click each check box percentage should be increased similarly when i uncheck the checkbox percentage should be decreased.
<code>$(document).ready(function(){
        var arr=['c','f','i','n','s'];
        var n=6;
            $("input").click(function(){
            if(this.checked){
            if($.inArray(this.value,arr)>-1){
                for(var count=1;count<n;count++)
                {

                  var percentage=Math.ceil(count * (100/5));
                  alert('your percentage is' + percentage);
                }
            }else{}}
            });

});
</code>
But it is returning 100% for a single click.What i am doing wrong?
Comment: check the answer provided by me , should work perfectly for you
Comment: show html code also or add plunker
Comment: https://jsfiddle.net/x4bb87L4/
Comment: why are you using checkboxes to do what radios are intended to be used for?
Comment: @charlietfl Nothing i am just practicing examples to learn jquery
Comment: Thanks Guys.Really this stack overflow is helping me to learn more:-)thanks all:-):-)
Answer: You can check updated fiddle jsfiddle.net/x4bb87L4/3/
Code that updated
<code>    $(document).ready(function(){
      var arr=['c','f','i','n','s'];

      $("input").click(function(){
        $(this).siblings('input[type="checkbox"]').not(this).prop('checked', false).next().removeClass("fa-times cross fa-check tick");

        if(this.checked){
            if($.inArray(this.value,arr)>-1){
                $(this).next().addClass("fa-check tick");
            }else{
               $(this).next().addClass("fa-times cross");
            }
        }else{
            $(this).next().removeClass("fa-check times tick cross");
        }

        var correctAnswer=$(".fa-check.tick").length;
        //var wrongAnswer=$(".fa-times.cross").length;
        //var count=correctAnswer-wrongAnswer;
        var count=correctAnswer;
        count=count<0?0:count;
        $('#value').html(count);
        var percentage=Math.ceil(count * (100/5));
        percentage=percentage<0? 0 :percentage;
        $('#percent').html(percentage);

    });
 });
</code>
Comment: yes I have updated fiddle code. Check it https://jsfiddle.net/x4bb87L4/2/
Comment: I have updated logic as per you told. You can check it here http://jsfiddle.net/x4bb87L4/3/
Comment: Have you seen above fiddle? Is it possible to decrease percentage when i click wrong answer?i.e i have to allocate only 20 percent per row .when i click correct answer percentage should be increased when i click wrong answer percentage should be decreased
Comment: I am getting wrong answer:-( i said i need to allocate only 20 percent per row,But it checks all check boxes.Can you please check again?
Comment: Yes let me check it
Answer: According to me this should be done by creating an other array like
<code>var n=0;
  var arrayforselection=[];
        $("input").click(function(){
        if(this.checked){

  if($.inArray(this.value,arrayforselection)<0){
  if($.inArray(this.value,arr)>-1){
  arrayforselection.push(this.value);
  }
  }
  }else{

  if($.inArray(this.value,arrayforselection)>=0){
  if($.inArray(this.value,arr)>-1){
  arrayforselection.indexOf(this.value)
  arrayforselection.splice(arrayforselection.indexOf(this.value),1);
  }
  }
  }
  n=arrayforselection.length;
        if($.inArray(this.value,arr)>-1){
  if(n===0){
             $('#value').html(n)
              var percentage=Math.ceil(n * (100/5));
              $('#percent').html(percentage)

  }
            for(var count=1;count<=n;count++)
            {
              $('#value').html(count)
              var percentage=Math.ceil(count * (100/5));
              $('#percent').html(percentage)
            }
        }else{

  }
        });
</code>
the previous selected Answer will not work in you multiple times check and unchecked the correct answer , it will increase the percentage and will not decrease it . Find the Updated Jsfiddel here
Comment: Ok i will check

Adding for loop inside click event


Is it possible to send/recieve Message via GSM Modem in Java?

Question: Using RXTX library im doing serial communication.I want to do it in swing based application

Write an AT commands to read received SMS in GSM modem
I need to send the messages to mobiles from java application
Is there any Java API which send/receive SMS using RxTx libraries.
Comment: That's not how you use AT+CGMS. Have you read the AT command specification?
Comment: Sorry, I typoed CGMS instead of CMGS in my comment. CMS Error 518 is "invalid parameter". You need the number enclosed in quotes like `AT+CMGS="+91994435474"`
Comment: Im getting **+CMS ERROR: 518** while im trying to communicate through the Hyperterminal"AT
OK
AT+CMGF=1
OK
AT+CMGS=+91994435474
+CMS ERROR: 518"
Comment: Im using AT+CMGS to send a message.It's correct only know
Answer: There is a Java API called smslib.


How to update an Object in play framework?

Question: How do I edit an existing object in the database?  For example, if I have a model like this:
class Topic{title,content,author}, when I edit and save the object I do not want to add the "author" object again.  How do I update my existing object rather than adding a new one?
Comment: If one of the answers you got solved your problem, please accept it by clicking on the check mark.
Comment: i think i didn't make myself clear, another example: my existing object is Topic(id:1,content:'xxx',author:'roy'...) , now i pass an object like Topic(id:1,content:'yyy',author:null...)。how do i just update the not null fields ? does it have any easy way to do that ?
Comment: Oh, you only want to update certain fields and not others?  Not easy, but see my answer below.
Answer: If you're inheriting from the Model class (as you should), it provides a save() method as well as an ID attribute.  When you call save() on an object you got out of the database, it will be updated, and if you call it on a new object it will be saved to the database.  It's all automagical!
Updating only specific fields
Model.save() saves the whole object, so if you want to update only some data fields in your object, you first have to construct the exact object you want to go in your database.  So let's say you don't want to update null fields, using your Topic(id, content, author) object:
Topic newT = Topic(1L, 'yyy', null);
Long id = newT.getID();

Topic oldT = Topic.findByID(id);  //Retrieve the old values from the database

Author newAuthor = newT.getAuthor(); //null

if (newAuthor != null) {  //This test will fail
  oldT.setAuthor(newAuthor);  //Update the old object
}

String newContent = newT.getContent(); //Not null

if (newContent != null) {
  oldT.setContent(newContent);  //Update the old object
}

// Now the object oldT holds all the new, non-null data.  Change the update tests as you see fit, of course, and then...

oldT.save();  //Update the object in the database.

That's how I would do it.  Depending on how many fields you have this code is going to get really clunky really fast.  Definitely put it in a method.  Also, see here about findByID() and other ways to pull objects from the database.
Comment: In play 2.0.2, Model class provides update method also, does it work the same way as you described for save method to update particular column or I have to implement it the way you have described but that does not make a sense for update method.
Answer: If you look at the JPA Object Binding part of the documentation, you will see it explains that, if you pass in an object to your controller, containing an ID, the object is first automatically loaded from the database, and then the new fields passed in are added to the object.
This means, you can simply call the save() method.
So, you controller action could be something like
public static void editTopic(Topic topic) {
   topic.save();
   //...any post edit processing
}


Erro "java.lang.AbstractMethodError" ao acessar projeto migrado do WebServer GlassFish para o Payara

Question: Migrei um projeto que estava no WebService GlassFish, para o Payara. A implantação ocorreu sem nenhum tipo de erro. Mas quando acesso o projeto, ele acusa um erro: java.lang.AbstractMethodError. Não realizei nenhuma modificação no projeto para que o erro surgisse. Apenas fiz a troca do servidor.
Segue o erro que consta no Log, abaixo:
    [2023-03-24T13:24:53.881-0300] [Payara 5.2020.3] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=74 _ThreadName=http-thread-pool::http-listener-2(4)] [timeMillis: 1679675093881] [levelValue: 900] [[

  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception

java.lang.AbstractMethodError

    at com.sun.ejb.containers.StatefulSessionContainer.createExtendedEMs(StatefulSessionContainer.java:781)

    at com.sun.ejb.containers.StatefulSessionContainer.createBeanInstance(StatefulSessionContainer.java:712)

    at com.sun.ejb.containers.StatefulSessionContainer.createEJBLocalBusinessObjectImpl(StatefulSessionContainer.java:660)

    at com.sun.ejb.containers.BaseContainer.createEJBLocalBusinessObjectImpl(BaseContainer.java:2533)

    at com.sun.ejb.containers.EJBLocalHomeImpl.createEJBLocalBusinessObjectImpl(EJBLocalHomeImpl.java:117)

    at com.sun.ejb.containers.EJBLocalHomeInvocationHandler.invoke(EJBLocalHomeInvocationHandler.java:166)

    at com.sun.proxy.$Proxy1872.create(Unknown Source)

    at com.sun.ejb.EJBUtils.resolveEjbRefObject(EJBUtils.java:372)

    at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:197)

    at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1015)

    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:770)

    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:738)

    at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159)

    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:476)

    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442)

    at javax.naming.InitialContext.lookup(InitialContext.java:417)

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:561)

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:439)

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:153)

    at org.glassfish.faces.integration.GlassFishInjectionProvider.inject(GlassFishInjectionProvider.java:200)

    at com.sun.faces.mgbean.BeanBuilder.injectResources(BeanBuilder.java:179)

    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:77)

    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:387)

    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:247)

    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:200)

    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:55)

    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:156)

    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:184)

    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:91)

    at com.sun.el.parser.AstValue.getBase(AstValue.java:125)

    at com.sun.el.parser.AstValue.getValue(AstValue.java:173)

    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:183)

    at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)

    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:73)

    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:170)

    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:157)

    at javax.faces.component.UIData.getValue(UIData.java:736)

    at javax.faces.component.UIData.getDataModel(UIData.java:1849)

    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:479)

    at javax.faces.component.UIData.setRowIndex(UIData.java:468)

    at javax.faces.component.UIData.visitTree(UIData.java:1441)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at javax.faces.component.UIForm.visitTree(UIForm.java:347)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at br.com.santa.view.handler.SecurityViewHandler.renderView(SecurityViewHandler.java:146)

    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)

    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)

    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)

    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)

    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)

    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1636)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:331)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at br.com.santa.filter.NoWebCache.doFilter(NoWebCache.java:64)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at br.com.santa.filter.AjaxEncoding.doFilter(AjaxEncoding.java:59)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at br.com.santa.filter.InternetExplorer8.doFilter(InternetExplorer8.java:60)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at org.idc.upload.UploadFilter.doFilter(UploadFilter.java:68)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)

    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:757)

    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:577)

    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:158)

    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)

    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)

    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)

    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:200)

    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)

    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)

    at java.lang.Thread.run(Thread.java:748)

]]

[2023-03-24T13:24:53.881-0300] [Payara 5.2020.3] [SEVERE] [] [] [tid: _ThreadID=74 _ThreadName=http-thread-pool::http-listener-2(4)] [timeMillis: 1679675093881] [levelValue: 1000] [[

  javax.servlet.ServletException: Um erro ocorreu ao realizar a inje��o de recurso no bean gerenciado pesquisaBean

    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:725)

    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)

    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1636)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:331)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at br.com.santa.filter.NoWebCache.doFilter(NoWebCache.java:64)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at br.com.santa.filter.AjaxEncoding.doFilter(AjaxEncoding.java:59)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at br.com.santa.filter.InternetExplorer8.doFilter(InternetExplorer8.java:60)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at org.idc.upload.UploadFilter.doFilter(UploadFilter.java:68)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)

    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:757)

    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:577)

    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:158)

    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)

    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)

    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)

    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:200)

    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)

    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)

    at java.lang.Thread.run(Thread.java:748)

Caused by: com.sun.faces.mgbean.ManagedBeanCreationException: Um erro ocorreu ao realizar a inje��o de recurso no bean gerenciado pesquisaBean

    at com.sun.faces.mgbean.BeanBuilder.injectResources(BeanBuilder.java:185)

    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:77)

    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:387)

    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:247)

    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:200)

    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:55)

    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:156)

    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:184)

    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:91)

    at com.sun.el.parser.AstValue.getBase(AstValue.java:125)

    at com.sun.el.parser.AstValue.getValue(AstValue.java:173)

    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:183)

    at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)

    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:73)

    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:170)

    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:157)

    at javax.faces.component.UIData.getValue(UIData.java:736)

    at javax.faces.component.UIData.getDataModel(UIData.java:1849)

    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:479)

    at javax.faces.component.UIData.setRowIndex(UIData.java:468)

    at javax.faces.component.UIData.visitTree(UIData.java:1441)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at javax.faces.component.UIForm.visitTree(UIForm.java:347)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1468)

    at br.com.santa.view.handler.SecurityViewHandler.renderView(SecurityViewHandler.java:146)

    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)

    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)

    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)

    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)

    ... 30 more

Caused by: com.sun.faces.spi.InjectionProviderException: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Local ejb-ref name=br.com.santa.controller.PesquisaBean/projetoFacade,Local 3.x interface =br.com.santa.dao.IProjetoFacade resolved to intra-app EJB ProjetoFacade in module ft,ejb-link=ProjetoFacade,lookup=,mappedName=,jndi-name=,refType=Session into class br.com.santa.controller.PesquisaBean: Lookup failed for 'java:comp/env/br.com.santa.controller.PesquisaBean/projetoFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}

    at org.glassfish.faces.integration.GlassFishInjectionProvider.inject(GlassFishInjectionProvider.java:208)

    at com.sun.faces.mgbean.BeanBuilder.injectResources(BeanBuilder.java:179)

    ... 60 more

Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Local ejb-ref name=br.com.santa.controller.PesquisaBean/projetoFacade,Local 3.x interface =br.com.santa.dao.IProjetoFacade resolved to intra-app EJB ProjetoFacade in module ft,ejb-link=ProjetoFacade,lookup=,mappedName=,jndi-name=,refType=Session into class br.com.santa.controller.PesquisaBean: Lookup failed for 'java:comp/env/br.com.santa.controller.PesquisaBean/projetoFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:638)

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:439)

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:153)

    at org.glassfish.faces.integration.GlassFishInjectionProvider.inject(GlassFishInjectionProvider.java:200)

    ... 61 more

Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/br.com.santa.controller.PesquisaBean/projetoFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound for java:comp/env/br.com.santa.controller.PesquisaBean/projetoFacade [Root exception is javax.ejb.EJBException: Couldn't create EntityManager for refName: br.com.santa.dao.ProjetoFacade/em; unitname: fichaPU]]

    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:496)

    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442)

    at javax.naming.InitialContext.lookup(InitialContext.java:417)

    at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:561)

    ... 64 more

Caused by: javax.naming.NameNotFoundException: No object bound for java:comp/env/br.com.santa.controller.PesquisaBean/projetoFacade [Root exception is javax.ejb.EJBException: Couldn't create EntityManager for refName: br.com.santa.dao.ProjetoFacade/em; unitname: fichaPU]

    at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:229)

    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:476)

    ... 67 more

Caused by: javax.ejb.EJBException: Couldn't create EntityManager for refName: br.com.santa.dao.ProjetoFacade/em; unitname: fichaPU

    at com.sun.ejb.containers.StatefulSessionContainer.createExtendedEMs(StatefulSessionContainer.java:786)

    at com.sun.ejb.containers.StatefulSessionContainer.createBeanInstance(StatefulSessionContainer.java:712)

    at com.sun.ejb.containers.StatefulSessionContainer.createEJBLocalBusinessObjectImpl(StatefulSessionContainer.java:660)

    at com.sun.ejb.containers.BaseContainer.createEJBLocalBusinessObjectImpl(BaseContainer.java:2533)

    at com.sun.ejb.containers.EJBLocalHomeImpl.createEJBLocalBusinessObjectImpl(EJBLocalHomeImpl.java:117)

    at com.sun.ejb.containers.EJBLocalHomeInvocationHandler.invoke(EJBLocalHomeInvocationHandler.java:166)

    at com.sun.proxy.$Proxy1872.create(Unknown Source)

    at com.sun.ejb.EJBUtils.resolveEjbRefObject(EJBUtils.java:372)

    at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:197)

    at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1015)

    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:770)

    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:738)

    at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159)

    ... 68 more

Caused by: java.lang.AbstractMethodError

    at com.sun.ejb.containers.StatefulSessionContainer.createExtendedEMs(StatefulSessionContainer.java:781)

    ... 80 more

]]

Answer: Vou escrever uma resposta porque ainda não tenho reputação suficiente para escrever comentários.
Olhando apenas o log de erro, sem o código das classes que são citadas, é bem difícil dizer com precisão seu problema.
De acordo com o log, eu diria que você tem um EJB br.com.santa.controller.PesquisaBean que injeta um DAO br.com.santa.dao.ProjetoFacade que, por sua vez, injeta o javax.persistence.EntityManager. Aparentemente, quando o container foi tentar criar uma instância para o EntityManager, algo deu errado. Além disso, o log faz referência ao nome da Persistence Unit fichaPU.
A troca de um servidor de aplicação - Glassfish por Payara, no seu caso, na maioria das vezes, não é tão simples assim.
Um exemplo clássico de um ponto onde ocorrem problemas são as definições de DataSources. Sua aplicação provavelmente referência um DataSource por seu nome JNDI no arquivo persistence.xml, mas esse DataSource foi definido no Payara antes?
Outro ponto que pode gerar problema são as versões de diferentes servidores de aplicação. Qual a versão do Glassfish que você está usando? Qual a versão da especificação Jakarta EE - no seu caso parece ser Java EE ainda - que sua aplicação usa? Diferentes servidores de aplicação suportam diferentes versões do Java EE / Jakarta EE.


Props not updated

Question: I'm a new user of React and I try to dispatch a modification from my redux store into my components through a container component and props.
My problem is at the end, the data isn't updated. I tested and I figured out that in a Board component, I got the correct edited state (I edit a module's name in this.state.mlodules[1].name) but this value isn't sent in the Bloc component. Here is the render function of my Board component:
render() {
    const modules = this.state.modules.map((module) => (
        <Draggable key={module._id} x={module.position.x} y={module.position.y} inside={this.state.inside}>
            <Bloc module={module} editModule={this.props.onModuleEdited(module._id)}/>
        </Draggable>
    ));

    return (

            {modules}

    );
}

And here is the render function of my Bloc component (I'm using a BlueprintJS editable text):
render() {
    return (

                <EditableText
                    className="name"
                    defaultValue={this.props.module.name}
                    onChange={this.nameChanged}
                />

    );
}

Any ideas ?
Thanks !
Comment: how do you assign a value for ``? it seems that you are only passing a `defaultValue` and what does `this.nameChanged` do?
Answer: as i mentioned in my comment, you are assigning a defaultValue and not assigning a value prop.
according to their source code on line #77 you can see that there's a value prop.
Edit: As you can see in the docs, defaultValue is uncontrolled input where's value is a controlled input
Comment: You are right about the defaultValue. But my problem is that I can't edit my field. I think it's because every time I type something, It re-render the component. However, the name value that I obtain from the parent component doesn't change that's why I can't "edit" this field. Why do I get the wrong value for the name ?
**Edit**: I find the answer. I was misundertound the basics of "controlled components" (using the state and the event handler onChange). Thank you !
Comment: where is the `name` value? i dont see it in your code, am i missing something?
Comment: The `name` value came from my props (this.props.module.name)
Comment: i've update my answer, dont forget about controlled and uncontrolled inputs
Comment: just noticed you new comment, glad you figure that out :)
Answer: I think, issue is defaultText. defaultText will assign the default text only on initial rendering it will not update the value. So instead of that assign the props value to value property.
Like this:
value = {this.props.module.name}

Note: But it will make the field read-only, if you don't update the props value (state of parent component) in onChange method.
Check this example, when you click on text 'Click Me' it will update the state value but text of input field will not change:

class App extends React.Component{
   constructor(){
      super();
      this.state = {a:'hello'}
   }

   click(){
      this.setState({a: 'world'},() => {
         console.log('updated value: ', this.state.a)
      })
   }

   render(){
      return(

            <Child value={this.state.a}/>

 this.click()}>Click Me

      )
   }
}

class Child extends React.Component{
   render(){
      console.log('this.props.value', this.props.value)
      return(
         <input defaultValue={this.props.value}/>
      )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'))

Comment: Than you for this example.
I understand that I only used defaultValue to set the value of this field at initilisation but actually, I can't edit the value even if I don't set the attribute "value". I think it's because every time I type something, It re-render the component. However, the name value that I obtain from the parent component doesn't change that's why I can't "edit" this field.
Why do I get the wrong value for the name ?
Comment: **Edit**: I find the answer. I was misundertound the basics of "controlled components" (using the state and the event handler onChange). Thank you !

Props not updated


How to preserve kint output upon form submit redirection?

Question: I've attached a custom submit handler to node add/edit form for the article content type:
$form['actions']['publish']['#submit'][] = 'my_module_node_edit_submit';

In the handler, I am trying to inspect the form state values with kint (via the devel module):
kint($form_state->getValues());

Upon submission of the form, I'm able to briefly see the kint output on the screen, but I am also presented with this message:

Redirecting to http://localhost/example.com/node/123

The page then redirects back to view the node, and the kint output is gone. How can I preserve the kint output so it is available after the redirection?
Comment: Just to be clear, is it your own code that performs the redirection or is that something core/contrib is doing?
Comment: I think this is a devel setting that is enabled. Otherwise you would not see such message. Also xdebug a great tool to use for this.
Comment: may be you could disable the direction for a while
Comment: @Clive, the redirection is done by core/kint (my submission handler does nothing but a kint output). If the kint command is removed, the redirection page is not shown. @Ivan Jaros, I looked at `admin/config/development/devel` but did not see any such settings, I shall go with xDebug.
Answer: Use ksm() instead of kint().
I ran into the same issue when I want to inspect the entity after saving, using drupal's hook_entity_presave and kint
I found this article on how to print variables using kint() which explains that ksm() prints the output inside the drupal page (not before as kint()) does.
So this example prints the entity without redirecting:
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  ksm($entity->toArray());
}

Answer: That is the normal behavior of the submit function, to process the form and redirect. If you want to debug this without any tools, then do a var_dump() and then stop the php with die. But debugging without tools is of course not very productive. When you want to do serious work, use xdebug and an IDE of your choice.
Edit:
Another way would be to use the message area, for example with drupal_set_message or dpm() from devel. This puts the debugging information in a session and you can see it after the redirect.


Shell script with export command and notify-send via crontab not working. Exported variable is set by a command

Question: I'd like to send a notification bubble to the gnome desktop from a shell script that is executed by cron.
To make it able to communicate with the desktop environment DBUS_SESSION_BUS_ADDRESS env variable needs to be set within the script. I'm trying to achieve this by the following code which isn't working.
#!/usr/bin/env sh
export DISPLAY=:0
dbus=$(env | grep DBUS_SESSION_BUS_ADDRESS | sed 's/DBUS_SESSION_BUS_ADDRESS=//')
export DBUS_SESSION_BUS_ADDRESS=$dbus
[...]
notify-send -u critical "Blah" "Blubb"

When hardcoded it works fine
export DBUS_SESSION_BUS_ADDRESS='unix:abstract=/tmp/dbus-HjnsLUTTrn,guid=17c8962443279ebbe24dcd66536278dd'

Problem is, the dbus session address changes so hardcoding isn't an option.
What am I doing wrong?
Answer: env when invoked from a script run by cron, only had the following variables set in my box.
SHELL=/bin/sh USER=clement PATH=/usr/bin:/bin PWD=/home/clement HOME=/home/clement SHLVL=2 LOGNAME=clement _=/usr/bin/env

and so grep in
$(env | grep DBUS_SESSION_BUS_ADDRESS | sed 's/DBUS_SESSION_BUS_ADDRESS=//')

didn't give any output. The following should work.
#!/bin/bash
PID=$(pgrep gnome-session)
dbus=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)
export DBUS_SESSION_BUS_ADDRESS=$dbus
notify-send -u critical "Blah" "Blubb"

Comment: I had solved it by writing the result of  `$(env | grep DBUS_SESSION_BUS_ADDRESS | sed 's/DBUS_SESSION_BUS_ADDRESS=//')` to a file in ~/. using the login script and reading it back into `$dbus`. Yours is more elegant though.
Comment: Replace `gnome-shell` with `nautilus` on Ubuntu.


Simple twitter module recommendation

Question: Can anyone recommend me a simple twitter module which will enable me to include twitter feeds on my site? I am using a corporate clean theme and would like to display it in the middle column of the footer section.
Comment: Twitter provides several widgets that are not Drupal-specific but will work on any website and can easily be cut and pasted into a block: https://twitter.com/settings/widgets
Answer: You should use the Twitter module.

This module provides API integration with the Twitter microblogging service. Out of the box, it allows users to:

Associate one or more Twitter accounts with their Drupal user account
List tweets in different ways thanks to Views
Post to their own Twitter account or a site-wide Twitter account whenever they create new content or based on Drupal Actions or Rules
Log in to your Drupal site via Twitter
Format twitter @usernames and #hashtags as links to Twitter.com
Answer: If your needs are simple I would choose a Twitter widget. If you need more advanced integration then I would suggest the Twitter module, perhaps along with Twitter Pull (7.x-2.x-dev), as that is basically the only option with OAuth authentication which will be required when Twitter shuts down API v.1, if they haven't already done so. Most other Twitter modules will no longer work when that happens, and right now the Twitter module is the best option.
Answer: The Twitter Block module provides configurable blocks for a Twitter feed.
Other Tweet modules which might be useful are:

Tweet button adds the Twitter buttons to your nodes.
Twitter provides API integration with the Twitter microblogging service. Out of the box, it allows users to:

Associate one or more Twitter accounts with their Drupal user
account
List tweets in different ways thanks to Views
Post to their own Twitter account or a site-wide Twitter account whenever they create new content or based on Drupal Actions or Rules
Log in to your Drupal site via Twitter
Format twitter @usernames and #hashtags as links to Twitter.com
Comment: Please stop deleting your answers: Deleting them can cause you to be answer banned. If that happens, you would not be anymore able to answer anymore to any question, until you don't get more reputation by asking questions. See [Should I delete my answers?](http://meta.stackexchange.com/questions/146403/should-i-delete-my-answers) Even in the case the answer is wrong, that would help the users who answer the question after you.
Comment: I didn't know that it's wrong. I won't do that any more unless I realy have to. Thank you for pointing that out, I appreciated it.
Answer: The Twitter module is your best bet. I know it can be intimidating at first but just follow the directions and you should be fine. Here's a step by step.

download and install the module.
go to https://apps.twitter.com/app/new and register your application
then go to admin/config/services/twitter/settings and enter your OAuth Consumer key and OAuth Consumer secret and save
Then go to admin/config/services/twitter and add an authenticated account. You can also add other users accounts.

Once you've done all that, you can use views to pull in tweets and display them in pages and blocks.
Hope this helps you out.

Simple twitter module recommendation


How can I set the Rails environment for my somewhat stand alone Ruby script?

Question: I have a Ruby script in my Rails app that I use to load some data from Twitter.
In the future I will make it an automatic background process, but for now I run it manually like:
ruby /lib/twitter/twitterLoad.rb

In order to use the Rails model classes and such, I have the following as the top line of the script:
require "#{File.dirname(__FILE__)}/../../config/environment.rb"

By default, the development environment is used.  But, I'd like to be able to choose the production environment at some point.
Update #1: The RAILS_ENV constant is getting set in the environment.rb file. So, I was able to put ENV['RAILS_ENV'] = 'production' at the very top (before the environment.rb) line and solve my problem somewhat.  So, my new question is, can do pass in env vars through the command line?
Answer: If you're going to be using the rails environment, your best bet would be to make this a rake script. To do this, put a twitter.rake file into lib/tasks and begin and end it like this:
task(:twitter_load => :environment) do
  # your code goes here
end

That way, you're doing it by "following conventions" and it doesn't have that 'orrible smell associated with it.
Answer: I currently use the following method, and I know the environment doesn't have the rb extension, it's not needed. You can also set it before running it to overwrite the ENV["RAILS_ENV"].

#!/usr/bin/env ruby

# Set your environment here.
ENV["RAILS_ENV"] ||= "production"

require File.dirname(__FILE__) + "/../../config/environment"

puts "Rails was loaded!"

Then to change the environment, just run it with:
rb /lib/tasks/file.rb RAILS_ENV=development
Comment: Yeah, after Aram's answer caused an redefining constant error, this is what I tried and it worked.  But, Pantulis's answer let's me choose which environment from the command line.
Comment: You can set the constant while running the script as well (I added an example inside the answer as well initially)
Answer: Don't forget script/runner.
Set your environment variable from the command line and
ruby script/runner your_script_here.rb

Comment: In 3.0+, use `rails runner path/to/script`.  Note: the path to your script is relative to your project root, not your working dir.
Comment: Advantages? Disadvantages? Still relevant in Rails 3.0?
Answer: The accepted answer to use rake is well-taken, but you may still want to manually set the environment for testing utility classes.
Here's what I use to set up the test environment for utility classes in /lib. For these I tend to use the Ruby convention of making my class file execute its tests when it gets run from the command line. This way I can do TDD outside of Rails' web-centric test harnesses, but still use the class within rake without affecting the environment that it sets.
This goes at the top:
if (__FILE__ == $0)
  ENV['RAILS_ENV'] ||= 'test'
  require File.join(File.dirname(__FILE__),'../config/environment.rb')
end

and this goes at the bottom:
if (__FILE__ == $0)
  require 'test/unit/ui/console/testrunner'
  Test::Unit::UI::Console::TestRunner.run(MyClassTest)
end

Answer: You can also do
script/console development < path/to/your/script.rb
Admiteddly cumbersome -and will spit out lots of irb garbage after evaluating each and every line of your script- but works for quickies and you dont have to remember that damned require line.
And don't forget that maybe the most elegant way to extend your app with scripts that do useful things is writing Rake tasks!
Comment: Well, this is just a temporary thing until I get BackgrounDRB to run the script automatically. So, while kludgey, this would work for now.
Answer: add the line:
RAILS_ENV = '<your environment of choice>'
http://wiki.rubyonrails.org/rails/pages/Environments#script
pantulis: It's cool that that works, but for quickies I just use RAILS_ENV = '<your environment of choice>' ruby path/to/script.rb. This is how you set environment variables in the console.
Comment: that's already being set in the 'environment.rb' file so I get the following error: lib/twitter/twitterLoad.rb:11: warning: already initialized constant RAILS_ENV
Comment: You need to add the require after it.
Answer: require 'bundler'
require 'bundler/setup'

ENV['RAILS_ENV'] ||= 'development'

RAILS_ROOT = Pathname.new(File.expand_path('~/path/to/root'))

puts "Loading Rails Environment from #{RAILS_ROOT}..."
require RAILS_ROOT.join('config/environment').to_s

This works but only if the Gemfile of your script contains all the dependencies of your rails app. You might be able to load one Gemfile from another, e.g just eval it, to overcome this copy/paste.