Javascript DOM | Find element by inner Text and replace every element that matches

Question: Here's the code I scraped from the internet and done something to it, I don't know anything about Javascript so don't blame me if this code is a total mess :)
My Code:
var aTags = document.getElementsByTagName("a");
var searchText = "VRX";
var found;

for (var i = 0; i < aTags.length; i++) {
  if (aTags[i].textContent == searchText) {
    found = aTags[i];
    break;
  }
}

Array.from(found).forEach(
    function(element, index, array) {
       document.getElementsByClassName("nova").style = "text-shadow:0.5px 0.5px 5px gold;color:gold;background: url(https://static.nulled.to/public/assets/sparkling.gif);-webkit-animation: randclanim 2s infinite linear;";
    }
);

HTML:
Comment: I don't understand what do you want to do! Dude please ask question clearly.
Comment: I apologize that I don't have the knowledge to ask clearly.   Let me explain again. The first part of the code gets the first element/tag that contains the word "VRX", I want that it gets every element that contains "VRX" in this nova class and adds the style value for each nova class that contains the word "VRX.
Comment: Yeah that's gr8 but nothing you've just commented is posted in your actual question...
Comment: Well, now u know ;)
Answer: As I see screenShot of your code, you should parsing span elements for example I write below code:

// if you want just A elements use below line
var els = document.getElementsByTagName("span");

  for (i = 0; i < els.length; i++) {
   console.log(els[i].textContent +"--" + i );
     els[i].className.lastIndexOf('nova')!=-1 && els[i].textContent.lastIndexOf('VRX')!=-1  ?  els[i].style = "text-shadow:0.5px 0.5px 5px gold;color:gold;background: url(https://static.nulled.to/public/assets/sparkling.gif);-webkit-animation: randclanim 2s infinite linear;" : 0;

  }

  HI

   VRX

 VRX

I hope it useful ;)
Comment: Sorry for interrupting u again, this code works perfectly fine. Example im writing a message in the shoutbox, is it possible to optimize the code that it refreshes itself or reruns to add the style value? I already tried it with looping the code, but this makes the website very laggy.
Comment: @VRX ,Dude upload part of your code in http://jsfiddle.net/ and link to me


the formula of eigenvalues of the matrix A

Question: For the linear system of the ODEs$${x'= Ax}$$  can please anyone explain why the eigenvalues of the matrix A are given by
$$ {\displaystyle \lambda _{1,2}={\frac {\operatorname{tr} (A)\pm {\sqrt {\operatorname{tr} (A)^{2}-4~ \det(A)}}}{2}}.}$$
Answer: This is true if $A$ is a $2 \times 2$ matrix because the characteristic polynomial of $A$ is $x^2 - \operatorname{tr}(A)x + \det(A)$. To see why, compute
$$ \left| \begin{pmatrix} a & b \\ c & d \end{pmatrix} - xI \right| = \left| \begin{pmatrix} a - x & b \\ c & d - x \end{pmatrix} \right| = (a - x)(d - x) - bc = x^2 - (a + d)x + (ad - bc) \\ =
x^2 - \operatorname{tr}(A)x + \det(A). $$
Comment: thank you very much , and the same idea for n by n linear system ?
Comment: @user0533535412: Not really, the formula for the characteristic polynomial in terms of the matrix coefficients is much more complicated. See https://en.wikipedia.org/wiki/Characteristic_polynomial for more details.


Why do we use ReLU in neural networks and how do we use it?

Question: Why do we use rectified linear units (ReLU) with neural networks? How does that improve neural network?
Why do we say that ReLU is an activation function? Isn't softmax activation function for neural networks? I am guessing that we use both, ReLU and softmax, like this:
neuron 1 with softmax output ----> ReLU on the output of neuron 1, which is
input of neuron 2 ---> neuron 2 with softmax output --> ...
so that the input of neuron 2 is basically ReLU(softmax(x1)). Is this correct?
Answer: The ReLU function is $f(x)=\max(0, x).$ Usually this is applied element-wise to the output of some other function, such as a matrix-vector product. In MLP usages, rectifier units replace all other activation functions except perhaps the readout layer. But I suppose you could mix-and-match them if you'd like.
One way ReLUs improve neural networks is by speeding up training. The gradient computation is very simple (either 0 or 1 depending on the sign of $x$). Also, the computational step of a ReLU is easy: any negative elements are set to 0.0 -- no exponentials, no multiplication or division operations.
Gradients of logistic and hyperbolic tangent networks are smaller than the positive portion of the ReLU. This means that the positive portion is updated more rapidly as training progresses. However, this comes at a cost. The 0 gradient on the left-hand side is  has its own problem, called "dead neurons," in which a gradient update sets the incoming values to a ReLU such that the output is always zero; modified ReLU units such as ELU (or Leaky ReLU, or PReLU, etc.) can ameliorate this.
$\frac{d}{dx}\text{ReLU}(x)=1\forall x > 0$ . By contrast, the gradient of a sigmoid unit is at most $0.25$; on the other hand, $\tanh$ fares better for inputs in a region near 0 since $0.25 < \frac{d}{dx}\tanh(x) \le 1 \forall x \in [-1.31, 1.31]$ (approximately).
Answer: One important thing to point out is that ReLU is idempotent. Given that ReLU is $\rho(x) = \max(0, x)$, it's easy to see that $\rho \circ \rho \circ \rho \circ \dots \circ \rho = \rho$ is true for any finite composition. This property is very important for deep neural networks, because each layer in the network applies a nonlinearity. Now, let's apply two sigmoid-family functions to the same input repeatedly 1-3 times:

You can immediately see that sigmoid functions "squash" their inputs resulting in the vanishing gradient problem: derivatives approach zero as $n$ (the number of repeated applications) approaches infinity.
Answer: Why do we use ReLUs? We use ReLUs for the same reason we use any other non-linear activation function: To achieve a non-linear transformation of the data.
Why do we need non-linear transformations? We apply non-linear transformations in the hope that the transformed data will be (close to) linear (for regression) or (close to) linearly separable (for classification). Drawing a linear function through non-linearly transformed data is equivalent to drawing a non-linear function through original data.
Why are ReLUs better than other activation functions? They are simple, fast to compute, and don't suffer from vanishing gradients, like sigmoid functions (logistic, tanh, erf, and similar). The simplicity of implementation makes them suitable for use on GPUs, which are very common today due to being optimised for matrix operations (which are also needed for 3D graphics).

Why do we need matrix operations in neural networks?: It's a compact and computationally efficient way of propagating the signals between the layers (multiplying the output of the previous layer with the weight matrix).
Isn't softmax activation function for neural networks? Softmax is not really an activation function of a single neuron, but a way of normalising outputs of multiple neurons. It is usually used in the output layer, to enforce the sum of outputs to be one, so that they can be interpreted as probabilities. You could also use it in hidden layers, to enforce the outputs to be in a limited range, but other approaches, like batch normalisation, are better suited for that purpose.
P.S. (1) ReLU stands for "rectified linear unit", so, strictly speaking, it is a neuron with a (half-wave) rectified-linear activation function. But people usually mean the activation function when they talk about ReLUs.
P.S. (2) Passing the output of softmax to a ReLU doesn't have any effect because softmax produces only non-negative values, in range $[0, 1]$, where ReLU acts as identity function, i.e. doesn't change them.
Answer: ReLU is the max function(x,0) with input x e.g. matrix from a convolved image. ReLU then sets all negative values in the matrix x to zero and all other values are kept constant.
ReLU is computed after the convolution and is a nonlinear activation function like tanh or sigmoid.
Softmax is a classifier at the end of the neural network. That is logistic regression to normalize outputs to values between 0 and 1. (Alternative here is a SVM classifier).
CNN Forward Pass e.g.: input->conv->ReLU->Pool->conv->ReLU->Pool->FC->softmax
Comment: Downvoting. This a very bad answer! Softmax is not a classifier! It is a function that normalizes (scales) the outputs to the range [0,1] and ensures they sum up to 1. Logistic regression does not "regularize" anything! The sentence "ReLU is computed after the convolution and therefore a nonlinear activation function like tanh or sigmoid." lacks a verb, or sense.
Comment: The answer is not that bad. The sentence without the verb must be "ReLU is computed after the convolution and *IS* therefore a nonlinear activation function like tanh or sigmoid."

Thinking of softmax as a classifier makes sense too. It can be seen as a *probabilistic* classifier that assigns a probability to each class. It "regularizes"/"normalizes" the outputs to the [0,1] interval.
Answer: ReLU is a literal switch.  With an electrical switch 1 volt in gives 1 volt out, n volts in gives n volts out when on.  On/Off when you decide to switch at zero gives exactly the same graph as ReLU.
The weighted sum (dot product) of a number of weighted sums is still a linear system.
For a particular input the ReLU switches are individually on or off.  That results in a particular linear projection from the input to the output, as various weighted sums of weighted sum of ... are connected together by the switches.
For a particular input and a particular output neuron there is a compound system of weighted sums that actually can be summarized to a single effective weighted sum.
Since ReLU switches state at zero there are no sudden discontinuities in the output for gradual changes in the input.
There are other numerically efficient weighted sum (dot product) algorithms around like the FFT and Walsh Hadamard transform.  There is no reason you can't incorporate those into an ReLU based neural network and benefit from the computational gains.
(eg. Fixed filter bank neural networks.)
Answer: ReLU is probably one of the simplest nonlinear function possible. A step function is simpler. However, a step function has the first derivative (gradient) zero everywhere but in one point, at which it has an infinite gradient. ReLU has a finite derivative (gradient) everywhere. It has an infinite second derivative in one point.
The feed forward networks are trained by looking for a zero gradient. The important thing here is that there's a lot of first derivatives to calculate in a large net's backpropagation routine, and it helps that they are fast to compute like ReLU. The second is that unlike step function, ReLU's gradients are always finite and they're not trivial zeros almost everywhere. Finally, we need nonlinear activations for the deep learning net to work well, but that's different subject.


how to get count of total record

Question: I'm using drupal pagination here i have add some part of my code pagination is working perfect while I'm trying to get the total no of record it is always displaying 10. As i understand i have set the limit 10 so it displaying only total 10
$query->orderBy('r.published_date', 'DESC');
        $pager = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
    $results = $pager->execute()->fetchAll();

This $results variable I'm getting data with the set of 10 values.
I would like to display total no of data for that i have created other variable where i have directly executed query in $result so it could give total no of records but its not working it displaying only 10
$result = $query->execute();
        while($data = $result->fetchObject()){
           $count_ret[]=$data->published_date;
        }
             $total=count($count_ret);

please  guide me where i'm doing wrong
Answer: Until the issue Convert pager.inc to a service is solved you find the pager information still in global variables:
global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;

$count_of_total_records = $pager_total_items[$element];

Where $element defaults to '0' if this is the first pager with no element id set.
Comment: Thanks i was using like this  global $pager_total_items;
                                          global $pager_total;
                                            echo $pager_total; echo $pager_total."hiiii";

how to get count of total record


How to convert a select query into a pandas DataFrame using PeeWee

Question: Using the PeeWee ORM I have the following query:
query = DataModel.select()where(DataModel.field == "value")

Is there any way to convert query into a pandas DataFrame without iterating over all the values? I'm looking for a more "Pythonic" way of doing this.
Answer: Assuming query is of type peewee.SelectQuery, you could do:
df = pd.DataFrame(list(query.dicts()))

EDIT: As Nicola points out below, you're now able to do pd.DataFrame(query.dicts()) directly.
Comment: for some reason `list(query.dicts())` is failing if there is a column that has the name of the table... has anybody experienced the same issue?
Comment: Brilliantly simple, and works like a charm! I won't tell you how long I spent trying to figure that one out, it's embarrassing. lol
Comment: Don't use list(), the correct code is: `pd.DataFrame(query.dicts())`
Answer: Just in case someone finds this useful, I was searching for the same conversion but in Python 3. Inspired by @toto_tico's previous answer, this is what I came up with:
import pandas
import peewee

def data_frame_from_peewee_query(query: peewee.Query) -> pandas.DataFrame:
    connection = query._database.connection()  # noqa
    sql, params = query.sql()
    return pandas.read_sql_query(sql, connection, params=params)

Checked with Python 3.9.6, pandas==1.3.2 and peewee==3.14.4, using peewee.SqliteDatabase.
Comment: Thanks a lot for writing this out — this is 100% the correct answer.
Answer: The following is a more efficient way, because it avoids creating the list and then pass it to the pandas dataframe. It also has the side benefit of preserving the order of the columns:
df = pd.read_sql(query.sql()[0], database.connection())

You need direct access to the peewee database, for example, in the quickstart tutorial corresponds to:
db = SqliteDatabase('people.db')

Of course, you can also create your own connection to the database.
Drawback: you should be careful if you have repeated columns in the two tables, e.g. id columns would appear twice. So make sure to correct those before continuing.

If you are using a peewee proxy
import peewee as pw;
database_proxy = pw.Proxy()

then the connection is here:
database_proxy.obj.connection()

Comment: How do you deal with the fact that `query.sql()[0]` returns a string with `%s` as placeholders?
Comment: @LivingSilver94 It isn't a complete solution but getting a cursor and using mogrify works for postgres: `cursor = db.cursor()` then `pd.read_sql(cursor.mogrify(*query.sql()), ...)`
Comment: I would have to take a look at your exact query but in generally it could mean that there is a format-string python syntax, [check this](https://stackoverflow.com/questions/997797/what-does-s-mean-in-a-python-format-string)


Usar JQuery para trocar textos

Question: Bom dia!
Não tenho acesso ao HTML de um site que estou editando, por isso pra fazer adições, só consigo via css ou js. Basicamente preciso trocar um texto de "serviço", para "Transfer" e to tentando com jquery no "Javascript no header", que tem no WP.
Sou bem amador em JS então não sei dizer onde está o erro. Estou tentando usar o Firebug pra achar problemas, mas a princípio o código nem aparece nele.
Segue codigo de como está agora

$(document).ready(function(){
    $('service').text('Transfer');
});

  <input type="checkbox" checked="checked" value="Service" id="package-service-toggle">

Serviço

Comment: Mas você consegue ver o código-fonte e poderia postar o trecho que você quer alterar na pergunta.
Comment: basicamente não vai funcionar, porque você fez um selector para buscar um elemento da tag "service", como se fosse "table", "body" ou "p", não acho que seja o caso. Se service for um id ou classe, precisa rever o seletor. Coloque o html pra que possamos ajudar
Comment: Segue HTML Serviço  O ID que tenho que escolher seria então "package-service-togglw"?
Comment: Adicione o código na pergunta, é só clicar em [editar](https://pt.stackoverflow.com/posts/329660/edit)
Answer: O problema pode ser no seletor que você está usando. Pois $("service") faz com o jQuery procure por um elemento <service> no DOM, o que acho pouco provável que aconteça. Veja:
$('service'); // Procura por <service>
$('#service'); // Procura por <??? id="service" />
$('.service'); // Procura por <??? class="service" />

Um exemplo funcional:

console.log('$("p"): ', $('p').html());   // Busca por tag
console.log('$("#p"): ', $('#p').html()); // Busca por id
console.log('$(".p"): ', $('.p').html()); // Busca por class

id == "p"

tag == "p"

class == "p"

Você pode checar a documentação do jQuery para ver mais opções de seletores.
Answer: Você vai conseguir desta forma:
$(document).ready(function(){
    $('#package-service-toggle')
    .closest('.service')
    .find('p')
    .text('Transfer');
});

Como podem ter outros elementos com a classe .service, selecione o id do input, busque o elemento pai que possua a classe .service e em seguida busque pela tag
, que só tem uma:

$(document).ready(function(){
    $('#package-service-toggle')
    .closest('.service')
    .find('p')
    .text('Transfer');
});

  <input type="checkbox" checked="checked" value="Service" id="package-service-toggle">

Serviço

Ou pode usar JavaScript puro que faz a mesma coisa:
document.addEventListener('DOMContentLoaded', function(){
   document.querySelector('#package-service-toggle')
   .parentNode.querySelector('p')
   .textContent = 'Transfer';
});

Exemplo:

document.addEventListener('DOMContentLoaded', function(){
   document.querySelector('#package-service-toggle')
   .parentNode.querySelector('p')
   .textContent = 'Transfer';
});

  <input type="checkbox" checked="checked" value="Service" id="package-service-toggle">

Serviço

Talvez seja necessário fazer a alteração após o carregamento completo
  da página. Para isso altere o $(document).ready(function(){ para
  $(window).on('load', function(){.
Comment: Ainda não consegui. O codigo agora está assim
Comment: Alterei a resposta. Veja agora.
Comment: Ainda não consegui. Estou colocando precisamente assim           Em teoria o WP já vem com essa biblioteca instalada então e como não tenho acesso ao HTML, só tenho como colocar esse cod usando o bloco "codigo js customizado", que é onde to colando. No caso na Header.
Comment: Dá uma olhada no console e veja se aparece algum erro
Comment: Nenhum relacionado a isso, segue link do site. Dentro da pagina estou tentando trocar o termo do motor de busca "monte sua viagem" de "serviço" para "transfer". https://viagens.apino.com.br/rd-summit-2018/
Comment: Funcionou sam! tks!
Comment: Blz. vou inserir na resposta porque pode ajudar quem tiver o mesmo problema. Abs!
Answer: O erro é que não foi bem especificado para o jQuery qual elemento você deseja manipular.
Portanto, como o service é um class deve-se colocar "." dentro do seletor do jQuery. E faltou navegar até o seu parágrafo.

$(document).ready(function(){
    $('.service p').html('Transfer');
});

    <input type="checkbox" checked="checked" value="Service" id="package-service-toggle">

Serviço

Usar JQuery para trocar textos


Is there a field tpl for body and/or title fields?

Question: I need to add some data- attributes and I am hoping to change it for the body and title fields on article content types. Do the title/body have tpl's that I can modify to add these? Or another method I could try? I've tried adding a field--body--article.tpl.php and it doesn't appear to work.
NOTE: This needs to be done in PHP as the search engine we're using needs it to be done server side.
Comment: You can do this by setting a view for the content type and using fields. Then use views templates for the title/body fields.
Answer: Title does not use a template, but is rendered directly in page.tpl.php by default.
Display Suite can be used to override this behavior. Many examples available. Here's one for D8, but the principal is the same in D7: https://www.webwash.net/using-display-suite-drupal-8-how-to-use-display-suite-fields/
You may also find using preprocess hooks in template.php to be useful.
https://www.drupal.org/docs/7/theming/overriding-themable-output/setting-up-variables-for-use-in-a-template-preprocess-and
Proprocess hooks give you control over the entire render pipeline, so it's hard to give better guidance without knowing more specifics of your use case.


Loading class which have only static methods

Question: I have a class MyClass that has a static variable. Class implements smth like singleton(it has java.sql.DataSource as static variable and has method getConnection() which checks whether DataSource variable is not null and if it is null - obtains the connection, else - return dataSource.getConnection())
When I call MyClass.getConnection() method for the first time the class is loaded to the memory and DataSource variable is obtained. Will this class stay in memory while the program is running or it will be garbage collected when the control flow of the program will exit outside the method where  MyClass.getConnection() was invoked?
Actually I want to know whether I have to obtain Connection object in each method(obtaining connection object is rather long operation, isn't it?) where I use it or only once in some place?
edit
This is my class that obtains a connection
public class ResourceManager {

    private static DataSource dataSource;

    public static synchronized Connection getConnection() throws NamingException, SQLException {
        if (dataSource == null) {
            Locale.setDefault(Locale.ENGLISH);
            Context context = (Context) new InitialContext().lookup("java:comp/env");
            dataSource = (DataSource) context.lookup("jdbc/Project");
            context.close();
        }
        return dataSource.getConnection();
    }

    public static void close(Connection con) {
        if (con != null)
            try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void close(ResultSet rs) {
        if (rs != null)
            try {
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void close(PreparedStatement stmt) {
        if (stmt != null)
            try {
            stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

in this class I obtain connection from tomcat pool
So, if in one method I call ResourseManager.getConnection() and it obtains the datasource, will it be the same datasource when I call this method after some time passed or it will be GC?
P.S. I use close methods in finally blocks
Comment: I've tried to understand your question, but it is hard. Can you improve the formatting so that we can see what you are asking?
Answer:
Will this class stay in memory while
  the program is running or it will be
  garbage collected when the control
  flow of the program will exit outside
  the method where
  MyClass.getConnection() was invoked?

Class objects will become eligible for garbage collection just like any other object - when no references exist to the Class objects. Typically, these references are held by the ClassLoader that loaded the Class in the first place. So, the class will stay as long as the Classloader that references it, is in use. It will not be unloaded after method execution, unless the Classloader was created by the caller, and the reference to the classloader no longer exists.
In long running applications (like Java EE applications), the class and the classloader (a unique one will typically exist for every application) will not be eligible for garbage collection, until the application itself is brought down.
The singleton pattern and its effect on GC
The garbage collection of classes that implement the singleton pattern is a unique situation. The class continues to be referenced by its instance, so it will never be eligible for garbage collection. This could lead to problems where the classloaders themselves may not be garbage collected, especially during application restarts in a container, thus leading to a memory leak. The solution to prevent such a problem, is to destroy the singleton instance in a context listener that listens for the context (application) destruction event.
Update #2
For the updated question:

Actually I want to know whether I have to obtain Connection object in each method(obtaining connection object is rather long operation, isn't it?) where I use it or only once in some place?

Obtaining a connection is expensive, but only if you manage the connection. That's why you use a datasource backed by a connection pool. Everytime you need a connection, the datasource will fetch one from the pool. Once you are done with the connection, you should close it, so that it can be returned to the pool. My advice is to not perform premature optimizations; connection pools are a fact in modern Java EE applications, and application servers perform enough optimization to ensure that there is very little latency here. IMHO, a properly tuned pool will give you better performance than a hand-crafted class put in place to centralize access to connection objects.
Comment: I don't think that this is correct.  By default the JVM will GC unused classes. But static variables are a GC root, so that once a class with a singleton has been initialised it will not be GC'd because the singleton will be an instance of the class. Set the singleton to null and the class can be GC'd if there are no other instances.
Comment: @Chris: Do you mean have an actual connection stored in a Singleton? If so, that is a very dangerous pattern for a wide variety of reasons (scalability comes immediately to mind).
Comment: If the singleton is only referenced by the class, and the class only by the singleton and classloader, and the classloader only by this class, shouldn't the garbage collector be able to clean this up?
Comment: @maks, use dependency injection if you can, to inject the DataSource objects at the point of need; then you can call getConnection() freely on the DS object. If you do not want to do dependency injection, avoid looking up the DataSource in the JNDI context first (this is performance intensive for every connection); you can store the DS reference in the resource manager, and return connections from it.
Comment: @Paulo, no the garbage collector will not clean up the singleton in that case. GC occurs for objects unreachable from GC roots. The singleton, it's class and the classloader will all be reachable from the thread stack (which is a GC root) or from the static member variable (which is a GC root).
Comment: @Vineet actually, in the example above i store reference in the resource manager. Thanks for help
Comment: @maks, I missed the if block. Also, I'm unsure about the need to synchronize on the DataSource object. It is most likely unnecessary. If you cannot use DI, use the (now deprecated) [ServiceLocator pattern](http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html).
Comment: maybe synchronize will avoid returning the same connection to different users if they simultaneously try to get connection?
Just came to mind: if I check for null in getconnection so every user will get the only one datasource from connection pool, because every time resource manager will return the same connection from the  only one datasource. Am I wrong?
Comment: @maks, I don't think so. If that were the case, even injected data source objects would need synchronization, which is not the case. Only a poorly programmed data source will exhibit the behavior that you've described.
Comment: Just came to mind: if I check for null in getconnection so every user will get the only one datasource from connection pool, because every time resource manager will return the same connection from the only one datasource. Am I wrong?
Comment: @Vineet hmm, my ResourceManager is not a kind of serviceLocator pattern, is it?
Comment: @maks, if it returned only the DataSource to a client class, I would have considered it to be a service locator. The current class however has too many responsibilities. It would be better to return the DS to the client, and have the Connection, PreparedStatement and other objects managed by the client.
Comment: @maks, as far as returning datasources from the pool, well that concept is incorrect. A datasource has access to a pool of physical connection objects. However, it never returns a physical connection to the client; it always returns a logical wrapper around the connection object. That way, the client never gets to create or close the real connection; all of this activity is done by the pool. You can provide the datasource object to multiple clients. If the datasource implementation is threadsafe, different connection wrappers will be returned to multiple clients in a thread safe manner.
Comment: @Gregory -- sorry to take a while. New baby in the family. No, actually I recommend against using singletons for maintaining database connections for the reason you mention about cleaning them up. I prefer to have a class that I can instantiate to maintain the connections and then I can better assure it is cleaned up with an explicit cleanUp method and then I can override the finalize method to make sure cleanUp is called to make sure the connections are released.
Comment: ++ to Vineet. You are better off creating a singleton that obtains the connection. But then don't forget to have a clean up method and/or put the release connection in the finalize() method so it can be released correctly on collection of the singleton. You might be better off having a regular class than trying to do something fancy with a static class. Trust me. I just did this on something I was working on. A regular instantiated class was cleaner.
Comment: @Duncan, the JLS allows for reclaiming classes only when the classloader is eligible for reclamation: `An implementation of the Java programming language may unload classes. A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector as discussed in §12.6.`
Comment: @Duncan, you are right however, that given the presence of the singleton, the class itself will never be eligible for reclamation unless the shutdown process of the application will nullify the singleton instance.
Comment: @Duncan: If the Singleton is static, it will remain in memory until the application shuts down. You can empty out a class method (as opposed to an instance method), but it will not GC like an instance method and it will remain there, albeit null, until the application shuts down.
Comment: @Vinnet So, should i not to use static variable DataSource, but simply obtain datasource in getConnection method and return connection from this datasource immediatly?
Answer: When you deal with static methods, etc., they do not belong to an instance. As such, they are not garbage collected when instances are collected. Instead, they stay in memory. In theory, they should stay in memory until the application in question is terminated. As long as it continues to run, the static items stay in memory.
What this means to you? if you are shutting down the application, the Singleton will be set for collection and collected at some point in time. Otherwise, it will stay there.


Exclude .NET Standard/.NET Core projects from NuGet restore step

Question: I have a solution that I am trying to move to being built by VSTS.  I have a dotnet restore step before my VS Build Solution step, but my VS Build step is failing.

[error]C:\Program Files\dotnet\sdk\2.1.100\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets(167,5): Error : Assets file 'D:\a\1\s...\...\obj\project.assets.json' not found. Run a NuGet package restore to generate this file.

But I have Restore NuGet Packages checked on the VS Build, and the dotnet restore step should also fix this.
I'm sure I'm missing something silly with this, but what am I missing with this?
Answer: Unsurprisingly, it was a silly thing.  I needed to add the last project to the dotnet restore step.  Thanks anyway!
Comment: What do you mean by "The Last project"?
Comment: The one project out of the solution that is .NET Framework, not .NET Standard.


How to pass variables from the thread to the outside environment?

Question: I have a Thread nested in the main activity:
public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    new Thread(new Runnable(){
        public void run() {
            int myInt = 1;
            // Code below works fine and shows me myInt
            TextView textView = (TextView) findViewById(R.id.text_view);
            textView.setText(myInt);
        }
    }).start();

    // Code below doesn't work at all
    TextView textView = (TextView) findViewById(R.id.text_view);
    textView.setText(myInt);

}

I'm not sure if this structure is correct at all. How should I pass myInt variable to the MainActivity so it will become recognizable and operable outside the Thread?
Comment: Handler is the best way. Here is the good article about it http://www.vogella.com/articles/AndroidPerformance/article.html
Answer: You would first want a global variable for the integer that is already set before you try setting the textview that's outside of your thread (on the main thread). It needs to be set beforehand because the new thread you start will simply be started and move along to the next lines of code, so myInt won't have been set yet.
Then, use the predetermined global integer value for the textview on the main thread, at least initially. If you would like to change it from within the thread you started, then create a method in your class like setIntValue() which will pass in the integer from the thread and set the global variable to that value. I can update with code examples later if you'd like.
UPDATE: example code
public class MainActivity extends Activity {

//your global int
int myInt

public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);

new Thread(new Runnable(){
    public void run() {
        int myRunnableInt = 1;
        // Code below works fine and shows me myInt
        TextView textView = (TextView) findViewById(R.id.text_view);
        textView.setText(String.valueOf(myRunnableInt));

        //say you modified myRunnableInt and want the global int to reflect that...
        setMyInt(myRunnableInt);
    }
}).start();

//go ahead and initialize the global one here because you can't directly access your
myRunnableInt
myInt = 1;

TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.valueOf(myInt)); //now you will have a value here to use

//method to set the global int value
private void setMyInt(int value){
    myInt = value;

    //you could also reset the textview here with the new value if you'd like
    TextView textView = (TextView) findViewById(R.id.text_view);
    textView.setText(String.valueOf(myInt));
}
}

Note: If you only wish to be able to reset the textview, as opposed to having a global, operable variable, I would suggest changing the method to just pass in the new integer and set the textview, rather than storing a global variable, like this:
private void setTextView(int newInt){
    TextView textView = (TextView) findViewById(R.id.text_view);
    textView.setText(String.valueOf(newInt));
}

If you do the above, make sure when you call the method from within the thread, call it on the UI thread like so:
    runOnUiThread(new Runnable()){
        public void run(){
            //update UI elements
        }
    }
Comment: Anyway you helped me a lot! Thanx!
Comment: It seems to work, but when I try to `textView.setText()` inside the `setMyInt(value)` I get nothing ... If I do `Log.d("myAlert",String.valueOf(value));` works perfect! I see the correct value in the console. Any thoughts why?
Comment: Sorry, I forgot that you must call the method from within a runOnUiThread call. Will update code.
Comment: No problem! Updated code with example of calling runOnUiThread
Answer: change
public class MainActivity extends Activity {
    // create activity field/member
    private int myIntValue;
    public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    runOnUiThread(new Runnable(){
        public void run() {
            myIntValue = 1;
            // Code below works fine and shows me myInt
            TextView textView = (TextView) findViewById(R.id.text_view);
            if (textView != null){
                textView.setText(myInt);
            }
        }
    });

    TextView textView = (TextView) findViewById(R.id.text_view);
    if (textView != null){
        textView.setText(myIntValue);
    }
}

Comment: I would suggest using runOnUiThread only since you are modifying the UI from what could be a background thread (if you change things around and use executors or something similiar).  but the new Thread(){}.start would work too.
Comment: I'm not sure this will work, unless he/she plans to not change myInt elsewhere, because myInt will have to be declared final if being used in the runnable.
Comment: it doesn't work for me ... I always get 0 (the initial value declared at the top)
Comment: also I've found just now that `textView.setText(myIntValue)` crashes the app and it's appropriateto use `textView.setText(String.valueOf(myIntValue))`
Answer: Try the following:
public class MainActivity extends Activity
{
    TextView textView;

    public void onCreate(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text_view);
        new Thread(new Runnable()
        {
            public void run()
            {
                int myInt = 1;
                textView.setText(myInt);
            }
        }).start();

    }

Comment: The thing is I'm trying to get **myInt** accessible outside the Thread in some external calsses for example ... but I tried your structure and it worked thanx!
Comment: In that case do with myInt the same as I did with textView and you will be able,for example,to pass as a parameter to other external classes
Comment: this code is wrong , you can change in ui with this code , please remove your answer


Compare specific recovery with random expectation

Question: i am reading a scientific article and i would like to understand how a specific statistical calculation is done. I am missing the principle and the method. If somebody could be so gentle to explain me which specific test has been done and why that would be great! i attach here the sentence:

To compare the recovery of known BMD genes to what would be expected
  by chance, we searched whole-body BMD data on 1928 mouse mutants
  (selected at random with respect to known involvement in BMD) from the
  International Mouse Phenotyping Consortium (IMPC) (Brown and Moore,
  2012a; 2012b). In the IMPC, 6.3% (122 of 1928) of mouse knockouts
  exhibited a BMD phenotype compared to 55% recovery of known regulators
  of BMD in the OFM (OR=8.6, Fisher's P=9.6 × 10−10), confirming that
  with respect to the regulation of BMD, the OFM is not a random gene
  set.

I attach here the reference: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5269473/pdf/nihms-824818.pdf
thanks in advance
Answer: seems they did fisher's exact test. It would be heavy computation though, like a permutation test, fisher's exact test, wiki
Comment: hi, why you say heavy computation? i understand the principle of fisher's but i dont see the point of applying this to this case to validate a run of predictions.
Comment: exact tests must generate the pool of possible results, hence demanding. Consider this paper: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3167045/: "The statistical assessments of interest are generated for each permutation sample. If the treatment has an effect, then one would expect the observed pattern of results to occur rarely among these re-randomized samples. Fisher's exact test, with which many researchers are familiar, is a permutation test for a single dichotomous endpoint.". I dont do gwas, but my immediate hunch for this kind of data would be an exact test, no study set up


Chamar post na página que é mostrado

Question: Eu tenho uma página de postagens que mostra o título da postagem e quero que ao clicar no no título abrisse uma DIV com a postagem em si.
Não tenho problemas quanto ao Javascript necessário para isso. O meu problema é que todas as notícias estão sendo mostradas, ao invés de apenas aquela associada ao título clicado.
Acredito que o meu problema esteja no loop, mas não consegui resolver.
Esse é meu código atual:

<?php query_posts('posts_per_page=2&cat=36');?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

        <img src="<?php echo wp_get_attachment_url(get_post_thumbnail_id()); ?>" alt="<?php the_title(); ?>"/>

<?php the_title(); ?>

<?php wp_limit_post(39,'...',true);?>...

        Fechar

<?php the_title(); ?>

<?php the_content(); ?>

        Fechar

<?php endwhile?>
<?php else: ?>

Nada Encontrado

Erro 404

Lamentamos mas não foram encontrados artigos.

<?php endif; ?>
<?php wp_reset_query(); ?>

A div post-single é a que vai aparecer quando se clicar no título.
Answer:

$(function () {
    $(document).on('click','.effect-goliath', effectgoliath);

    function effectgoliath(e){
        $this = $(this);
        //$this.siblings('.post-single').css('display','none');
        $this.siblings('.post-single').slideUp();

        //$this.next().css('display','block');
        $this.next().slideDown().one('click','.close',function(e){
            $this.next().slideUp();
        });
    }

});
.post-single {
    display:none;
}

title um

    Fechar

title title title

content content content content

    Fechar

title um

    Fechar

title title title

content content content content

    Fechar

Answer: O div post-single, não tem id ou name. Isso me faz pensar que vc deve estar usando um javascript que localiza a div e mostra ela. Só que, como vc está fazendo um loop para todos os posts em:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

isso quer dizer que todas as div serão renderizadas sem id ou name específico para cada registro. Por isso, quando vc localizar uma div no javascript vai localizar todas e abrir todas.
Precisa achar um jeito de colocar um id em cada uma e fazer o javascript localizar a específica que vc quer abrir.
Se puder mostrar o código javascript que vc usa para abrir a div, talvez possa auxiliar um pouco mais.
Answer: Você pode criar a página single-NOME.php, e atribuir as funções the_content() e o que você quiser (imagem, etc..) para mostra nessa pagina.
Ao clicar na tag  que tem o the_permalink() ele vai direcionar automaticamente você para o single.
O Wordpress entende tudo isso de forma automática.

Chamar post na página que é mostrado


How can I customise horizontal menu prestashop module

Question: I would like to edit the prestashop module (Top horizontal menu v1.3) I have some categories setup so I have Parent>Child, Child on the menu. I would like to disable the link on the parent category so that it does not link to a page only the child categories link to pages.
Thx for the help.
Comment: You should probably add a prestashop tag to target the right people to answer this
Answer: I'm not experienced with Prestashop, but thought I would provide some sort of feedback anyway.
As a rule of thumb, whenever I'm making a parent>child navigation I like to make the parent link to a [parent] landing page, or if possible a request to the same page on the server which modifies the navigation output on the server side.  This way, if a client has Javascript disabled, or if there is ever a bug in your Javascript, it does not render your navigation useless.
Might be something to think about.  I don't think any item in a navigation should not link to somewhere.
Sorry I couldn't provide any specific help regarding Prestashop.


Google Maps RichMarker Event

Question: I have events working fine in Chrome and IE10 for Google Maps (APIv3) and RichMarkers. Problem is, the same code borks on Firefox19 with event undefined. So, this code works on Chrome and IE10...
<code>google.maps.event.addListener( marker, 'mouseover', function(event) {
        console.log(event);
});
</code>
But not on Firefox. Interestingly, attaching a CLICK event to the map object does work as  you'd expect. The event object is visible within the called function in all browsers. So, does anyone have any idea as to how to fix this? I really need to pass the event object onwards as I have funcs that use it for positioning and so on.
Normally, I'd get around this using jQuery to attach the events, but this is not an option here.
Cheers
CT
Answer: There is no mouseover-event : http://google-maps-utility-library-v3.googlecode.com/svn/trunk/richmarker/docs/reference.html
Apply the mouseover-event to the content of the marker(the content must be a node)
Comment: OK I've tried to do this, before passing the content to the RichMarker, with no apparent success. I guess its processing the element on handover to RichMarker. So I'll try applying the events after RichMarker init and see how that goes.

Google Maps RichMarker Event


Likelihood and Prior density scales

Question: I have a question about priors and likelihoods and their visualisation.
A Bernoulli likelihood is $$\theta^{N_1}(1 - \theta)^{N_0}$$
where $N_1$ and $N_0$ are number of success and failures, respectively.
I want to visualise (in R) a conjugate Beta prior $Beta(2, 2)$ and Likelihood:
N_1 = 4
N_0 = 1

N = N_1 + N_0

curve(dbeta(x, 2, 2),
      col = 'red')

So far so good, but when I try to add the Likelihood function:
likelihood = function(theta) theta^N_1 * (1 - theta)^N_0
curve(likelihood,
      add = T)

They are definitely on different scales. But what multiplication constant am I missing here? Thanks.
Answer: First of all, in this case, you have the likelihood function of a discrete random variable, so it shows probabilities between zero and one, and the prior is here a continuous random variable with a probability density function that doesn't have an upper bound. Probability density function shows "probability per foot" and it depends on the units of the variable. Even if you had two probability density functions, their units would not be the same, but here there is no reason to expect them to have the same units.
Second, as you noticed, you are not using a normalizing constant for the likelihood, so it doesn't integrate to unity and can take any units. Normalizing constants are not needed for optimization or sampling. You would need them for applying the Bayes theorem directly.
For plotting, you can always re-scale one of the functions by multiplying it by some constant, so they have comparable height on the plot.
Comment: Thanks! Yes, I know that normalisation is not needed for sampling, was just wondering in this particular analytical case. I've realised that if I divide the likelihood function by $\Gamma(N_1 + 1, N_0+1)$ it scales it appropriately. I guess it simply transforms the likelihood into a Beta distribution?
Comment: The first reason is misleading: densities do have units of measurement and, when these likelihoods are properly normalized, the densities can legitimately be compared.  Only the second reason (lack of a normalizing constant) is a valid explanation.
Comment: @whuber not sure what you are trying to say. They wouldn't have comparable height on the plot, even if properly normalized. Sure, the difference won't be that extreme, but they won't be the same. Depends on what you mean by "comparing" them and the point of the visualization.
Comment: @Tim On the contrary, they *would* have comparable heights.  Otherwise, normalization can't even make sense: since both plots have identical areas in identical units and span identical horizontal axes in identical units, their heights are comparable, too, and are in identical units.
Answer: You could try a log scale for the $y$-axis, so the following shows

your prior distribution in red
your likelihood in black
your posterior distribution in blue

You can see the peak of the posterior distribution is further left than the maximum likelihood position
curve(dbeta(x, 2, 2), log="y", ylim=c(0.001,5), col = 'red')
N_1 = 4
N_0 = 1
curve(x^N_1*(1-x)^N_0, add = TRUE, col="black")
curve(dbeta(x, 2+N_1, 2+N_0), add = TRUE, col="blue")

Likelihood and Prior density scales


Dealing with missing data - glmer in lme4 package

Question: I have an unbalanced data set / data set with missing values, consisting of 20 submersible acoustic receivers that have been range tested on 8 days (Both receiver ID and Day are treated as random effects in my model). My aim is to test the effects of multiple environmental variables on the detection range of these receivers. Unfortunately, due to technical issues, a total of 5 receivers could not be tested every day (e.g., 2 receivers could not be tested on 2 days, 3 could not be tested on 1 day).
What would be the right way to proceed? I have 2 choices: 1) reduce data set (exclude all receivers that are not tested on every day), or 2) work with full data set, including missing values.
The first choice is easy, but may not be the best choice (as far as I've read online). besides, collected data will be thrown away.. The second choice however seems more difficult to work with. I read that glmm in the lme4 package can deal with missing values, however, the only thing it does is automatically exclude all rows that contain NAs.
So let's say I choose the second option, and let the model run with missing values that automatically get deleted. How would this affect hypothesis testing? In other words, is the interpretation of p-values just as straightforward as when it would be a balanced design?
[EDIT: I worked out the full data analysis that excluded those receivers for my masters project in order to maintain a balanced data set, however for a publication I would like to analyse my data using the second choice, as I think it's a better one. There's not much literature surrounding this subject as far as I'm aware, hence my post to this forum.]
Comment: Why not just excluding the actual missing data? If you format your data with columns `ID`, `Day`, environmental variables, response, everything should be fine to just omit the missing measurements, keeping in the other measurements on those IDs.
Comment: Thank you for your reply. To be very clear, by omitting the missing data I can safely proceed with hypothesis testing in exactly the same way as when I would be having a balanced data set?
Comment: More or less, yes. I don't know what methods you were using before, but for models like this it's generally accepted that the most accurate confidence intervals are obtained by bootstrapping, e.g., by using `lme4::confint()` with `method = "boot"`. That method will not care if your data is balanced or not.
Comment: Thank you, I haven't used any method before I'm afraid, just hypothesis testing by means of finding the minimum adequate model. I will look into it in more detail.
Answer: Turning my comments into an answer as they seem to have answered your question...
Just exclude the actual missing data. If you format your data with columns ID, Day, environmental variables, response, everything should be fine to just omit the rows where an ID is missing a measurement on a certain day, still keeping the other measurements on those IDs.
For inference, you'll get the best accuracy using bootstrapped estimates, (lme4::confint() with method = "boot" works well -- you'll need to install the boot package for this to work). If you want more info on that, I'd recommend Faraway's Extending the Linear Model with R, section 8.2. The lme4 package has been considerably updated since Faraway's book's printing, you can see the accompanying transition guide. The principles, of course, remain the same.
Comment: @MvZB: no it doesn't.
Comment: This would be the way I would do it, but I want to emphasize that your data needs to be in the 'long' or 'narrow' format as opposed to wide. This way you don't drop measurements that you do have data for. See [data formats](http://en.wikipedia.org/wiki/Wide_and_narrow_data)
Comment: Thanks Benjamin, I have it in the 'long' format. I made this mistake some time ago on a different project, but I learned from it :) Better to prevent than to repair wrongly formatted data frames.
Comment: I forgot to mention that I'm trying to fit a binomial and poisson GLMM. Does that matter for the explanation you gave earlier?
Answer: You must create an indicator variable as control in your model: 1 for acoustic receiver in the missing day and 0 for complete data. Repeat the code for the same acoustic receiver in all its observed and unobserved days (in wide format data base, before converting to long format). You can do it for any missing day or one indicator variable for each missing day separately or grouping days as you consider important. If the indicator variable has no statistic significance, missing data is unimportatnt for the model, but statistic significance shows that the nonobservation is due your dependent variable or vice-versa.
Comment: I have tried to improve some of the English, but could you clarify "nonobservation is due your dependent variable or vice-versa"?


How to make working TFTP server on CentOS 6.2

Question: I'm trying to setup TFTP server on CentOS 6.2.
The /etc/xinet.d/tftp configuration file is the following:
service tftp
{
    disable = no
    socket_type     = dgram
    protocol        = udp
    wait            = yes
    user            = root
    server          = /usr/sbin/in.tftpd
    server_args     = -s /tftpboot -vvv
    per_source      = 11
    cps         = 100 2
    flags           = IPv4
}

The selinux and firewall are disabled.
The /etc/hosts.allow and /etc/hosts.deny files are empty.
When I'm trying to get a file from the TFTP server, the file transfer always failed and I see the following errors into /var/log/messages
Jul 11 03:16:53 localhost xinetd[4155]: xinetd Version 2.3.14 started with libwrap loadavg labeled-networking options compiled in.
Jul 11 03:16:53 localhost xinetd[4155]: Started working: 1 available service
Jul 11 03:17:00 localhost xinetd[4155]: START: tftp pid=4157 from=192.168.10.3
Jul 11 03:17:00 localhost in.tftpd[4158]: RRQ from 192.168.10.3 filename 1
Jul 11 03:17:00 localhost in.tftpd[4158]: sending NAK (0, Permission denied) to 192.168.10.3
Jul 11 03:17:01 localhost in.tftpd[4159]: RRQ from 192.168.10.3 filename 1
Jul 11 03:17:01 localhost in.tftpd[4159]: sending NAK (0, Permission denied) to 192.168.10.3
Jul 11 03:17:03 localhost in.tftpd[4160]: RRQ from 192.168.10.3 filename 1

The tftpboot directory permissions are (output of the ls -l command):
drw-rw-rw-.   3 root root  4096 Jul 11 03:32 tftpboot

I also see that the tftpboot directory is shown (by ls -l) with green background (unlike other files/directories) (Why? As I know the green background is for sticky bit only).
What I did wrong? How can I make TFTP server working?
Comment: The green background in `ls -l --color` means that the file or directory is world writable.
Answer: Your /etc/xinet.d/tftp configuration file is correct.
The permissions of /tftpboot should be 755 or drwxr-xr-x.
Make sure chkconfig --list shows tftp enabled under xinetd.
xinetd based services:
        chargen-dgram:  off
        chargen-stream: off
        daytime-dgram:  off
        .
        .
        rsync:          on
        tcpmux-server:  off
        tftp:           on

Comment: Definitely need +rx for directories.
Comment: old thread i know - but suspect OP eventually had to mess with selinux settings. if 'setenforce 0' alleviates the issues, there are selinux issues with /tftpboot
Answer: I've run into this a couple of times.
Verify /etc/xinetd.conf to see if your server is named to allow access to the xinetd daemon and check /etc/host.allow to see if tftp and in.tftpd is allowed on your network.
Answer: We went through and did all of the above (have run tftp many times) and could not get it to work on CentOS7.  Write Permisson problem no matter what we did.  Finally took @justjeff suggestion and "setenforce 0" and it worked.
kernel has all the latest patches.
Issue with selinux again.


uploadFile primefaces

Question: O método abaixo, junto com meu jsf, faz o upload de um arquivo .bat para uma pasta dentro do meu projeto, até ai funciona normal, o problema é que quando vou ver a pasta onde está o arquivo, ele esta lá, só que com 0kb, abro ele e não tem nada, alguém sabe como resolver? Abaixo meu método:
<code>  public void handleFileUpload(FileUploadEvent event) throws SQLException {
        this.arquivo = event.getFile();
        DirControle dir = new DirControle();
        String directory = dir.selectedDir_CB().toString().replace("[", "").replace("]", "");
        String nomeArquivo =arquivo.getFileName();
        try {

            byte[] arq = arquivo.getContents();

            File file = new File(directory +"\\"+getDestino()+ "\\" + nomeArquivo);

            try ( // esse trecho grava o arquivo no diretório
                FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(arq);
                fos.flush();
                fos.close();
                FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, message); // mensagem pra saber se ouve sucesso

            }

        } catch (Exception ex) {

            ex.printStackTrace();
            System.out.println(ex);
        }

meu form de upload:

<h:form class="upload" >
                            <p:fileUpload fileUploadListener="#{upload_file.handleFileUpload}" mode="advanced" dragDropSupport="false"
                                          multiple="true" update="messages" sizeLimit="100000" fileLimit="100" allowTypes="/(\.|\/#_)(gif|jpe?g|png|bat|rar)$/"
                                          />

                            <p:growl id="messages" showDetail="true" />
                        </h:form>
</code>
Answer: Para mim deu certo, fazendo desta maneira, veja se resolve o seu problema.
<code>ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
String realPath = context.getRealPath("/");
File file = new File(realPath + "/import/");
if (!file.exists())
{
    file.mkdirs();
}

byte[] arquivoByte;

try (FileInputStream fileInputStream = (FileInputStream) event.getFile().getInputstream())
{
    arquivoByte = new byte[(int) event.getFile().getSize()];
    fileInputStream.read(arquivoByte);
}

String fileName = realPath + "/import/" + event.getFile().getFileName();
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(arquivoByte);
fileOutputStream.flush();
fileOutputStream.close();
</code>

uploadFile primefaces


android.helpers unit not found

Question: I am trying to use the Unit Androidapi.Helpers, but when I included it in the USES delphi cannot compile the project. I am using Delphi XE 8 and Windows 7.
Delphi shows me the following error: [dcc32 Fatal Error] Unit2.pas(8): F2613 Unit 'Androidapi.Helpers' not found.
But if I search in my folders I can locate this unit at: C:\Program Files (x86)\Embarcadero\Studio\16.0\lib\android\debug.
How can I fix that?
Comment: @aalmeidasp: You really should not add RTL source folders to your project. Strive to use the pre-compiled RTL DCUs instead of the RTL source `.pas` files directly.
Comment: Let's keep the comments constructive and civil please.
Comment: Does the compile find other Android related units? What is your build target? I hope it's Android.
Comment: You should not need to change anything. This should work out of the box surely.
Comment: Hi Ken, yes the file is located at C:\Program Files (x86)\Embarcadero\Studio\16.0\source\rtl\android. But how can I add the folder tothe project Library, can you explain what is the way to do that?
Comment: I got it. It is working now. Thanks Ken, I add the folder to the project library. Thanks a lot.
Comment: @aalmeidasp Please don't add the RTL source folder to your library path, or indeed the source file to the project. You need to make sure that the compiler can find the compiled DCU file shipped with the compiler
Answer: The Androidapi.Helpers unit still exists in XE8.  Double-check your search path configuration, you are probably missing an entry for the folder that contains the DCU that Androidapi.Helpers was compiled into.  Also note that there is a FMX.Helpers.Android unit as well.
Answer: You can use like this;
Androidapi.Helpers.SharedActivity.startActivity(Intent);

android.helpers unit not found


Reconciling two definitions of uniform integrability

Question: Take a family $F$ of measurable functions on $\mathbb{R}$, then $F$ is uniformly integrable if:
Definition 1 (Royden): For each $\epsilon >0$, there is a $\delta>0$ such that for each $f\in F$, if a Borel set $I$ is such that $\lambda(I)<\delta$ (Lebesgue measure), then $\int_I |f|<\epsilon$.
Definition 2 (Billingsley): The following holds uniformly: $\lim_{a\to\infty}\sup_n \int_{|f|\geq a} |f| =0$.
I can easily see how definition 1 yields definition 2, but have trouble seeing the reverse direction. My guess is we look at $(-\infty, -a]\cup [a,\infty)$ to construct $\delta$ as responding to $\epsilon$, but unsure on the exact approach.
Comments and questions(that I'll leave here but personally expand upon later): Here is a definition of tightness (from my course notes) for random variables on standard $\mathbb{P}$-spaces:

A family of random variables $\{Y_\alpha| \alpha\in \mathcal{S}\}$ is tight if for $\epsilon>0$ there exists a compact $K$ such that $\mathbb{P}(Y_\alpha \notin K)<\epsilon$ for any $\alpha$. How does this tie into uniform integrability?
- Tightness of a family of measures: $\mu_n(\{x||x|>u\})\to 0$ as $u\to\infty$
Tightness of a family of functions suggest, more or less, that such functions "don't escape to infinity", or rather that their "escape to infinity" is arbitrarily small and they can therefore be sufficiently approximated on a set $E$ of finite measure.
Example of not tight (but uniformly integrable) functions: $f_n = \mathbb{X}_{[n,n+1]}$
Example of not uniformly integrable (but tight) functions: $f_n = n \mathbb{X}_{[0,1/n]}$
From this, we see that tightness is a "horizontal" constraint. See Royden's Vitali Convergence Theorem, finite and general cases. On the other hand, uniform integrability is a "vertical" constraint.
Next question: what is the relation between the aforementioned concepts and the $L^p$ spaces? In particular, we know that perhaps due to non-tightness, we may see functions that converge pointwise in $L^1$ to a $f$, but not weakly to it in $L^1$.
Comment: [Related](https://math.stackexchange.com/q/4437079/121671)
Answer: Choose $a$ such that $\sup_f\int_{|f|>a} |f|<\epsilon$. Then for any $I$,
$$ \int_I |f| \le \int_{|f|>a} |f| + \int_{(|f|\le a) \cap I} |f| < \epsilon + a \lambda(I)$$
So if we pick $\delta = \epsilon/a$ we get for $I$ with $\lambda(I)<\delta$ that $\sup_f\int_{I} |f|\le2\epsilon$, QED.
Comment: Of course, that makes sense. Thanks!
Comment: @Calvin Khor: It makes sense to my brain now. And it's much appreciated.
Comment: @Calvin Khor  Thanks for your explanation but I still need help understanding it if you don't mind. I understand that without the $\cap{I}$, then it would just be $ \lt \epsilon$. But, when you put the $\cap$ there, does that mean that the integral is over the intersection of the two sets or that the integral is over both of the sets $|f| \le a$ and $I$. Thanks and I  really appreciate your help.
Comment: Also, is the $n$ in Billingsley's definition, just a typo ? That confused me also. Thanks again.
Comment: @markleeds yes, the intersection symbol means the integral is over the intersection of the sets. It is simply the Lebesgue integral $\int_A |f|$ with  $A= \{x \in \mathbb R : |f(x)|\le a \} \cap I$. And the $\sup_n$ I guess should be $\sup_{f \in F}$ but I didn't check Billingsley
Comment: Hi Calvin: Thanks for your help. But that's what confuses me.  If it's the interesction, then that set is smaller than just $\{x \in \mathbb{R}: |f(x)| \le a\}$, so how can one put the $\epsilon$ on the other side ? Thanks and apologies for so many questions.
Comment: @markleeds $$\int_I |f| = \int_{ (|f|\le a)\cap I} |f| + \int_{(|f|>a) \cap I} |f| \le \int_{ (|f|\le a)\cap I} |f| + \int_{|f|>a } |f|$$ and $$\int_{(|f|\le a)\cap I} |f| \le\int_{(|f|\le a)\cap I} a \le \int_I a = a\lambda(I)$$


Erro >> TESTE500K.c:(.text+0x8f): undefined reference to `INSERE' <<

Question: Galera, estou tentando criar uma lista mas está dando esses erros
TESTE500K.c:(.text+0x8f): undefined reference to `INSERE'
TESTE500K.c:(.text+0xa5): undefined reference to `IMPRIME'
[Error] ld returned 1 exit status
Teria que fazer com String (char*) que é outro problema, mas resolvi testar primeiro com char só que não está funcionando.
    #include <stdlib.h>
    #include <stdio.h>

    struct agenda {
        int tel;
        char nome;
        struct agenda *prox;
    };
    typedef struct agenda Agenda;
    typedef Agenda *Ponteiro;

    void INSERE (Ponteiro *, int , char);
    void IMPRIME (Ponteiro);

    int main (){
        Ponteiro inicio = NULL;
        int telefone;
        char NOME;
        int escolha;
        printf ("DIGITE: \n 1 para Inserir \n 2 para Imprimir \n 3 para Finalizar \n");
        scanf ("%d", &escolha);
        if (escolha == 1){
            printf ("DIGITE O NOME: \n");
            scanf ("%c", &NOME);
            printf ("DIGITE O NUMERO: \n");
            scanf ("%d", &telefone);
            INSERE (&inicio, telefone, NOME);

        }
        else if (escolha == 2){
            IMPRIME (inicio);
        }
        else {
            return 0;
        }
        void INSERE (Ponteiro *sPtr, int novo_telefone, char novo_nome){
            Ponteiro novo, anterior, atual;
            novo = malloc (sizeof(Agenda));
            if (novo != NULL){
                novo->tel = novo_telefone;
                novo->nome = novo_nome;
                anterior = NULL;
                atual = *sPtr;
                while (atual != NULL){
                    anterior = atual;
                    atual = atual ->prox;
                    if (anterior == NULL) {
                        novo->prox = *sPtr;
                        *sPtr = novo;
                    }
                    else{
                        anterior->prox = novo;
                        novo->prox = atual;
                    }
                }
            }
        }
        void IMPRIME(Ponteiro atual) {
            if (atual == NULL)
                printf( "A Agenda esta vazia.\n\n" ) ;

            else {
                printf( "A lista eh:\n");
                while (atual != NULL) {
                    printf("%c", atual->nome);
                    printf("%d", atual->tel);

                    atual = atual -> prox;
                }
            }
    }
    }

Comment: Olá Jorge! Bem vindo ao Stack Overflow! Gostaria que você pudesse editar um pouco melhor sua pergunta, está um pouco difícil de entender, veja [este link](https://pt.stackoverflow.com/help/how-to-ask) para ter uma ideia de como editá-la.
Answer: Após
 else {
        return 0;
    }

deveria haver mais uma chave, que fecharia a função main(). Sem a chave, você está basicamente definindo as funções IMPRIME() e INSERE() dentro de main(), o que é impossível em C, logo as funções não estão sendo criadas, e o seu compilador não sabe o que fazer.
Também é necessário que você remova a última chave do programa, já que é lá que o seu programa está acabando atualmente.
Comment: Na verdade o GCC permite a criação de funções dentro de outras funções como extensão de linguagem, mas essas funções internas não têm acesso ao escopo léxico circundante como as funções em javascript ou lua, por exemplo. A Wikipédia em inglês tem um ótimo artigo sobre [o problema](https://en.wikipedia.org/wiki/Funarg_problem).
Comment: @Wtrmute Obrigado pelas observações.


Transformar decimal em binário PHP

Question: Estou desenvolvendo uma calculadora IP em PHP. O problema é que, quando é digitado uma máscara em decimal, exemplo "255.255.255.0" a máscara em binário é exibida "1111111111111111111111110" pois usei a função do php DECBIN que transforma decimal em binário. O problema é que fazendo dessa forma, os oito bits do último octeto não são exibidos, pois o último número é "0" em decimal. Abaixo está meu código. Alguém sabe de uma forma para transformar com 32 bits?
 $mascara_decimal = array("", "", "", "");
                $mascara_decimal = explode(".", $_POST["mascara"]);
                $mascara_binario = array("", "", "", "");
                echo "Máscara em decimal: ";
                echo $_POST["mascara"];
                echo"
";
                echo "Máscara em binário: ";
                for ($i = 0; $i < 4; $i++) {
                    $mascara_binario[$i] = decbin($mascara_decimal[$i]);
                    echo $mascara_binario[$i];
                }

Answer: Utilize-se do str_pad:
 for ($i = 0; $i < 4; $i++) {
      $mascara_binario[$i] = str_pad(decbin($mascara_decimal[$i]), 8, "0", STR_PAD_LEFT);
      echo $mascara_binario[$i];
 }

Ele preencherá os zeros (0) faltantes.
Answer: Você também pode usar o ip2long() para converter para decimal.
Dessa forma:
$decimal = ip2long('255.255.255.0');

Então pode converter de decimal para binário usando o decbin e depois usar o str_pad como usando na solução do @Everson. Uma outra opção é usar simplesmente o sprintf:
echo sprintf('%032b', ip2long('255.255.255.0'));
// Resultado: 11111111111111111111111100000000

Teste isto

Transformar decimal em binário PHP


Add values of a column and display added result in new table

Question: The table with the data that I have
In the above table I have the columns : weekNumber , weeklyHours ,     points_Rewarded.
There are four employees : a,b,c,d
I have the values for week1,week2,week3, and so on ( I can have data for many more weeks also such as week4,week5, etc)
I want to write a query such that after passing the query I get the total of the weeklyHours and points_Rewarded for each employee in a new table.
The kind of table that the query should give me is here the desired table that I want  after passing the query
Please help me with the query.
Thanks in advance.
Answer: You can use GROUP BY to achieve aggregate values. In your case your are looking for SUM.
Try this
DECLARE @tbl TABLE(EmployeeID INT, EmployeeName VARCHAR(100),WeekNumber VARCHAR(100),WeeklyHours INT,pointsRewarded INT);
INSERT INTO @tbl VALUES
 (1,'a','week1',10,20)
,(2,'b','week1',1,20)
,(3,'c','week1',20,20)
,(4,'d','week1',30,30)
,(1,'a','week2',11,10)
,(2,'b','week2',44,10)
,(3,'c','week2',5,10)
,(4,'d','week2',6,40)
,(1,'a','week3',7,10)
,(2,'b','week3',88,10)
,(3,'c','week3',9,10)
,(4,'d','week3',0,10);

SELECT tbl.EmployeeID
      ,tbl.EmployeeName
      ,SUM(tbl.WeeklyHours) AS Total_Weekly_Hours
      ,SUM(pointsRewarded) AS Total_Points
FROM @tbl AS tbl
GROUP BY tbl.EmployeeID, tbl.EmployeeName

Comment: Thanks a lot.forgot to mention ,I have an Employee_Id column too.What if I want to insert the Employee_id column in the result
Answer: Try with the below query.
      SELECT EmployeeName
           ,SUM (weeklyHours)Total_weekly_hours
           ,SUM (pointsrewarded) TotalPoints
       FROM YourTable
     Group By EmployeeName

Answer: This is a simple GROUP BY. You want to group the employees by name so specify employeename in the GROUP BY statement. Then just select HOW you want to group the other columns. In this case, you want to SUMthem:
SELECT employeename,
SUM(weeklyhours) as total_weekly_hours,
SUM(points_rewarded) as total_points
GROUP BY employeename

Note that you could also use AVG or MIN or MAX in place of SUM depending on what you want to find. The AS clause specifies what you want to call a particular column in your output.
Tested here: http://sqlfiddle.com/#!9/2a96f


Qual framework ou ferramenta posso utilizar para gerar relatórios?

Question: Tenho uma dúvida quanto a geração de relatórios em Java:
No meu caso preciso de uma ferramenta para gerar relatórios diários que possam ser impressos ou exportados.
Qual framework ou ferramenta vocês podem me indicar?
Comment: Cara eu te indicaria JasperReports, mas também te indicaria que você reformulasse sua pergunta, tentando deixa-la um pouco mais completa
Comment: R.Santos tudo bem?
Comment: Teoricamente qualquer string pode ser exportada e qualquer tipo de documento (.docx, .pdf, .html) pode ser impresso. Você precisa descrever melhor o que você quer.
Comment: Eu uso eclipse e estou começando a estudar spring.
Comment: Além disso, o que é que o seu problema tem a ver com Spring? Você colocou Spring no título, mas o corpo da pergunta nada tem a ver com Spring.
Comment: O sistema no qual eu vou desenvolver, precisa gerar relatorios e exportar para excel e isso pode ser por extensao csv, ou em pdf.
Comment: Bom em cima dessas "Vastas informações" a resposta do @KaranAlvesPereira já resolve sua questão
Comment: o sistema vai ser desenvolvido com o framework spring e por isso mencionei ok Victor Stafusa. Sou novato em java, fiz um curso mas nao cheguei a desenvolver uma aplicaçao mais madura ok
Comment: obrigado a todos pela sugestoes e dicas.
Answer: O que normalmente é utilizado para geração de relatórios em java é o Jasper. Já trabalhei também com o Crystal (não recomendo). As duas ferramentas possuem a opção de imprimir ou exportar os arquivos.
Answer: Existe um projeto chamado BIRT Report.
http://www.eclipse.org/birt/


Probability and conditional distribution

Question: I'm finding difficulties in cracking this probability problem. Let's say that we have $n$ players, who are supposed to be part of two teams, red and blue. They are divided with the following procedure. A number $Y$ is chosen randomly from the set $ \left \{1,2,...,n-1 \right\}$, with all values equally likely. Then $Y$ of the $n$ players are chosen to form the red team, with all possible sets of size $Y$ equally likely. The remaining $n-Y$ players form the blue team.
Let's consider a particular player, called player A. I have to find the probability that the team containing player A has size $k$ for $k=1,2,...,n-1$. Moreover, I need to find the mean of the size of the team that contains player A.
After the teams have been chosen, each team selects a captain, who is equally likely to be any member of that team. I have to find the conditional distribution of the size of the team containing Player A, given that Player A is the captain.
The results I get aren't consistent with the data given: maybe I'm setting up the problem badly...
Comment: How are you setting up the problem and what results are you getting?
Comment: It might help to look at the situations with $n=2,3,4$ in detail.  There are few cases to examine, so you can work out all probabilities by making an exhaustive list of all the possible team choices. If you approach your enumeration in an orderly fashion, it will reveal helpful symmetries and relationships.
Comment: I have tried to set up the first step of the problem like this: $P(A \in R | Y=y) = \frac{P(A \in R \cap Y=y)}{P(Y=y)} = \frac{n}{2}$, but I think that I've made a mistake... For the next two steps I don't really know how to proceed...
Answer: ale42, in your comment above you are trying to determine the conditional probability $P(A \in R| Y = y)$ by looking at a quotient.  However in this problem the joint distribution in the numerator is one of the harder things to get at, whereas the conditional probability you were trying to find is much simpler.  So let's focus for now on:
$$
P(A \in R | Y=y).
$$
If $Y=y$, then the Red team will have $y$ out of the $n$ people on it.  There are $\binom{n-1}{y-1}$ options that have player $A$ on the Red team.  Meanwhile, there are $\binom{n}{y}$ total options.  That ratio comes out to
$$
\frac{\binom{n-1}{y-1}}{\binom{n}{y}} = \frac{(n-1)!}{(y-1)!(n-y)!} \cdot \frac{(y)!(n-y)!}{(n)!} = \frac{y}{n}
$$
The much more intuitive way of seeing this is that with each choice $\frac{k}{n}$ of the players end up on the Red team.  So because no player is more likely to end up on the Red team than anyone else, everyone must have probability $\frac{k}{n}$.
Now because of the way this problem (and many problems like this) is set up, the conditionals are easier to work with than the joint distribution.  But once we have the joint distribution we can get whatever we want by summing.  So the questions are, what is the joint distribution?  And what do we want?
I'll help get you started on that.  Ultimately what we care about is the size of teams, and which one player $A$ is on.  Let us call A's team $T_A$.  We could answer the question if we knew:
$$
P(T_A = x, Y=y) = P(T_A=x|Y=y) \cdot P(Y=y).
$$
I think you can work that out.  My question to you is, what is $P(A$ is on a team of size $k)$ in terms of $P(T_A = x, Y=y)$?
Comment: Lower case $y$ in the numerator at the end but that's totally correct.  Now can you answer the last question in my post?
Comment: Ah to be precise.  $P(T_A = R| Y=y)=\frac{y}{n}$.  But $P(T_A = B| Y=y)=\frac{n-y}{n}$.
Comment: @ale42 good now can you use the joint distribution to get the probability that A is on a team with $k$ people on if?
Comment: Whe should have $P(Y=y) = \frac{1}{n-1}$ whereas for $P(T_A = x | Y = y) = \frac{Y}{n}$... Correct me if I'm wrong
Comment: Thus we should have $P(T_A = R, Y= k) = \frac{k}{n(n-1)}$ for the red team, whereas for the blue we should have $P(T_A = B, Y= k) = \frac{n-k}{n(n-1)}$... Anyway the two step forward are much more messing...
Comment: Ok, later I'll try to post a complete solution of the problem! :) thanks for the help!
Comment: Ok, now following the reasoning we should have: $ P(Y = k | T_A= R) = \frac{k^2}{n(n-1)}$ and: $ P(Y = k | T_A= B) = \frac{(n-k)^2}{n(n-1)}$ How can I get the size of a generic team? Should I use convolution?
Comment: Can you explain why you want to know $P(Y=k | T_A = R)$?  I asked a question in my answer and you still have not addressed it.  Using $P(T_A = x, Y=y)$ can you express the probability that player $A$ is on a team with $k$ people?
Comment: Yes, the probability should be $ P(Y = k | T_A) = \frac{k^2}{n(n-1)}$  by applying the law of conditional probability distribution...
Comment: This is not correct and I don't know what you mean by the "law of conditional probability distribution".  What has to happen, for player A to be on a team with $k$ people.  Please answer in words.  How can it happen?
Comment: He can be choosen with probability $\frac{1}{k}$
Comment: Please try to give me an answer in words only because you are not grasping the math yet.  You can't get the math if you can't translate what the question is asking.  **How** can player A end up on a team with $k$ people.  In what scenarios will that occur?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/29502/discussion-between-jlimahaverford-and-ale42).


Obter conteúdo que está antes do número usando regex

Question: $MinhaString = "Aventura, Fantasia, Ação 25 de maio a 31 de maio"

Tentei fazer assim, só que não funciona.
$Genero = strstr ($MinhaString,"/[^0-9]/",true);

Preciso apenas do "Aventura, Fantasia, Ação". A data não é estática.
Answer: Você pode fazer isso usando o método preg_match
preg_match('/^([^0-9]+).*/', "Aventura, Fantasia, Ação 25 de maio a 31 de maio", $matches);
print_r($matches);

A regex '/([^0-9]+).*/' vai pegar todos os caracteres não numerais antes do primeiro número.
Na sua tentativa você esqueceu de colocar na regex o match para o resto da string.
Comment: Alterei para incluir a ancora no começo da string.
Comment: Eu ainda poria o âncora antes do conjunto. Mais sobre o assunto : http://aurelio.net/regex/guia/ancoras.html#2_3
Comment: sua regex já funcionaria sem o método preg_match amigo!
Answer: Essa regex vai funcionar, ela captura todo o conteúdo não numérico do início da linha até a primeira ocorrência de um dígito.
^\D*(?=\d)

Explicação:

^ indica o início da linha.
\D* faz a regex capturar todos os caracteres não numéricos de forma greedy.
(?=\d) isso é um positive lookahead com dígito, indica que só deve capturar o \D* se houver um dígito depois do grupo de captura e nesse caso já faz a regex parar a captura.

Troque sua RegEx por essa e vai funcionar.
Aqui tem um teste


how to comment individual image in popup form drupal 7?

Question: I have created view to display images and when I click on the image it gets displayed in pop-up form. I want to allow user to comment on image in pop-up form only so i have displayed comment form with php code. But its not working properly. It displaying preview button instead of comment. And when I click on preview it redirects to the image node page which should not be happened. I want it to work properly please help me suggesting solution. Hope image below will help you to understand what actually I have done.
Answer: First, in your content type edit page, make the "Preview Before Submit" option disabled or optional. Once you do that you will see the Submit button.
Even you make the Submit button appear, the same will happen and user will be redirected to the actual page with no modal display. From the pattern of your modal window, I guess you are using colorbox plugin. If yes then you need to open this colorbox as an iframe option.

So even you submit the page, the page will not be redirected outside of modal.
EDIT #1
Then I think you may have to alter the form you are using and check for form elements with a debug() function. Then I guess in your form_alter you can do the following,
<?php
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['type']) && $form_id == 'mymodule_node_form') {
      // Hide the preview/submit button.
      $form['actions']['preview']['#access'] = FALSE;
  }
}
?>

Have a check on the variable that sets the preview, by
variable_get('comment_preview_' . $node_type);

If it's set then can be disabled via,
variable_set('comment_preview_' . $node_type, DRUPAL_DISABLED);

I hope this will be helpful to your cause.
Comment: Yes I am using colorbox plugin. And also disabled preview option on content type edit page but still the preview button is visible. This might be because of the code I have used to print comment form. Hope it will help you.      print drupal_render(drupal_get_form("comment_node_node_gallery_item_form", (object) array('nid' =>$row->nid)));
print render($content['comments']['comment_form']);
Comment: Have a look at the EDIT#1. This may help you.
Comment: Yes its working fine for some extent that is at the place of preview button now its displaying submit button which is working absolutely fine. Thanks Aneek, But after commenting its redirecting user to the node page of the image.


How to export path breadcrumbs

Question: I see written everywhere that Path breadcrumbs https://www.drupal.org/project/path_breadcrumbs can be exported via features. But I am unable to see any Path breadcrumb option when I'm creating a feature, nor I see any export thing in Path breadcrumbs settings.
Do you know where/how?
Answer: Features: Check if you have Path Breadcrumbs module checked in Features Settings (screenshot below). If it was checked and you still do not see it in the Features components list than something else is amiss.

Export: As for the direct export of Path Breadcrumbs, you can find "export" link while clicking on "edit" in path breadcrumbs actions list (screenshot below)

Hope this helps.
Comment: @Francesc you could do it manually similar to views. The hook to add the export of breadcrumbs settings would be `hook_path_breadcrumbs_settings_info()`. Still a mystery why path breadcrumbs are not shown as a component..
Comment: Oh I see the export option (in my defence, I am working with a Japanese web site). So that is one thing. But I still don't see anything when I'm creating a new feature, even though I made sure I have the checkbox checked as in your first screenshot. But I guess I can manually create a file with the export option and put it inside the feature, as like views works with features?

How to export path breadcrumbs


Var and Expected Shortfall

Question: I am struggling to find an example which has 2 random variables (say L1 and L2) with same VaR but different Expected Shortfall.
Comment: Have you tried discrete distributions?
Comment: This is for homework?
Answer: There's really nothing unusual about that. A simple example would be to just take a standard normal distribution and a distribution with fatter tails, say a Student-t distribution, and just shift it so their VaR's line up.
More explicitly, fix the level $\alpha$ and take:
$$L_1 \sim \mathcal{N}(0,1)$$
And:
$$L_2' \sim \mathcal{T}_\nu$$
Then define:
$$L_2: = L'_2 + (q^{(1)}_{\alpha}-q^{(2)}_{\alpha})$$
where $q^{(i)}_{\alpha}$ is the $\alpha$-quantile for $L_i$. Then:
$$P[L_2 \leq q^{(1)}_{\alpha}] = P[L'_2 + (q^{(1)}_{\alpha}-q^{(2)}_{\alpha})\leq q^{(1)}_{\alpha}] = P[L_2'\leq q^{(2)}_{\alpha}] = \alpha$$
So, the VaR of $L_1$ and $L_2$ is the same for this value of $\alpha$.
alpha <- 0.01
nu <- 4
adj <- (qnorm(alpha)-qt(alpha,nu))

xs <- seq(-5,0,length.out=1000)

plot(xs,pnorm(xs),log="y",type="l",col='blue', main = "CDF",ylab="Probability",xlab="")
lines(xs,pt(xs-adj,nu), col = 'red')
abline(h=alpha)
legend("bottomright", legend = c("L1 ~ N(0,1)","L2 ~ T_nu + adj"),col=c("blue","red"),lty=1)

However, the expected shortfall is not the same because $L_2$'s left tail is fatter, so more of the mass is concentrated further to the left of their common $\alpha$ quantile, so ES will be larger. Referencing the formulas here, in this specific example you can compute that:
es1 <- dnorm(qnorm(alpha))/alpha
es2 <- -adj+(nu+qt(1-alpha,nu)^2)/(nu-1) * dt(qt(1-alpha,nu),nu)/(alpha)

c(es1, es2)
# [1] 2.665214 3.799985

The VaR is legitimately fundamentally not informative about the mass to the left of that quantile, at all. This is a more contrived example, but consider $L_1$ with any distribution whatsoever, then define $L_2$ as having the same distribution to the right of the VaR, and then concentrate all the mass on the left at an arbitrarily distant point. This doesn't change the VaR, but you can get an arbitrarily large difference in expected shortfall.
The VaR cannot distinguish between the normal "it could get a little bit worse than this" scenario and the "if it gets any worse than this, the world will end" scenario.

Var and Expected Shortfall


Route [/download] not defined. (View:

Question: hi I am downloading data directly from URL, but when I try to make a button that when I click on it then it becomes downloadable then it said:
Route [/download] not defined.

D:\xampp\htdocs\laravel\webpro5\resources\views\showrecord.blade.php

code of button:

      Export to Excel

route:
  Route::get('/download', function(){
    return Excel::download(new ExcelsExport, 'importpdfs.xlsx');
  });

Answer: The route() function expects a single parameter that matches a named route. Currently, you don't have a named one. Either use the url() function:
...

or name your route:
Route::get("/download", ...)->name("download");

Answer:

  Export to Excel

or

      Export to Excel

route helper is used for named routes.
Additionally you can do
Route::get('/download', 'Controller@Method')->name('download');

then you can use the route helper like this:
{{ route('download') }}

Route [/download] not defined. (View:


Applying styles to tables with Twitter Bootstrap

Question: Does anyone know if it is possible to apply styles on tables with Twitter Bootstrap? I can see some table examples in some older tutorials but not on the Bootstrap site itself.
I've tried to set it up but the tables in my page have almost no styling applied to them.

            #
            First Name
            Last Name
            Language

            1
            Some
            One
            English

            2
            Joe
            Sixpack
            English

What classes do I need to apply?
Answer: Bootstrap offers various table styles. Have a look at Base CSS - Tables for documentation and examples.
The following style gives great looking tables:

  ...

Answer: Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it'll look nice.  You might use it on your data reports, showing information, etc.

You can use :
basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables

Striped rows Table :

    #
    Name
    Address
    mail

    1
    Thomas bell
    Brick lane, London
    firstname.lastname@example.com

    2
    Yan Chapel
    Toronto Australia
    firstname.lastname@example.com

    3
    Pit Sampras
    Berlin, Germany
    Pit @yahoo.com

Condensed table :
Compacting a table you need to add class class="table table-condensed" .

    #
    Sample Name
    Address
    Mail

    1
    Thomas bell
    Brick lane, London
    email@example.com

    2
    Yan Chapel
    Toronto Australia
    firstname.lastname@example.com

    3
    Pit Sampras
    Berlin, Germany
    Pit @yahoo.com

Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial
Answer: You can also apply TR classes: info, error, warning, or success.
Answer: Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.

NATO Phonetic Alphabet

        Letter
        Phonetic Letter

    A
    Alpha

    B
    Bravo

    C
    Charlie

Answer: bootstrap provides various classes for table

Answer: you can Add contextual classes to every single row as follows:

You can also add them to table data same as above
You can set your table size by setting classes as table-sm and so on.
You can add custom classes and add your own styling:

      First Name
      Last Name

      Asdf
      qwerty

This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.


Solve the Poisson Equation on a Riemannian Manifold

Question: Imagine that I have a field that obeys to the Poisson equation. To solve the equation, in my bag of tools I only have the divergence theorem or the Fourier/Laplace transform. They usually are enough to tackle the problem and I'm happy with myself...
Let's then say that the field lives on a Riemannian Manifold other than Euclidean. Let's take for example  the 2-torus. Well for starters I can't use the divergence theorem since I can't really define a border at which the field (actually the gradient) is constant... I am then left with the Fourier transform technique. But, I only know the Fourier Transform on Euclidean geometry... Then, I started studying the way of generalizing the Fourier transform to another Riemannian Manifold. In general this is not possible but in some cases it is... But then, after much browsing, I read that even if one could define a FT on the manifold that wouldn't help me solve the problem...
After this very long introduction: Is that true? If it is: How would one solve the Poisson equation?
Comment: Related question by OP: http://physics.stackexchange.com/q/56551/2451
Answer: I suggest you to take a look on this book in page 104. Also, you can find a lot of information on this one, in particular, in the part where he treats Poincare inequality (Theorem 2.10) and Proposition 2.6.
Comment: I believe that what you're telling (showing) me is the necessary condition for a solution to exist (If I didn't read the references correctly please tell me). I've seen that in lots of places but not one has actually solved the problem on a particular manifold...For example on a cylinder with a point source it shouldn't be too difficult (although I can't solve it =/)...

That's what I asking. A way of solving the equation.
Comment: Dear @PML, please take a look in page 104 of Aubin, in particular, take a look in item $\gamma$ after $\beta$. There he solves the equation by using the classical variational setting, i.e. a) define the energy funcional; b) show this functional is bounded below and take a minimizing sequence; c) show this sequence converges.
Comment: Oh I see. I'm sorry, I, clearly, didn't look thoroughly enough the references that you indicated. I'll take a look again. Thank you for you help.


How to prove that a sequence is Cauchy

Question: How do I show if $x_n = \frac{n^2}{n^2 -1/2}$ is a Cauchy sequence? (using the definition of Cauchy sequence)
My attempt: A sequence is Cauchy if $ \forall \epsilon>0$ $ \exists N \in \mathbb N$ $\forall m,n \geq N$ :|$x_n -x_m$|$\leq \epsilon$
|$x_n -x_m|=|\frac{n^2}{n^2 -1/2} -\frac{m^2}{m^2 -1/2}$| $\leq|\frac{n^2}{n^2 -1/2}-1|+|1-\frac{m^2}{m^2 -1/2}|= 1/2|\frac{1}{n^2 -1/2}|+1/2|\frac{1}{m^2 -1/2}|$
$1/2|\frac{1}{n^2 -1/2}| \leq \epsilon$ and also $1/2|\frac{1}{m^2 -1/2}| \leq \epsilon$
So $1/2|\frac{1}{n^2 -1/2}|+1/2|\frac{1}{m^2 -1/2}| \leq 2 \epsilon$
if we choose $N \in \mathbb N$ such that $N >\sqrt{\frac{\epsilon}{2}+\frac{1}{2}}$
Answer: Easier:
$$x_n = \frac{1}{1-\frac{1}{2n^2}} \stackrel{n \to \infty}\longrightarrow 1$$
and convergent sequences are Cauchy sequences.
Answer: Your penultimate line is unnecessary. You actually want $N>\sqrt{\frac{1}{2\epsilon}+\frac12}$ to ensure $|x_n-x_m|<2\epsilon$. Usually, we'd instead prove $|x_n-x_m|<\epsilon$ is achievable, with $\min\{m,\,n\}>\sqrt{\frac{1}{\epsilon}+\frac12}$.
Answer: In this case, you can easily conclude that it is Cauchy because it converges for $n \rightarrow \infty$
Answer: The definition you posted is correct. Note though that
$$
x_n
 = \frac{n^2}{n^2-1/2}
 = 1 + \frac{1/2}{n^2-1/2},
$$
and it's clear this is a sequence which decreases to $1$, so $x_{n+1} < x_n$ for all $n$. (You could at this point claim that since the sequence is convergent, it is also Cauchy, but if you need a proof from the fundamentals, read on).
Assuming $N<m<n$,
$$
\begin{split}
\left|x_m - x_n\right|
 &= x_m - x_n \\
 &= \left(1 + \frac{1/2}{m^2-1/2} - 1 - \frac{1/2}{n^2-1/2}\right) \\
 &= \frac12 \left(\frac{1}{m^2-1/2} - \frac{1}{n^2-1/2}\right) \\
 &= \frac12
    \left(\frac{n^2 - m^2}
               {\left(m^2-1/2\right)\left(n^2-1/2\right)}\right) \\
 &\le \frac12
    \left(\frac{n^2}
               {\left(m^2-1/2\right)\left(n^2-1/2\right)}\right) \\
 &\le \frac{1/2}{m^2-1/2} \left(\frac{n^2}{n^2-1/2}\right)\\
 &\le \frac{1/2}{m^2-1/2} \left(1 + \frac{1/2}{n^2-1/2}\right)\\
 &\le \frac{1}{m^2-1/2}\\
 &\le \frac{1}{N^2}.
\end{split}
$$
Can you find what $N$ you need to pick in terms of $\epsilon$ to have that expression $< \epsilon$ in the end?
Comment: so we need $N> \sqrt{1/ \epsilon}$ right?
Comment: @Bob correct :)

How to prove that a sequence is Cauchy


How do I add a script just above the closing body tag?

Question: How do I add a script on Drupal 8 site/app just above closing body tag?
Vendor provided some JS in the following form:

Asked me to place immediately above .
The script was only to run for Anonymous traffic.
Here's how I did it:
THEME = name of your theme

Removed  from code
Minified using https://javascript-minifier.com/
Created file name-of-my-script.min.js
Uploaded to THEME/js/custom/name-of-my-script.min.js
Added library to bottom of THEME.libraries.yml

name-of-my-library:
  version: 1.0
  js:
    js/custom/name-of-my-script.min.js: {preprocess: false} // {preprocess: false} is responsible for code showing up above

Added the following code to THEME.theme to an already existing function: function THEME_preprocess_page(&$variables) {}

$logged_in = $variables['logged_in'];
    if (!$logged_in) {
    $variables['#attached']['library'][] = 'THEME/name-of-my-library';
}

Cleared cache.

Resourses that helped:

https://www.drupal.org/docs/8/api/javascript-api/add-javascript-to-your-theme-or-module
https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
Comment: Please don't add the answer to the question. Please add it as answer below.
Comment: I see that I need to escape the closing body tag. I don't have edit access (even though I created post) so could admin please help with that? Tahnks.
Comment: Your script get's aggregated by Drupal's core. You will not see it in the rendered page output. You may change the aggregation on /admin/config/development/performance.
Comment: By adding `{ preprocess: false }` property, the script does not get aggregated:

https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#js-properties
Comment: What is your question - does your code solve the problem?
Comment: I was told that asking and answering my own question was a good way to help others on StackExchange; this was my first offering.

I'd edit the post but I no longer see the edit button.

All I have to do is change the heading from 'How to..." to "How do I".
Comment: I found the edit link and made the change to question. Thanks for pointing out.
Comment: Where does this requirement come from? Some library telling you to do it that way? It's probably just fine to have it added to the footer by default.
Comment: There are many ways to add a library to a Drupal 8 website. This is one way; maybe someone will share a different way - and we'll all learn something new.

"How do I add a script on Drupal 8 site/app just above closing body tag?" is the/a question. Respectfully,
Answer: You can achieve this simply by using jquery. If you want to access it from all theme pages you need to add the below line in your global common js file which has access to all the theme pages in the app.
$('body').append('');