mongodb mystery crashes with sigkill under strace

Question: I have a mongodb instance that seems to crash roughly once a day. I don't see any useful information in the mongo log file. All is well and then the process is just crashed with no additional information logged. I ran it under strace in hopes of getting some useful clues until it crashed and got this output:
Wed Apr 17 10:56:39.340 [conn172]               M/R: (1/3) Emit Progress: 2800/4351     64%
Wed Apr 17 10:57:16.696 [PeriodicTask::Runner] task: DBConnectionPool-cleaner took: 16ms
Wed Apr 17 10:57:17.035 [PeriodicTask::Runner] task: WriteBackManager::cleaner took: 17ms
Wed Apr 17 10:57:17.429 [PeriodicTask::Runner] task: DBConnectionPool-cleaner took: 79ms
+++ killed by SIGKILL +++

This is only happening on one specific VM and the rest are fine. Also checked hourly/daily cron jobs in case something was going haywire and killing mongod but no suspects there.
OS: Ubuntu 12.04.2
Mongo: 2.4.1
Anything else I can do to further troubleshoot?
Comment: Any chance that this is an Amazon VM?
Comment: It's a rackspace gen1 VM.
Answer: You are running a Map Reduce job at the time it is killed, is that always the case?
I ask because it sounds like the kind of behavior you get when a watchdog type process decides you are using too much memory and kills the process.  Map Reduce jobs (inline, or those that run on large data sets in particular) tend to push up RAM usage quickly.
SIGKILL is not what you would get if this was the kernel deciding you were Out Of Memory and invoking the OOM killer (that looks like a silent crash and is logged in dmesg).  Hence, that would make me believe that there's something else doing the killing to prevent memory usage beyond a certain threshold.
If you wanted to verify, run db.collection.find().explain() on a large data set and see if that triggers a SIGKILL also.  If so, I don't think this type of VM is suited to running a memory mapped database.
Comment: Hmm, sounds plausible I guess. I'll investigate.


Conduit - Splitting a ByteString source to chunks of bytes

Question: With sourceFile we get a ByteString stream.
With reference to my other question "Combining multiple Sources/Producers into one", I'm able to get a source of (StdGen, ByteString) using ZipSink, sourceFile and a custom source that produces an infinite stream of StdGen.
What I'm trying to achieve is to pair each StdGen with one single byte of ByteString, but with my current implementation, I'm getting one StdGen paired with the whole content of the input file from sourceFile.
I have looked into Conduit.Binary's isolate function, but it doesn't seem to be working for me when I use as follows:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}

import System.Random (StdGen(..), split, newStdGen, randomR)
import ClassyPrelude.Conduit as Prelude
import Control.Monad.Trans.Resource (runResourceT, ResourceT(..))
import qualified Data.ByteString as BS
import Data.Conduit.Binary (isolate)

-- generate a infinite source of random number seeds
sourceStdGen :: MonadIO m => Source m StdGen
sourceStdGen = do
    g <- liftIO newStdGen
    loop g
    where loop gin = do
            let g' = fst (split gin)
            yield gin
            loop g'

-- combine the sources into one
sourceInput :: (MonadResource m, MonadIO m) => FilePath -> Source m (StdGen, ByteString)
sourceInput fp = getZipSource $ (,)
    <$> ZipSource sourceStdGen
    <*> ZipSource (sourceFile fp $= isolate 1)

-- a simple conduit, which generates a random number from provide StdGen
-- and append the byte value to the provided ByteString
simpleConduit :: Conduit (StdGen, ByteString) (ResourceT IO) ByteString
simpleConduit = mapC process

process :: (StdGen, ByteString) -> ByteString
process (g, bs) =
    let rnd = fst $ randomR (40,50) g
    in bs ++ pack [rnd]

main :: IO ()
main = do
    runResourceT $ sourceInput "test.txt" $$ simpleConduit =$ sinkFile "output.txt"

In Conduit terms, I thought isolate will do an await, yield the head of the incoming ByteString stream, and leftOver the rest (put it back to the incoming stream's queue). Basically, what I'm trying to do is chopping the incoming ByteString stream into blocks of bytes.
Am I using it correctly? If isolate is not the function I should be using, then can anyone provide another function that splits it into arbitrary byte chunks?
Comment: Let me see if I understand you correctly. You're saying that you want a separate `StdGen` per `Word8`? In other words, you want a stream of `(StdGen, Word8)`?
Comment: @Michael, that's right.
Comment: @MichaelSnoyman, Would you be able to check the conduit I've written? (`condWord`). Did I just reinvented the wheel since I'd expect `Conduit.Binary` library having something similar (and probably more versatile)
Answer: If I understand correctly, you want something like this:
import System.Random (StdGen, split, newStdGen, randomR)
import qualified Data.ByteString as BS
import Data.Conduit
import Data.ByteString (ByteString, pack, unpack, singleton)
import Control.Monad.Trans (MonadIO (..))
import Data.List (unfoldr)
import qualified Data.Conduit.List as L
import Data.Monoid ((<>))

input :: MonadIO m => FilePath -> Source m (StdGen, ByteString)
input path = do
  gs <- unfoldr (Just . split) `fmap` liftIO newStdGen
  bs <- (map singleton . unpack) `fmap` liftIO (BS.readFile path)
  mapM_ yield (zip gs bs)

output :: Monad m => Sink (StdGen, ByteString) m ByteString
output = L.foldMap (\(g, bs) -> let rnd = fst $ randomR (97,122) g in bs <> pack [rnd])

main :: IO ()
main = (input "in.txt" $$ output) >>=  BS.writeFile "out.txt"

It is probably more efficient to omit map singleton, you may as well use the Word8s directly and convert back to ByteString at the end.
Comment: I noticed that you're not using `sinkFile`. Doesn't this mean that you're not really streaming to your output file, but instead storing it all in memory first and then writing to output using `BS.writeFile`?
Answer: I managed to write a conduit myself (condWord) which splits incoming ByteString into Word8 chunks. I'm not sure whether I'm reinventing the wheel here though.
To get my intended behavior, I simply bolt condWord onto sourceFile.
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}

import System.Random (StdGen(..), split, newStdGen, randomR)
import ClassyPrelude.Conduit as Prelude
import Control.Monad.Trans.Resource (runResourceT, ResourceT(..))
import qualified Data.ByteString as BS
import Data.Conduit.Binary (isolate)
import Data.Maybe (fromJust)

-- generate a infinite source of random number seeds
sourceStdGen :: MonadIO m => Source m StdGen
sourceStdGen = do
    g <- liftIO newStdGen
    loop g
    where loop gin = do
            let g' = fst (split gin)
            yield gin
            loop g'

-- combine the sources into one
sourceInput :: (MonadResource m, MonadIO m) => FilePath -> Source m (StdGen, Word8)
sourceInput fp = getZipSource $ (,)
    <$> ZipSource sourceStdGen
    <*> ZipSource (sourceFile fp $= condWord)

-- a simple conduit, which generates a random number from provide StdGen
-- and append the byte value to the provided ByteString
simpleConduit :: Conduit (StdGen, Word8) (ResourceT IO) ByteString
simpleConduit = mapC process

process :: (StdGen, Word8) -> ByteString
process (g, ch) =
    let rnd = fst $ randomR (97,122) g
    in pack [fromIntegral ch, rnd]

condWord :: (Monad m) => Conduit ByteString m Word8
condWord = do
    bs <- await
    case bs of
        Just bs' -> do
            if (null bs')
                then return ()
                else do
                    let (h, t) = fromJust $ BS.uncons bs'
                    yield h
                    leftover t
                    condWord
        _ -> return ()

main :: IO ()
main = do
    runResourceT $ sourceInput "test.txt" $$ simpleConduit =$ sinkFile "output.txt"

Comment: [concatC](http://hackage.haskell.org/package/conduit-combinators-0.2.5/docs/Conduit.html#v:concatC) will actually do the same thing as `condWord`. A simply approach would also be `awaitForever $ mapM_ yield . BS.unpack`.
Comment: Lovely, and there's a bunch of them at http://hackage.haskell.org/package/conduit-combinators!


SpringBoot Kafka: Clarification on consumer initiated transactions

Question: This link tells us to use @Transactional for 1PC between a DB and Kafka for consumer-initiated transactions.
An excerpt:

the container (configured with a KTM) starts the kakfa transaction

The question is where and how do we configure a container with the KTM? Looked at the code sample here and it seems that the configuration for producer has it configured for transactions:
spring.kafka.producer.transaction-id-prefix=tx-

However, imagine that we do not have the producer or any event generation to kafka in the listener as in:
@KafkaListener(id = "group1", topics = "topic1")
    @Transactional("dstm")
    public void listen1(String in) {
        // COMMENT THIS:
        // this.kafkaTemplate.send("topic2", in.toUpperCase());
        this.jdbcTemplate.execute("insert into mytable (data) values ('" + in + "')");
    }

Now the questions is:

if the kafka transaction is in play?
Would the offsets commit (for the message "in") not happen if the db transaction is rolled back?
Do I need to manually ack for the offsets?
Comment: Ideally, you don't do this at all. Use Kafka Connect JDBC sink rather than Spring JDBC Template
Answer: See the documentation.
For consumer-initiated transactions, the listener container must be configured with a KafkaTransactionManager so the offset can be sent to the transaction.
If you are not sending data to Kafka it makes no sense to use a consumer initiated transaction. Normal Spring transaction management will apply and if the commit fails, the normal container error handling will handle the exception (normally re-seek the record and retry).
If you are consuming and sending to Kafka then the container must start the Kafka transaction, not the producer; otherwise the send won't be rolled back.
Comment: Boot will automatically configure a `KafkaTransactionManager` when you set the transaction id prefix. In addition, if Boot finds a `KTM`, it will automatically wire it into the container factory. To prevent a kafka transaction from being started, you could force the TM to null in the container properties (after boot has done the auto config), or don't use boot to set the `transaction-id-prefix`; instead use `spring.kafka.producer.properties.transactional.id=prefix`. That will still work for producer-only transactions, but will bypass Boot's auto configuration logic for the container.
Comment: Thanks. I understand that from the docs that only the Spring tx mgmt will apply. And  DB tx will be committed before the kafka messages are ack. Please correct me if needed. Also, another reason for asking this question is that we do see Kafka transactions being started. See https://stackoverflow.com/q/74946915/3109248


Create Slack channel programmatically

Question: I don't see it in the documentation, but I was curious if anyone knew of a way within slack app to create a channel programmatically.
Here was my first attempt via slash commands via slackbot, but no success.
curl --data "/open test" https://xxxxxxx.slack.com/services/hooks/slackbot\?token\=xxxxxxxxx\&channel\=%23general

Answer: You can also create new channels directly with the API method channels.create.
See the documentation for more details
Answer: You can create channels via the API using the channels.join method: https://api.slack.com/methods/channels.join.
This method is used to join a channel. If the channel does not exist, it is created.

Hope that helps!

Create Slack channel programmatically


Generate Install Scripts from current Nodes, Views, Fields in Drupal

Question: I have theme with custom content types, views, etc. and i would like to package into a custom module so it can be easy installed in another Drupal instance via MODULE_install().
Currently, Module_install() looks something like this:
<code>function MODULE_install(){
    $t = get_t();
    foreach (_jobs_installed_fields() as $field) {
        field_create_field($field);
        drupal_set_message($t('Field type: '.$field['field_name'] . ' created'));
    }

    foreach (_jobs_installed_field_instances() as $field) {
        field_create_instance($field);
        drupal_set_message($t('Field instance: '.$field['label'].' initiated and added to User Profile'));
    }

    drupal_set_message($t('Finished adding fields to User profile'));
}

function _jobs_installed_fields() {
    return array(
        'field_name' => array(
           ...
        ),
        'field_name2' => array(
           ...
        ),
     );
}

function _jobs_installed_field_instances() {
    return array(
        'field_name' => array(
           ...
        ),
        'field_name2' => array(
           ...
        ),
     );
}
</code>
The content of _jobs_installed_field_instances and _jobs_installed_fields functions is generated via PHP Execute Script Dev module block from the current instance content and then copy/paste in the install script.
<code>$entity_type = 'user';
$field_name = 'field_name';
$bundle_name = 'user';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">" . $output . '</textarea>')
</code>
This can be lot of work for larger Themes and i cannot rerun it later once the change is introduced. I was thinking creating some Php scripts that would generate me the install script from the current nodes, views, etc so i can rerun as like in future. Is there anything like this already available? What would be your approach to this problem? Thank you
Comment: You mean, you want to create [Features](https://drupal.org/project/features)?
Comment: Thank You Motot. Not exactly. I have new theme it in its own folder but this theme depends on Content Type, Views that also need to be present from the theme to properly function. So I would have a separate custom module that all will do is create these content types, views on install
Comment: But with features you can do that, you can only select views and content types to be exported.
Comment: Ah Motot...you made my day! The Features module looks exactly what i am looking for. I am sorry I didn't got the first time you mentioned but Thank You for pointing out again. You my hero!
Comment: Posted it as an answer - if it is really what you need, no point in keeping your question on "unanswered" list.
Answer: Looks like Features module is what you really want:

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

With addition of UUID Features Integration:

The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.

Of course you will probably only use a subset of it's capabilities, but it should cover all your needs with content types, nodes, and views definitions.
Comment: Motot, the feature works well for exporting content structures(content types, views, etc), but what would i use for exporting content itself (Nodes). i have some test data that i would like to package in another module as well. Thank you
Comment: @latvian answer updated.


Display content having the taxonomy of the logged in user

Question: I need help creating a view in Drupal 7 with the following logic:

My users have taxonomy reference field.
My articles also have    taxonomy reference field.

When a user is logged in I want them to see only the articles that have the same term as the logged in user.  How to set the relationships and contextual filters in this view?
Answer: Create a view to display the article content, then add as relation for user and  add a contextual filter for UID for logged in user.
Add new filter for content taxonomy and it must be equal to user taxonomy.
Comment: Hi Prem, thanks for your answer. I don't understand this part "add as relation for user". When I click the "Add" button of the "Relationships" section, which one should I select? The only one that mentions "user" is called "Content revision: User" but I don't think this is the one I need.


Como copiar um arquivo com PHP?

Question: Bom o meu problema é o seguinte desejo imprimir um código PHP em outro arquivo.
Por exemplo, eu tenho um arquivo x.php, e tenho um arquivo y.php, neste arquivo y.php quero que este crie um arquivo z.php e que faça uma cópia ao arquivo x.php, Como posso fazê-lo?
Answer: Bem, se for para fazer cópia de um arquivo .php utilize a função copy() do php:
http://php.net/manual/pt_BR/function.copy.php
$arquivo = 'arquivo.php';
$copia   = 'copia.php';

if (!copy($arquivo, $copia)) {
    echo "falha ao copiar $arquivo...\n";
}

Answer: Para copiares em PHP, conforme já referido, podes usar a função copy() que te permite copiar um ficheiro para outro local ou para outro ficheiro pois o nome de entrada não tem que ser igual ao nome de saída.
Exemplo
Conteúdo do arquivo x.php
<?php
// Eu sou o arquivo X

echo "X é muita fixe, mas o bubu é mais fixe!";
?>

Conteúdo do arquivo y.php
<?php
// Eu sou o arquivo Y

// Vou criar um arquivo "z.php" e copiar para lá o arquivo "x.php"
copy("caminho/para/arquivo/x.php", "caminho/para/arquivo/z.php");
?>

O resultado daquilo que o arquivo y.php faz é criar um arquivo com o nome z.php que irá conter o conteúdo do arquivo x.php.
Answer: Você pode incluir códigos PHP dentro de outro utilizando os comandos include, require e require_once. O  melhor no seu caso é o include, que pode ser utilizado assim:
include('arquivo.php');

Se lembre que o arquivo a ser chamado deve estar no mesmo diretório que o arquivo atual, caso esteja em outra pasta, ou em uma pasta anterior, você precisa especificar exatamente o caminho, exemplos:
include('scripts/arquivo.php'); // Arquivo em uma pasta que está dentro do diretório atual
include('../arquivo.php'); // Arquivo em um diretório antes

Para saber a diferença entre os comandos você pode dar uma pesquisada. Aqui uma referência rápida: https://webpub.wordpress.com/2007/11/11/diferenca-entre-require-require_once-include-include_once/
Comment: Por exemplo, eu tenho um arquivo x.php, e tenho um arquivo y.php, neste arquivo y.php quero que este crie um arquivo z.php e que faça uma cópia ao arquivo x.php, Como posso faze-lo?

Como copiar um arquivo com PHP?


Como faço para validar quantas imagens tem dentro de um arquivo TIFF?

Question: Quero fazer uma validação em C# para quando converter uma imagem de TIFF para JPEG eu consiga saber se todas as imagens foram convertidas, pois o TIFF é um único arquivo que as vezes traz várias imagens dentro dele.
Então às vezes tenho 10 TIFF que Gera 30 JPEG, então para não precisar abrir o TIFF e ir contando eu gostaria de saber se existe uma forma de saber quantas imagens vem no TIFF sem abrir.
Comment: Acho que isto pode te ajudar: http://stackoverflow.com/questions/11668945/convert-tiff-to-jpg-format
Comment: Converter eu consigo, o problema é eu validar se está trazendo a quantidade de imagens certa, pois geralmente são milhares de imagens que eu converto.
Answer: Usando o método GetFrameCount da classe Image é possível saber o número de imagens contidas no arquivo:
int numeroImagens = Image.FromFile(@"C:\test.tiff").GetFrameCount(FrameDimension.Page);


Lagged variables in multilevel models

Question: Is it okay to use lagged dependent variables as predictors in multilevel models? i.e. If there are $j$ groups of $i$ individuals each measured $t$ times, to model
$$ y_{ij} = \beta_{0j} + y^{-1}_{ij} + \beta X_{ij} + e_{ij} $$
where $\beta_{0j}$ are the random intercepts for group $j$, and the $y^{-1}_{ij}$ indicates the use of a lagged variable.
This link: https://statisticalhorizons.com/lagged-dependent-variables says it is not but there are cases of it being done, this link: www.bristol.ac.uk/cmm/team/longitudinal.pdf gives one.
What am I not understanding, thanks.
Answer: This type of models is also known with the name transition models; for example, see Chapter 10 of Diggle, Heagery, Liang and Zeger.
An issue with these models is that the vector of regression coefficients $\beta$ for the covariates $X$ has an interpretation conditional on the previous response, and not the usual marginal interpretation.
Comment: The first link is saying that you should not use lagged dependent variables in a longitudinal mixed model in which there are repeated measures on the same set of individuals. The second link identifies the same problem (initial conditions) and suggests a couple of different solutions. The solutions recommended in both links are viable alternatives for your case.
Comment: thanks @Dimitris, I'll have a look at the book chapter. So it appears that this is a reasonable thing to do; so I guess I am either misunderstanding the first link above or their issue is due to the interpretation issue that you mention.
Answer: Have a look at this very similar question and my answer:
Bayesian analysis of multilevel model with lagged dependent variable
In short: Yes, you can use lagged dependent variables in multilevel models as long as you group-mean center them. According to Hamaker & Muthén (2019). Hamaker, E. L., & Muthén, B. (2019, October 14). The Fixed Versus Random Effects Debate and How It Relates to Centering in Multilevel Modeling . Psychological Methods. Advance online publication. http://dx.doi.org/10.1037/met0000239
Comment: I'm not so sure that Hamaker & Muthen are saying this. They are indeed referring to the problem of endogeneity of time-varying predictors in random effects models. However, a lagged DV is a different beast entirely. The random intercept is based on the DV, so when you put any version of the DV into the multilevel model, it will be correlated with the random intercept. You cannot center your way out of that problem. This is why Allison, the Mplus group, and others (see `ctsem()` in R) have moved to a different approach using structural equation modeling.

Lagged variables in multilevel models


SolrQueryByDistance: kilometers or meters?

Question: http://wiki.apache.org/solr/SpatialSearch states:
NOTE: Unless otherwise specified, all units of distance are kilometers and points are in degrees of latitude,longitude
As seems to be the case in this question, I need to multiply my distances by 1000 before I get any results.
E.g.:
<code>{!geofilt pt=52.375,52.38 sfield=geo d=2992}
</code>
Since we've coupled the latlong information with zipcodes, I can verify that the returned zipcodes are all in the same neighbourhood.
So, distance, what unit is it in?
Answer: I've made an obvious mistake: The coordinates I was using for geofilt, were nowhere near the coordinates for my documents.


Getting critics to recognize that two similar input patterns refer to the same output-performance relationship

Question: The actor-critic model is used within temporal difference learning, which is a method within reinforcement learning, to optimize a process on a state-by-state basis by using the difference between performance and expected performance for each respective state. In other words, there is a set of possible input patterns to the process, each of which constitutes a state (the state in which the agent finds itself). For each state, the actor computes an output, which is evaluated by a performance metric (which can theoretically define a different target output for each state) that returns the reward (performance) signal. Meanwhile, for each state, the critic tracks the expected reward, which is a function of the past reward signals for that state. At each iteration, the difference between the reward signal and the expected reward signal is taken and used to update both the actor's policy (hopefully up a performance gradient) and the critic's performance expectation for that state.
Hypothetically, for some problem there exists two or more states (input patterns) that are similar and where the information that differs between the two is irrelevant. In other words, the target output for the states is the same and the input is similar. It would then be potentially useful for the critic to have a method for recognizing that all states that share a certain similarity are effectively the same state, so that the set of those states can share the same predicted outcome. In particular, if you are dealing with a system that features a massive amount of inputs, and if most of those are non-pertinent at any given point in time, then you don't want to relearn the expected performance for each possible combination of non-pertinent inputs.
My question, then, is how you do this. How do you get a critic to organize different states into state classes, and in a way that improves performance over the long run?
Answer: Within the value-function approximation model (which you've adopted?), you can opt to use a compressed encoding of the state-action space instead of a tessellation. Neural networks are sometimes used for this purpose.
What you might try with the critic is to use a supervised clustering algorithm over all states which were recently fed to the actor with the actions as the classes. You could then plunk a new state-action pair into the clustering model. If it flops down in the middle of a pure cluster, and is of the wrong class, it's worth training on. If it's of the right class, you can probably skip it. If it's in an impure cluster, or significantly outside of any dense cluster, probably keep it.
Comment: the actor in my system is an NN, so I think I know what you mean by compressed encoding: basically mapping multiple states to the same (or part of the same) action. I'm not familiar with supervised clustering algorithms though. Could you elaborate a bit? If I understand, some algorithm derives state classes, and then any new state that appears to be of an existing class is tested, and if it fails the test or didn't appear to meet any existing class, then it is trained as though belonging to an unknown class?
Comment: Yep, that's about right. Thinking about it, my terminology might be a bit off. What you do is run an _unsupervised_ clustering algorithm (e.g. k-means) over all previously evaluated points in the _state_ (not state-action) space. You'll get out a bunch of clusters (k). Test the clusters for purity using the _action_ of each point as a label. Take your new point, drop it into the state space, and determine which cluster it belongs to. If the cluster is highly pure, and the new point's action matches the cluster label, don't bother with it. Otherwise, it's worth learning.


Projeto JSP Eclipse - Linkando página de estilo CSS

Question: como linkar de forma correta minhas folhas de estilo no meu projeto JSP Servlet? Segue abaixo a estrutura do meu projeto.
Também não sei se a hierarquiaesta correta. Me ajudem.

Já tentei ../webapp/style/estilo.css e nada. Tentei modificar e colocar a folha de estilo na pasta webapp e linkar:
     <link rel="stylesheet" type="text/css" href="estilo.css" >

Mas não dá, e tipo na página fica só uma borda, não puxa tudo...
Página INICIO.JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="javax.servlet.http.HttpSession" %>
<%@ page import="br.edu.unilasalle.model.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link href="style/estilo.css" rel="stylesheet"/>

Menu Principal

Opções

    Cadastro de Usuário

    Cadastro de Bancos

    Cadastro de Categorias

<%
    if(request.getSession(true).getAttribute("usuario")!=null){

    Usuario usuario=
   (Usuario)request.getSession(true).getAttribute("usuario");
%>

    Usuário: <%=usuario.getId()%>. <%=usuario.getNomeCompleto() %>   Sair

<%} %>

Página de estilo.css
@CHARSET "ISO-8859-1";

body{
    background: rgba(0,77,153,0.6);
    border: 4px solid #8080c0;
    margin: 200px 500px 0px 500px;
    border-radius: 125px;
}

div {
    color: white;
    font-family: 'Times New Roman';
    font-size: 20px;
    padding: 80px;
    padding-bottom: 60px;
}

#acesso{
    margin-bottom: 5px;
    margin-left: 150px;
    font-family: 'Times New Roman';
    color: blue;
}

.fundo{
    background: url('../WebContent/img/wallpaper.jpg') no-repeat center;
    margin:0;
    padding:0;
    background-size:cover;
}

Answer: Pelo que li em seu comentario voce diz que a unica propriedade que funciona é " Border: 4px" .
Então isso quer dizer que você esta chamando a folha de estilo de forma correta!!!
O problema é provalvemente o estilo ou a pagina....
Apague tudo da sua folha de estilo e mude so a cor de fundo da pagina para fazer um teste.
Caso de certo vá adicionando um a um  os estilos na sua folha de estilo e em sua pgina confera se eles estao funcionando um a um .
Onde você chama a div , o id #acesso ?
Você tem que chamar eles na pagina jsp!!!
Se não chamar não funciona!!
Voce apenas chamou aqui nesse trecho do seu codgo
tem que fazer o mesmo para os demais propriedades do seu css.

Menu Principal

Opções

    Cadastro de Usuário

    Cadastro de Bancos

    Cadastro de Categorias

 Isso é uma id

<%
    if(request.getSession(true).getAttribute("usuario")!=null){

    Usuario usuario=
   (Usuario)request.getSession(true).getAttribute("usuario");
%>

    Usuário: <%=usuario.getId()%>. <%=usuario.getNomeCompleto() %>   Sair

<%} %>

A forma que eu usei a div e o id acima é só um exemplo, não quer dizer que tem de serem usados  exatamente nesses lugares , voce esta livre para usar onde quiser..
Quanto a forma de chamar o link,que não é o problema,  tente assim:
<link href="style/estilo.css" rel="stylesheet" type="text/css">

ou
<link rel="stylesheet" href="${pageContext.request.contextPath}/style/estilo.css" />

No primeiro caso acima voce pode adicionar ../ ou remover para achar a profundidade onde esta  a sua pagina de estilo.
Por exemplo :
 <link href="../style/estilo.css" rel="stylesheet" type="text/css">
 <link href="../../style/estilo.css" rel="stylesheet" type="text/css">
...

Comment: Não funciona. Abre a página e a unica propriedade da folha de estilo que funciona é a Border: 4px; Na folha tem algumas propriedades e inspecionando o código, elas ficam riscadas... Por que?
Comment: Removi todos comentários
Comment: Bah... pior que funcionou! Que descuido meu e nem me dei conta!
Comment: Muito bem ! Da proxima vicê ja sabe!! Valeu!!!


Write task output to file while using "until"

Question: I have an ansible task that fails about 20% of the time. It almost always succeeds if retried a couple of times. I'd like to use until to loop until the task succeeds and store the output of each attempt to a separate log file on the local machine. Is there a good way to achieve this?
For example, my task currently looks like this:
- name: Provision
  register: prov_ret
  until: prov_ret is succeeded
  retries: 2
  command: provision_cmd

I can see how to store the log output from the last retry when it succeeds, but I'd like to store it from each retry. To store from the last attempt to run the command I use:
- name: Write Log
  local_action: copy content={{ prov_ret | to_nice_json }} dest="/tmp/ansible_logs/provision.log"

Answer: It's not possible as of 2.9. The until loop doesn't preserve results as loop does. Once a task terminates all variables inside this task will be gone except the register one.
To see what's going on in the loop write a log inside the command at the remote host. For example, the command provision_cmd writes a log to /scratch/provision_cmd.log. Run it in the block and display the log in the rescue section.
    - block:
        - name: Provision
          command: provision_cmd
          register: prov_ret
          until: prov_ret is succeeded
          retries: 2
      rescue:
        - name: Display registered variable
          debug:
            var: prov_ret
        - name: Read the log
          slurp:
            src: /scratch/provision_cmd.log
          register: provision_cmd_log
        - name: Display log
          debug:
            msg: "{{ msg.split('\n') }}"
          vars:
            msg: "{{ provision_cmd_log.content|b64decode }}"

Comment: Thank you! That's exactly what I needed.


Inspect content of SLAB

Question: Is there a way, preferably simple, how to inspect content of SLAB caches, especially dentry cache? I can imagine that this can be doable through kernel modules, but I highly doubt security would let me install custom-built kernel module to production system.
I'm 99% sure we're impacted by NSS dentry leak, but want to see cached entries to be 100% sure.
rhel, 2.6.32
nss-softokn-3.14.3-18.104.22.168.el6_8.x86_64
Thanks!
Answer: Server Fault has covered this before: Unusually high dentry cache usage which resulted in RHEL bug 1044666, Can curl HTTPS requests make fewer access system calls?
Examining cache contents is not required. From the bug report, this is not a small amount objects in the cache, they got millions of them with just a few curl executions. Further, you can see it access files by tracing processes using NSS, looking at calls to access().  There should be a high volume of access to files that do not exist.
Set environment variable NSS_SDB_USE_CACHE and retest. This env var needs to be set to "yes" or "no" to bypass file system speed tests, apparently. Excessive access to non-existent files should cease, and slab consumption stabilize.

In general, slab should not grow without bound.
Monitor this over time. For example, netdata collects slab by default. (Although, export it to a time series database with more retention to see trends over days and weeks.)

Inspect content of SLAB


Is my six sided dice weighted?

Question: I was playing a game with my son, and it seemed that we rolled two or five about half the time. He was wondering if the die was weighted.
So I re-rolled it a bunch of times and jotted down the results:
<code>1: 4 times
2: 12 times
3: 13 times
4: 4 times
5: 13 times
6: 8 times
</code>
I realise that this is a small sample (only 54 datapoints), but to my very untrained eye, the 1 and 4 seem very low. I was wondering how I would go about determining the probability that the die is fair. I was expecting about 9 each. I did a ChiTest in excel, which I am not sure how to calculate manually and got 0.069
Does this mean that there's a 6.9% chance that the die is unweighted, and therefore a 93.1% chance it's weighted, or have I misinterpreted the results entirely?
Comment: It would be difficult to weight a die so that it rolled $2$'s and $5$'s preferentially, because on a standard die the $2$ and the $5$ are on opposite faces.
Answer: This is not the right interpretation of the $0.069$ number. Indeed, this wrong interpretation is extremely common, and people from doctors to judges to scientists to policy makers routinely get this wrong (and go on to make poor decisions as a result).
The $0.069$ number means this: if your die is fair, then the probability of getting a result at least as extreme as the one you observed is $0.069$. In other words, if you do sets of 54 trials over and over again, you'll see distribution as extreme or more in 6.9% of the trials.
You can use this informtaion however you want to make deductions about whether the die is fair or unfair. However, it makes no sense to talk about "the probability that the die is fair" unless we have an underlying space of all possible events as reference (all dice in the world, for example, or all ways of manufacturing dice). The result from a chi-square test simply does not provide that type of information.
Answer: It would be better at least 5 obs but also 4 is fine.
$$\chi_{(5)} ^2=\frac{(4-9)^2}{9}+\frac{(12-9)^2}{9}+\frac{(13-9)^2}{9}+\frac{(4-9)^2}{9}+\frac{(13-9)^2}{9}+\frac{(8-9)^2}{9}=10.22
$$
The critical $\chi_{(5)}^2$ at 5% is 11. Your dice is fair. To calculate the exact p-value you must use a calculator.
You interpreted well your results
Comment: "Your dice is fair": that's not right! If you mean that there is no compelling evidence that the die is unfair, then yes. But that is not what you said.
Comment: @TonyK: Yes, you are right. That is not what I said. I am italian, not a professor but just an amateur....very sorry for that, I agree with you
Answer: I would not consider your die as weighted, we can see this as a binomial distribution problem
$$P(X=r)={{n}\choose{r}}P^{r}(1-P)^{n-r}$$
This basically models your case, $r$ is the number of succeses, $n$ would be the number of trials and $P$ the probability of succes. Replacing and computing for rolling number 1 four times in 54 trials
$$P(X=4)\approx0.0268$$
Which would be 2.68%, since it is not incredibly low, considering all the posibilities (one 1, two 1s,..., 54 ones) I would guess it is not. But you could always apply the large number rule, meaning the more tries, the more the real possibility asimilates to the theorital possibility.

Is my six sided dice weighted?


Custom Angular directive with template won't run in node

Question: I have worked a few Angular projects, but am a little new to node. I have a custom directive that displays summary statistics about data, . The directive works fine when I'm developing the front end using Gulp and Browser Sync, but when I build all of the files and run node server.js, my custom directives cause the browser to lag out. I believe that it's due to including a templateUrl in the directive.
Is there something I need to do to include templates specified by templateUrl so that node will serve up the HTML files?
Here is my directive:
app.directive('summaryStats', function(scatterService) {
    return {
        restrict: 'A',
        templateUrl: 'app/components/summaryStats/summaryStats.html',
        link: function(scope, el, attr) {

            function update(data) {
                scope.lowCost = data.xMin;
                scope.highCost = data.xMax;
                scope.avgCost = data.avgCost;
                scope.lowTime = data.yMin;
                scope.highTime = data.yMax;
                scope.avgTime = data.avgTime;
                scope.topTechs = data.topTechs;
            }

            scope.$watch(function() { return scatterService.getModel(); }, function(newVal) {
                update(newVal);
            }, true);
        }
    };
});

Here is my server.js file:
var express = require('express');
var path = require('path');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var fs = require('fs');

var app = express();
app.use(function(req, res, next) {
  req.headers['if-none-match'] = 'no-match-for-this';
  next();
});

app.use(express.static(path.join(__dirname, '/dist')));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(methodOverride());

app.get('*', function(req, res) {
  res.sendfile('./dist/index.html');
});

app.listen(8080);
console.log("App listening on port 8080");

Answer: My problem was that that my Gulp build task wasn't inserting the templates into the distribution folder. This problem was solved by placing a static folder that housed my HTML files, and building that into my distribution folder with Gulp.


Paginação aparecer em JSF Primafeces Datatable apenas quando tiver mais que uma página

Question: Como fazer para que a paginação apareça apenas quando tiver mais que uma página, utilizando o componente Datatable do  Primefaces no JSF?
Comment: Você esta utilizando JSF puro ou algum framework (Primefaces, Richfaces, Icefaces...)?
Comment: Editei a pegunta e acrescentei o primefaces lá
Comment: Qual versão está usando?
Answer: Seguindo a documentação do Primefaces 6.1, você pode utilizar o atributo paginatorAlwaysVisible para ocultar caso a tabela não apresente o número de registros necessários para paginação:
Segue uma tradução da documentação:

Propriedade: paginatorAlwaysVisible
Valor padrão: true
Define se o
  componente de paginação deve ser oculto se o contador total de
  registros é menor que a quantidade de registros por página

Portanto em sua datatable utilize o atributo paginatorAlwaysVisible="false"


prove that square root of 2 is irrational using sets

Question: There is a set $A$ with positive integers $x$ such that there exists $y$ s.t.$ x^2=2y^2$. Show that if A is non-empty, it violates the well ordering principle.
I don't even know how to start this.
Comment: It is quite puzzling that there are currently two votes to close as "not a real question".  It is most certainly a real question.
Comment: No, it's more than a hint, it's a method --- you can prove if $A$ is non-empty then there's always a smaller element, and get a contradiction.
Comment: They meant, you should prove that $A$ is empty, i.e.\ there are no such $x$ and $y$. The 'well ordering principal' is just a kind of hint..
Comment: http://math.stackexchange.com/questions/917983/the-proof-of-sqrt2-is-not-rational-number-via-fundamental-theorem-of-arithm
Answer: If $x^2=2y^2$, then $(2y-x)^2=2(x-y)^2$.
Comment: I'm being completely and utterly explicit --- I'm just not doing all the work for you. You have to think about why the second equation is true (just do some calculation), and you have to work out what this has to do with the well-ordering principle (*not* principal). You do know what the well-ordering principle says, right?
Comment: can you be more explicit please? I'm new to this subject
Comment: that nonempty set has a smallest element
Comment: i still don't see anything that you did, what this has to do with a square root of 2 anyways?
Comment: You are trying to prove $\sqrt2$ is irrational, that is, there are no integers $x,y$ with $x/y=\sqrt2$, that is, there are no integers $x,y$ with $x^2=2y^2$. You are trying to prove it by well-ordering, so you are assuming there is such an $x$ (and corresponding $y$) and then showing there's a smaller such $x$ so there's no smallest such $x$, contradicting well-ordering. But let's start with what I wrote: can you prove that if $x=2y^2$ then $(2y-x)^2=2(x-y)^2$?
Comment: This way of doing it used to be not very widely known. I wonder if that's changing.  The way Bill Dubuque does it in his answer posted here is the one that everyone knows.
Answer: Hint $\ $ Show that if $\rm\,A\,$ is nonempty then it has no least element, contra $\rm\,A\subseteq \Bbb N\,$ is well-ordered. Note $\rm\:a\in A\:\Rightarrow\:a^2 = 2\,b^2\:\Rightarrow\:a $ even so cancelling $\,2\,$ yields $\rm\:b^2 = 2\,(a/2)^2$ so $\rm\,b\in A,\,$  and $\rm\,b < a.\:$
Remark $\ $ This contrapositive form of induction is known as infinite descent (Fermat). More conceptually the proof is a descent on the set $\rm\,A\,$ of numerators of fractions $\rm = \sqrt{2},\:$ since $\rm\:(a/b)^2\! = 2\:$ $\Rightarrow$ $\rm\:a/b = 2b/a = b/(a/2),\:$ yielding a fraction with smaller numerator $\rm\,b < a$.
Comment: How did you get $\rm\:b^2 = 2\,(a/2)^2?\ $ You divided by 2?
Comment: @JackF $\ $ Yes $\rm\:1/2\:$ times $\rm\,2\,b^2\! = a^2\ \to\,\ b^2\! = a^2/2 = 2\,(a/2)^2,\:$ and $\rm\:a/2\in \Bbb N\:$ since $\rm\:a\:$ is even. $\quad $
Comment: Where did that 2 come from at the end?
Comment: @JackF $\ $ It's just $\ \ \dfrac{1}2\, =\, 2\cdot \dfrac{1}4\, =\, 2\cdot \left(\dfrac{1}2\right)^2\ $ scaled by $\rm\:a^2\ \ $
Answer: What you want to do is show that if
$\sqrt 2 = m/n$, where $m$ and $n$ are positive integers,
then there are positive integers
$p$ and $q$ with $q < n$
such that $\sqrt 2 = p/q$.
The key trick is to write
$\sqrt 2 = \sqrt 2 \frac{\sqrt 2 - 1}{\sqrt 2 - 1}
= \frac{2-\sqrt 2}{\sqrt 2 - 1}
= \frac{2-m/n}{m/n-1}
= \frac{2n-m}{m-n}$.
Now set $p = 2n-m$ and $q = m-n$.
Since $m-n < n$, this denominator is smaller, and well-ordering can be used.
This can be used to prove that $\sqrt k$ is irrational
for any non-square positive integer $k$.
I don't know if a variation of this is known for the cube root.
Of course, this is not original with me.
Comment: Marty, you may be interested in my paper, http://www.austms.org.au/Gazette/2008/May08/Myerson.pdf where I note how to push a version of this argument to cube roots and beyond.
Comment: See [this answer](http://math.stackexchange.com/a/91595/242) which shows how to reduce irrationality of cube roots to that of square roots (and ditto for higher degrees). See also [this answer](http://math.stackexchange.com/a/39769/242) which links to a sci.math discussion of the classical topics in Gerry's paper.
Comment: Gerry: That's nice. Somehow it doesn't seem that it should be that easy. I guess it just requires "straight thinking". Thanks


Finding ratio of length of radii from ratio of areas?

Question: The Question: A central angle of two concentric circles is $\frac{3\pi}{14}$. The area of the large sector is twice the area of the small sector. What is the ratio of the lengths of the radii of the two circles?
Answer: 0.71:1
The answer I end up with is $\sqrt{2}$:$1$, instead of $\frac{\sqrt{2}}{2}$: 1 (which I'm assuming is how they got 0.71). My book says the angle measure is superfluous, and that "areas of similar figures are proportional to the squares of linear measures associated with those figures". Using the similar figures property, this was my answer:
if $r_2$ = radius of larger circle and $r_1$ = radius of smaller circle and likewise for $a_2$ and $a_1$, then ($\frac{r_2}{r_1}$)$^2$ = $\frac{a_2}{a_1}$. Since $\frac{a_2}{a_1}$ = 2, taking the root of both sides yields $\sqrt{2}$ = $\frac{r_2}{r_1}$. Any explanation would be appreciated, thank you very much!
Comment: What are  you actually asking?
Comment: $\frac{1}{\sqrt{2}} = \frac{\sqrt{2}}{2}$ - maybe this is where you are going wrong. Plus the order of the ratio.
Comment: @simplest_mathematics Sorry if it wasn't clear, I just didn't know why my answer was wrong/how they got their answer.
Comment: They have written as the answer the ratio of the smaller to the larger, and you have found the ratio of the larger to the smaller.
Comment: @DavidQuinn My answer was sqrt(2):1, and theirs was 0.71:1.
Comment: Explanation of what?  Everything you said is perfectly correct.  The ratio of the long to short radius is root (2) to 1.  The ratio of the short radius to long is 1/root (2) $\approx$ .71 to 1 (and *SHAME* on your book for thinking that was a acceptable answer, especially at the teaching level).  And shame on your book for not specifying whether it wanted the ratio of the long to short, or the short to long.
Comment: @DavidQuinn Sorry, got super confused there! You're right, thanks!
Comment: @fleablood Thanks! This had me so confused, didn't even think about the possibility that they might have done it the other way!
Comment: r2/r1= root (2).  r1/r2 = 1/root (2) =.71.  No harm no foul.  But I'm not going to be taking your book to the prom after that sort of shenanigans.
Answer: The question does not specify which radius comes first in the proportion.  The book answer gives $r_1:r_2=\frac {\sqrt 2}2:1$ while you are saying $r_2:r_1=\sqrt 2:1$.  You agree with the book but present the data in the opposite order.  I also object strongly to saying $\frac {\sqrt 2}2=0.71$ but that is another issue.
Answer: let r = radius of the smaller circle and
     R = radius of the larger circle.
We will get R:r= √2: 1.
Since the order in taking which radius first we can take
            r:R =1:√2
          or r/R=1/√2= 0.707
          i.e., r:R=0.707:1
<code>            r:R=0.71:1
</code>


Recuperar dados firebase - itens de pedido

Question: Boa tarde
estou tentando listar todos os itens de um pedido em um recycler view, mas a consulta só retorna um valor conforme abaixo :
 public void recuperarItemPedido(String idPedido1) {
    databaseReference = FirebaseConfig.getFirebaseDatabase().child("pedidos");
   Query query = databaseReference.orderByChild("id").startAt(idPedido1).endAt(idPedido1+"\uf8ff");

      query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                pedidoList.add(dataSnapshot1.getValue(Pedido.class));
            }
            Collections.reverse(pedidoList);
            adapterDetalhes.notifyDataSetChanged();
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

em outra tela, esse mesmo código retorna todos os itens que estao dentro do pedido. não sei mais o que pode ser
Answer: Boa noite.
Tenta instanciar novamente a lista no onDataChange antes de recuperar os itens
pedidoList = new ArrayList();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        pedidoList.add(dataSnapshot1.getValue(Pedido.class));
    }

Comment: Boa tarde , tentei isso tambem mas não funcionou...
Comment: Pode ser a classe FirebaseConfig. Mostra o código dela
Answer: Bom dia
Consegui resolver alterando o adapter da seguinte forma:
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    Pedido pedido = pedidoList.get(position);
    List<ItemPedido> itens = new ArrayList<>();
    itens = pedido.getItens();

    String  modelo = "",cor1 = "",cor2= "",cor3= "",cor4= "",valor = "",qtd="",tam = "";
    int numeroItem = 1;

    for ( ItemPedido itemPedido : itens ){
        String modelo1 = itemPedido.getModelo();
        Double preco = itemPedido.getPreco();
        String cor1_1 = itemPedido.getCor1();
        String cor2_2 ="", cor3_3="", cor4_4="";

        String tam1 = itemPedido.getTam();
        int qtd1 = itemPedido.getQuantidade();

        if(itemPedido.getCor2()!=null) {
            cor2_2 = itemPedido.getCor2();
        }if(itemPedido.getCor3()!=null){
            cor3_3 = itemPedido.getCor3();
        }if (itemPedido.getCor4()!=null){
            cor4_4 = itemPedido.getCor4();
        }
        modelo += numeroItem + "\t" + modelo1 +"\n";
        cor1 += "\t"+cor1_1+ "\n";
        cor2 += "\t"+cor2_2+ "\n";
        cor3 += "\t"+cor3_3+ "\n";
        cor4 += "\t"+cor4_4+ "\n";
        qtd += "\t"+qtd1+ "\n";
        tam += "\t"+tam1+ "\n";
        valor +="\t"+preco+ "\n";
        numeroItem++;
    }
    holder.nomeModeloItem.setText(modelo);
    holder.cor1.setText(cor1+cor2+cor3+cor4);
    holder.qtd.setText(qtd);
    holder.tamanho.setText(tam);
    holder.valor.setText(valor);
}

Espero que ajude alguém, muito obrigada!


Problem with Views 7.x-3.0 - Column not found

Question: I just updated the views from 7.x-3.0-rc1
 to version 7.x-3.0 and now I'm getting the following error when executing my view:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_category.nid' in 'on clause'
The generated query looks like this:
SELECT node.title AS node_title,
       node.nid AS nid,
       node_field_data_field_category.title AS node_field_data_field_category_title,
      'node' AS field_data_field_color_node_entity_type,
      'node' AS field_data_field_image_node_entity_type,
      'node' AS field_data_field_sale_node_entity_type
FROM {node} node
LEFT JOIN {field_data_field_category} field_data_field_category ON node.nid =
                                      field_data_field_category.entity_id AND
                                      (field_data_field_category.entity_type = 'node' AND
                                      field_data_field_category.deleted = '0')
LEFT JOIN {node} node_field_data_field_category ON field_data_field_category.nid =
                 node_field_data_field_category.nid
LEFT JOIN {field_data_field_gender} field_data_field_gender ON node.nid =
                                    field_data_field_gender.entity_id AND
                                    (field_data_field_gender.entity_type = 'node' AND
                                    field_data_field_gender.deleted = '0')
WHERE (((node.type IN  ('product')) AND (node.status = '1') AND
        (field_data_field_gender.field_gender_value IN  ('0', '1'))));

I see that the field_data_field_category.nid should be field_data_field_category.field_category_nid, but how do I solve this without using something like hook_query_alter?
Answer: The problem was in the references module, I found this patch wich solved the problem.
Answer: Most likely the data for the field is wrong or incomplete. You can fix this with hook_views_data_alter. Not knowing anything about the field, it's hard to say what to do exactly. At worse, you need to create a custom handler.


Lpush and Zadd methods of Jedis not found in Jmeter

Question: I have written a beanshell sampler which has the objective of setting the multiple values for a single key. I tried with lpush just for the start. Then I went on using the zadd method which I believe is for adding multiple values for a single key.
But, in both the cases, I am getting an error in the log viewer that the respective method in the jedis class does not exist. How do I go about resolving this error.
I have tried to replace the jedis jar file(current version i am using is: 2.2.1) with the latest version(in the lib folder) in order to ensure the completeness of the methods to be used. But then, while starting the jmeter from command line throws java.lang.VerifyError.
Please let me know the solution for this problem.
Answer: Show your code so that we can help more precisely.
Another option is to use this if you only want to read the values:

http://jmeter-plugins.org/wiki/RedisDataSet/


Azure Active Directory B2C Error: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable

Question: Right after authenticating for my web app with Azure Active Directory B2C, I get the following error message:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
This error message comes up after successfully authenticating through the "Sign In", "Sign Up", and the new "Sign Up or Sign In" policies. I have two identical websites, one hosted by Azure through their "App Services", and the other hosted in IBM Bluemix. The Bluemix-hosted website authenticates fine without errors, but the Azure-hosted version is the one giving me the error.
I have also created a troubleshooting webpage so I can troubleshoot and narrow down the source of the problem. As soon as I add the Application Claim "User's Object ID", and only that claim, I get the error. The problem is, I need that claim, among others, for authenticating purposes, so I can't just simply remove that claim.
The troubleshooting webpage is here:
https://troubleshootb2c2.azurewebsites.net/
In that webpage, just click on "Log in" at the top-right corner, and you will be taken to an authentication page using the "Sign Up or Sign In" policy. Once you sign in or sign up, it will redirect to a valid URL (https://troubleshootb2c2.azurewebsites.net/auth) and show the error message in the form of a webpage.
My code can be found here, if the problem lies within my code:
https://github.com/edsfocci/troubleshootb2c2
Comment: To possibly help in troubleshooting, I have a similar app that authenticates fine if it is hosted in Bluemix, but shows the error if it is hosted in Azure App Service. Therefore, it isn't a browser problem.
Answer: You need to import redirect in your views.py.
<code>from django.shortcuts import render, redirect
</code>
Looking at the Fiddler, I can see that this response is coming back from Azure App Service (IIS / Django app) rather than the Azure Oauth workflow. If you visit https://troubleshootb2c2.azurewebsites.net/auth/ directly you would expect it to redirect to https://troubleshootb2c2.azurewebsites.net/ but you get a Django NameError instead.
Comment: Good catch @Ryan. I made the change, but the error still shows up. I remove the query string, and it redirects me to '/' fine, but when I click on "Log in" again, the error comes back.


Is this the right way of solving $x^2y''-xy'+y=8x^3$?

Question: The original equation is:
$$x^2y''-xy'+y=8x^3$$
My workflow (Warning: quite long)

$\begin{align} y &= x^k \\
y' &= kx^{k-1} \\
y'' &= k(k-1)k^{k-2} \end{align}$
after symplyfiyng I got:
$$k^2-2k + 1 = 0 \tag{1}$$
with double root $k_{1,2} = 1$
So the general solution is: $$y(x) = C_1x+C_2x\ln|x|$$

After that I rewrote equation $(1)$ as:
$$y'' -2y'+y = 8x^3 \tag{2}$$
and as right side of $(2)$ is the cubic polynomial,  the particular solution will be:
$$\begin{align} y_p &= Ax^3+Bx^2+Cx+ D \\
y'_p &= 3Ax^2 + 2Bx +C \\
y''_p &= 6Ax + 2B \end{align}$$
After applying Undetermined Coefficients methos I got the system:
$$\begin{cases} A = 1 \\ B = -6 \\ C = -30 \\ D = -48 \end{cases}$$
Finally $y_p = x^3-6x^2-30x-48$
And the answer is $y(x) = C_1x+C_2x\ln|x| + y_p$

so my questions are:
1.) Did I do this right? (My book's answer mentioned $x = e^t$ substitution, so answer looks different, but can shown way be accepted as the right answer, though?
2.) A bit of off-topic in the end, but could these substitutions be applied if for example $(1)$ had  the complex-conjugate roots? (Some resources say yes, some no, so I am totally confused).
Comment: I guess the particular solution is wrong. If you plug in $y_p(x)=Ax^3+Bx^2+Cx+D$ into $x^2y''(x)-xy'(x)+y(x)=8x^3$ you will get the system $4A=8$ and $B=D=0$. Here $C$ is arbitrary because $Cx$ solves the homogeneous part. The solution is now $y_p(x)=2x^3$.
Comment: There is something wrong with the solution of the homogeneous part. See the answer of Nicolas Francois below
Comment: Got it! I had substituted things into equation which I denoted as $(2)$, and I did not think about the original one, that is what I had missed.
Comment: @Fakemistake, yes, you sre right, I got the solution now, will mark your answer as accepted, despite it shows the other way, thanks!
Answer: Big Hint: (with the given substitution $x=e^t$ above)
\begin{align}
y'(x)&=\frac{y'(t)}{e^t}\\
y''(x)&=\frac{y''(t)}{e^{2t}}-\frac{y'(t)}{e^{2t}}
\end{align}
You will get
\begin{align}
y''(t)-2y'(t)+y(t)=8e^{3t}
\end{align}
Can you take it from here?
Comment: I know that, it is caused by $x = e^t$ substitution :), but I am about another substitutions :)
Comment: I think you meant to write $8e^{3t}$.
Comment: @JohnWaylandBales of course it's $8e^{3t}$. I will correct it.
Answer: try $y_P=Ax^3$ for the particular solution.
Comment: you can try this also, then you will get $$B=C=D=0$$
Comment: I thought any polynomial should be expanded to the full one, like if we have only $$x^2$$ then $$Ax^2+Bx +C $$ and it the actual example there is $x^3$ so it should be written like $$Ax^3+Bx^2+Cx+D$$ Is not this correct?
Comment: so we only take the coefficients from variables that match the variables power of the original solution, and the rest can just be omited without fear of loosing anything?
Comment: @M.Mass When there's a polynomial of degree $m$ on the right hand side, you have to take the full ansatz $y_p(x)=a_mx^m+a_{m-1}x^{m-1}+\ldots+a_1x+a_0$ for the particular solution of the ode. In your own words, you have to take $y_p(x)=Ax^3+Bx^2+Cx+D$
Answer: Looking for a solution of the form $y=x^k$ for the homogeneous equation , as you did, you find $y=Cx$.
Now let's make the constant dance : put $y=zx$ with $z$ a function. You have $$y'=z+xz',\ y''=2z'+xz''$$
so substituting in the homogeneous equation :
$$3x^2z'+x^3z''=0\iff (x^3z')'=0\iff x^3z'=C\iff z=\frac{C'}{x^2}+C''$$
Therefore, a solution for the homogeneous equation is
$$y=\frac{C'}{x}+C''x$$
Remains to find a solution for the base equation. You can use the usual method, but here, as suggested, looking for a solution of the form $y=Ax^3$ is successful : you find $A=2$, so a complete solution on either $]-\infty,0[$ or $]0,+\infty[$ is
$$y=2x^3+\frac{C}{x}+C'x$$
Of course, as the equation is an Euler equation, putting $x=\pm e^t$ immediately transforms the homogeneous equation in a linear one, so it may be a better method.
Hope I didn't make too many mistakes...


Failing to load resources on apache server

Question: I've got a website I'd like to temporarily host on my VPS, but I've run into a problem.
After creating the '.conf' file in 'sites-available', and activating the site, numerous files aren't being properly linked to.
Here's my .conf configuration:
# domain: mynewsdesk.dev
# public: /var/www/html/mynewsdesk.dev/public

<VirtualHost *:80>
     ServerAdmin firstname.lastname@example.com
     ServerName mynewsdesk.dev
     ServerAlias www.mynewsdesk.dev
     DirectoryIndex index.php
     DocumentRoot /var/www/html/mynewsdesk.dev/
     ErrorLog /var/www/html/mynewsdesk.dev/public/logs/error.log
     CustomLog /var/www/html/mynewsdesk.dev/public/logs/access.log
     combined
</VirtualHost>

In chrome inspector, I see 'Failed to load resource: the server responded with a status of 404 (Not Found)' followed by paths that are clearly incorrect, for example: http://188.8.131.52/mynewsdesk.dev/css/main.css.php.
What settings should I change so that files are pulled from 'mynewsdesk.dev/public/' instead of 'mynewsdesk.dev'?
Answer: Change your DocumentRoot to be /var/www/html/mynewsdesk.dev/public/.
Alternatively, if you have scripts that you want to run that are outside that directory, and you have mod_rewrite enabled, you can add some rewrite conditions and rules to return files from public and direct all other requests to those scripts.
For example, in your vhost:
RewriteEngine on

RewriteCond          %{DOCUMENT_ROOT}/public%{REQUEST_URI}  -f
RewriteRule  ^(.+)$  %{DOCUMENT_ROOT}/public/$1  [L]

RewriteRule ^(.*)$ index.php?$1 [NC,L,QSA]

Comment: Just following up: Worked great! Thanks again


Sisteminha de busca com tabelas relacionadas mysql

Question: Como podem ver na imagem abaixo, eu tenho a tabela Imóveis (mysql) que se relaciona com as tabelas Tipo, Bairro e Cidade.

O que eu preciso é o seguinte:
Tem um campo de texto para efetuar uma busca simples e pode ser digitado qualquer coisa. Suponhamos um usuário digite "São Bernardo do Campo", o sistema vai procurar nas tabelas Tipo, Bairros e Cidades até encontrar na coluna "nome" a palavra digitada e caso encontre, pega o ID e faz um loop comparando com o respectivo ID na tabela Imóveis e retorna todas as ocorrencias encontradas.

Eu gostaria de fazer com INNER JOIN, más eu estou tendo dificuldades para entender.
Agradeço qualquer ajuda.
Answer: Primeiro você vai ter que linkar todas as tabelas com o inner join.
Depois você tem que ver onde irá buscar 'campos'...
Seria algo assim:
SELECT * FROM `imoveis` AS `i`
INNER JOIN `tipo` AS `t` ON `i`.`tipo_id` = `t`.`tipo_id`
INNER JOIN `cidades` AS `c` ON `i`.`cidade_id` = `c`.`cidade_id`
INNER JOIN `bairros` AS `b` ON `i`.`bairro_id` = `b`.`bairro_id`

Isso faz as ligações das tabelas pelas respectivas chaves estrangeiras, após isso irá ter que fazer onde buscar...
WHERE `b`.`bairro_nome` = ? OR `c`.`cidade_nome` = ? OR `t`.`tipo_nome` = ?

Pronto, agora você tem sua query string, é claro que assim irá voltar todos os campos da tabela, antes você deve fazer o SELECT correto de quais campos irá querer ter o retorno.

Obs: antes de postar uma pergunta tente ler sobre o assunto, estude
  mais, isso é uma coisa simples de se fazer, iria conseguir em poucas
  horas procurando na internet.
Comment: Mano, funcionou certinho.... valeu mesmo.


Debian Squeeze Slow SMB/Samba Write Speeds

Question: Arch: x86_64
OS: Debian
Sub-Version: Squeeze
Prev Speed: 3-5MB
Current Speed: 1MB
Connection: WIFI
WIFI Speed: 150Mbps
I have been Google'in and testing for hours using the same file. I was getting 3-4 and now its 1 or less.
Comment: I believe the title is self explanatory
Answer: You have to remember that 1 megabyte per second transfer speed is much different than 1 megabit per second transfers. 150 megabits per second is about 18 megabytes per second but that is if you are actually getting the whole 150 megabits per second in the first place. This speed isnt bad for wireless. Step up to a 300mbps router and you may see 2-4 Mb/sec.
Comment: I was getting 3-4 and now it dropped to 1 or less


Can't access bundle from pod library

Question: I try to use PEPhotoCropLibrary in my project. I added it using cocoapods installer. But when I try to use it in my code, I get error:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: ' -[NSBundle initWithURL:]: nil
  URL argument'

That happens here:
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"PEPhotoCropEditor" withExtension:@"bundle"];

Then I tried to get access to PEPhotoCropEditor.bundle in my code:
let url = Bundle.main.url(forResource: "PEPhotoCropEditor", withExtension: "bundle")

and got nil as result. Project structure is here:

What is wrong here, why I can't access library bundle?
Comment: what does NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"PEPhotoCropEditor" withExtension:@"bundle"]; ?
Comment: That code from PEPhotoCropEditor library.
Comment: is this your library : https://github.com/kishikawakatsumi/PEPhotoCropEditor
Comment: Yes, this library i'm trying to use.
Answer: Please change:
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"PEPhotoCropEditor" withExtension:@"bundle"];

to:
NSURL *bundleURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"PEPhotoCropEditor" withExtension:@"bundle"];

Can't access bundle from pod library


Why is the Edinburgh Half Marathon world record eligible?

Question: In order for times set in a road race to be eligible for a world record, the course needs to satisfy some rules, two of which are:

The start and finish points of a course, measured
along a theoretical straight line between them, shall
not be further apart than 50% of the race distance.
The overall decrease in elevation between the start
and finish shall not exceed 1:1000, i.e. 1 m per km
(0.1%).

See rules 31.21.2 and 31.21.3 here. The purpose of these rules are to avoid athletes getting a world record time by being aided by an overall downhill course or having a constant tailwind in a point-to-point course.
In this document there is a list of marathons and half marathons around their world, alongside with an indication as to whether or not they satisfy the downhill/separation rule. I noticed that the Edinburgh Half Marathon is included as compliant with the rule (and therefore a theoretical world record set on this race would be valid). However, if we look at the race information page, specifically the elevation profile, we see that it drops from about 90 m to 10 m, i.e. about an 80 m drop, which is far higher than the 21 m maximum permitted for a half marathon (1/1000 of 21 km).
Plotting the start and finish points on Google Maps, we come to a similar conclusion about the elevation drop.
So my question is: Despite all this, why is the Edinburgh Half Marathon still considered Rule 31.21 compliant?
I also want to note that World Athletics' list has been updated this year and the couse has been unchanged for several years, and is set to remain unchanged for the 2021 edition of the race (this year's edition was cancelled due to COVID-19).
Another surprising fact is that the Edinburgh Marathon – which takes place on the same day and has the same start and finish points – is not even included on World Athletics' list, neither as compliant or non-compliant with the rule. The elevation drop of ~80 m is still too much for a marathon, put proportionally less than the half marathon since the course length it is double the distance.
As a side note, when looking at the route map on the race information page, it may also give the illusion that the half marathon violates the 50% separation rule since the course heads mostly eastwards. However, by using the measure distance tool in Google Maps, we find that the straight line distance is about 9 km – so it is safe by about 1.5 km.
Up until now, the times set in the Edinburgh Marathon and Half Marathon do not come close to the world records and it seems very unlikely that a world record will be attempted in Edinburgh in the near future. However, the course being world record eligible can influence non-professional runners who are considering running it as a PB attempt, since it means that whatever time they achieve is "valid" as a PB (compared to, say, a race going from the top of a 2000 m mountain pass to sea level, which would be considered "cheating" since the massive elevation drop will probably make everyone several minutes faster).
Comment: Good question - I don't know why it's listed.  It's odd that the full isn't listed at all - most races are listed under both distances, even if one doesn't qualify.  I almost wonder if there's a second half marathon that's being confused with it, but it doesn't seem likely (and nearly all races on Edinburgh seem to be quite a bit downhill, which is not surprising given the terrain).
Comment: You're right, this is weird. You've documented this so thoroughly that I feel like the most-likely explanation at this point is that World Athletics included the race in the list (or noted it as rule 31.21 compliant) in error.
Answer: This answer has been significantly improved based on insights from @olmomiau.
The Edinburgh Half Marathon never used a world record eligible course.
Points to consider:

No world records have been reported from this course yet, so the scrutiny wasn't enormous.

They advertise: "With a descent of almost 90 metres to near sea level, we believe this is the fastest half marathon route in the world."

Well, if it is, then it has to beat, among others, very many advertised "downhill half marathons" that manage to drop anything from hundreds of meters to over two vertical kilometers.

Very many events advertise using the identical claim of being a "fastest half marathon route in the [you guessed it] world".  They may differ in their degree of fastestness and halfmarathonness.

The general profile of the Edinburgh Marathon in recent times is the initial mostly descending three or so miles through the city, followed by a much longer distance in East Lothian that's very flat at near sea level.  The Half Marathon generally copies the first half of the Marathon, which makes it twice less likely to conform with Rule 31.21.3 than the Marathon.  Read on for details.

It was not always like this.  A hilly full marathon course from the eighties changed, as of 2007, into a course advertised as having a 40 metre initial drop (compliant with Rule 31.21.3 for the Marathon but not for the Half), and a similar course was then used till 2017 (or even 2018? - the link URL suggests 2018 but I don't trust that hint), after that switching to the present 90 metre drop course starting on Potterow, not counting the 2020 and 2021 editions which went virtual because of Covid and thus very thoroughly ineligible for any records beyond personal bests.

Even the 40 meter drop Marathon route used a double start with only one of the starting points (London street) compliant for the full Marathon, but the other starting point (Regent street) exceeding the maximum allowed drop even for the full Marathon.  This might not stand in the way of Rule 31.21 for the full marathon as the faster waves were starting from the lower starting point.

The Edinburgh Marathon held the IAAF Bronze Label from 2013 to 2017 as the only road race in Scotland ever; the concurrently organized half marathon never enjoyed the distinction.  From 2018 on, none of the Edinburgh races are listed.  (World Record eligibility is a requirement for a Bronze Label, but not vice versa.)

There is at least one differently named half marathon run in a superficially similar mix of Edinburgh and East Lothian environments currently offering a more modest but still non-compliant overall elevation drop.

If you don't know whether Rule 31.21.4 was followed, then Rule 31.21.3 becomes rather pointless.  In plain English, if you don't know whether the course was correctly marked in the streets, then it doesn't matter whether it looked compliant on the maps.

You are looking at a 2020 edition of certain document, i.e., an edition from a year in which no event EMF Edinburgh Half Marathon was actually run.  We can conclude that Rule 31.21.4 wasn't followed that year, although whatever the original plan has been is anyone's guess - we can reasonably interpolate between 2019 and the same route planned for 2022, or we could speculate that a course change was being proposed for 2020 and never materialized.  If you have earlier editions of the document, or if you talk to whoever provided it to you, you could likely find out how that entry came into being.

Suggested conclusion: Personal bests, for non-professionals, are eminently informal personal records.  Hobby runners will achieve more if they spend more time running than studying World Athletics rules for road races.  If somebody submits their half marathon time from Edinburgh as a qualification proof for another event, which happens all the time, it's not cheating unless they are misrepresenting the circumstances of their publicly tracked accomplishment somehow.  It's up to the recipient of such a proof to evaluate whether they care about Rule 31.21.3, and how much.  Likewise for any boasting rights and so on.
Comment: It used have a double start in Regend Road and London Road (see [here](https://www.clapa.com/get-involved/challenge/challenge-events/edinburgh-marathon-festival-2018/edinburgh-marathon-route-map-2014/)) and that was until 2017. London Road is at ~40 m but Regent Road is at least 70 m and the finish is only ~5 m; thus one of the starts was not even compliant back then (for the full marathon). They used [this elevation graphic](https://www.fionaoutdoors.co.uk/wp-content/uploads/2013/05/full_route_elevation.gif) which shows a <40 m drop but of course completely disregards the Regent Road start.
Comment: @olmomiau - Thank you!  This is getting really interesting.  I'll rewrite my answer or upvote yours (if you care to post one) whichever you prefer.


I have a mess in my head regarding redirect 301,mails and moving to a new website

Question: I'm new to the web world and i have a great mess in my head.
i got a project to build a website for a company and i did.
now this website was built with some cms and i built it with Wordpress.
So now i have to take care that some of the SEO meta tags will not ruin when moving to the new website, i used YOAST SEO plugin to do so.
Now my boss is keeping on asking about redirect 301 which i don't understand why do i need to use it?
if we dont transfer any campaigns and only moving to a new website why do i need it?
another problem is the mails on the domain.
the company has like 5 mails on the domain adress and the domain is sitting on the old company they used to work with,which are not cooperative.
how do i transfer the mails from their servers to a new one?
Thanks a lot.
Answer: The 301 redirects are for the newly created Url's.
Because every site has their own way or wwriting url's you need to make sure that you carry across the links to the old urls to the new url structure of the wordpress site.
Example
sitename.com/about_us.html is now sitename.com/about-us/ you will then need to redirect the old about_us url to the new one.
This ensures that any old indexed or shared pages don't server a page not found error.
Very important and can be done using the HTACCESS file or a redirect plugin.
Comment: ps. The mails are a totally different issue.
Comment: So how can i know what i need to redirect?
Comment: What you need to do is if you have a full copy of the old website, get all the url's and then redirect them to the new url's. Alternatively, if you do not have it then go ahead and check your google analytics and see what pages are serving 404 errors. ps. remember to mark this as answered if you are happy with the answer.
Comment: If i only want to save the SEO so i don't need to redirect right?
Comment: Recommended to redirect


how to get rid of descriptions that are linked to input types?

Question: I've got a question about the descriptions that are linked to input type options.
How do I get rid of it?
I've inherited a site that, for some reason, when I mouse over the options they start twitching as the text adjusts and tries to move to the second line. As a result is a pain to make the PHP selection.
I've seen other drupal sites that have the option without the description, but when I went to "Site configuration > Input formats" I didn't see any way to remove those descripts.
any suggestions or links to documentation would be welcome!
Answer: The Better Formats module is your friend here, you can use it to remove all or part of the format descriptions/options:

Better formats is a module to add more flexibility to Drupal's core input format system.
...

Set the default format per role.
Set the default format per content type.
Control allowed formats per content type.
Hide format tips.
Hide more format tips link.
Hide format selection for nodes, comments, and blocks seperately, forcing the default to be used.

...

(emphasis mine)
Comment: Thanks! this looks promising, I'll give it a try and let you know how it goes. Thanks for your help!


Converter um documento word(DOC,DOCX) para PFD usando PHP ou JavaScript

Question: Gostaria de saber se há a possibilidade de converter um arquivo Word (.doc,.docx) para um arquivo .pdf usando Php ou JavaScript (ou algo parecido). Por exemplo: o usuário faz o upload de um arquivo .docx que deve ser guardado apenas no formato .pdf --para isso fazer a conversão.
Answer: phpgearbox/pdf

Requer: http://phantomjs.org

Pode usar o https://github.com/phpgearbox/pdf, deve instalar via composer:
composer require gears/pdf:*

Depois no seu composer.json adicione:
"scripts":
{
    "post-install-cmd": ["PhantomInstaller\\Installer::installPhantomJS"],
    "post-update-cmd": ["PhantomInstaller\\Installer::installPhantomJS"]
}

Então após o upload selecione assim:
<?php
require_once 'vendor/autoload.php';

//Upload vem aqui

\Gears\Pdf::convert('<caminho do documento>/documento.docx', '<caminho aonde será salvo o pdf>/documento.pdf');

PHPOffice/PHPWord
Pode usar o https://github.com/PHPOffice/PHPWord que suporta diversos formatos:

odt
RTF
Word2007
HTML
PDF

Deve instalar via composer:
composer require phpoffice/phpword

Exemplo:
<?php
require_once 'vendor/autoload.php';

//Upload vem aqui

$source = '<caminho do documento>/documento.docx';

$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF');
$objWriter->save('<caminho aonde será salvo o pdf>/documento.pdf');

Comment: Segundo a documentação, é necessário instalar o libreoffice, no caso do phpgearbox. É isso msm?
Comment: @RenanLopes **libre-office-headless** ou **unocon**


Calling addToBackStack() on a Fragment that is added via ActionBar

Question: So basically, I have a simple Fragment that uses an AsyncTask to download a bitmap from a URL and then displays it inside an ImageView.
This is the Fragment's code:
public class TestFragment extends Fragment {

public TestFragment () {}

private String pictureUrl = "https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-prn1/532762_10150739418088211_1186720820_n.jpg";

private TextView sampleText;
private ImageView sampleImage;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment_view, container, false);
    String textToSet = "Section Three";

    sampleText = (TextView) root.findViewById(R.id.textView1);
    sampleText.setText(textToSet);

    sampleImage = (ImageView) root.findViewById(R.id.imageView1);
    DownloadImageTask task = new DownloadImageTask(pictureUrl, root, sampleImage.getId());
    task.execute();

    return root;
}
}

This same fragment is displayed three times, one per each tab inside an ActionBar. The problem I am having is that each time the user selects a different tab, the previous one is destroyed, and when the user navigates back to the original tab, the content needs to be redownloaded. I want to make sure that the least amount of resources are consumed (saving both Data, and valuable overHead processing).
Here is the Fragment Container activity:
public class LayoutContainer extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout_container);

    if (savedInstanceState != null) {
        return;
    }

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    Tab tab = actionBar.newTab()
            .setText(R.string.title_section1)
            .setTabListener(new TabListener<TestFragment>(
                    this, "one", TestFragment.class));
    actionBar.addTab(tab);

    tab = actionBar.newTab()
            .setText(R.string.title_section2)
            .setTabListener(new TabListener<TestFragment>(
                    this, "two", TestFragment.class));
    actionBar.addTab(tab);

    tab = actionBar.newTab()
            .setText(R.string.title_section3)
            .setTabListener(new TabListener<TestFragment>(
                    this, "three", TestFragment.class));
    actionBar.addTab(tab);

}

public static class TabListener<T extends Fragment> implements ActionBar.TabListener {

    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    public TabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
        }
        ft.replace(android.R.id.content, mFragment, mTag);
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.addToBackStack(null);
        ft.commit();
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}

I currently have it set to call ft.replace() on the OnTabSelected() method, but I had previously tried with ft.add(). Same goes for my current ft.addToBackStack() call inside OnTabUnselected(), I initially had it set for simply calling ft.detach() but that was doing the same thing I described as being my problem. It loads that way, but it has to download the image every single time.
Now, I have tried calling addToBackStack() but the app force closes stating the FragmentTransaction CANNOT be added to the back stack. I also tried in the past to cache the image offline, to avoid data consumption, the app would still need to parse the image from a local URI and use processing power.
Any ideas I can try?
FYI, Yes, I know that the same fragment is loading the same image on all three tabs. This is merely a test project that is intended to help me better understand the lifecycle of Fragments.
Answer: So After a lot of reading I realized that the important code block is not done on your TabListener but in fact done on each Fragment that you use.
The fragment WILL be detached when navigating away from it, but that does not mean I cannot retain it state using onSaveInstanceState(...).
Here is simple implementation of what was needed to retain the Fragment's state after it being detached.
public class TimelineFragment extends ListFragment{
...

public TimelineFragment () {}

public void onSaveInstanceState(Bundle outState){
    getActivity().getFragmentManager().putFragment(outState, TAG, this);
}

public void onRetoreInstanceState(Bundle inState){
    getActivity().getFragmentManager().getFragment(inState, TAG);
}
...
}

We are saving the Fragment by calling putFragment(), and restoring it by calling getFragment(). Pretty darn simple, and I never thought of it.
Answer: What I do when a user need an image from the web I first check if I've cached it or the image is at the SD. If the image can't be found at SD or cache I download the image, store it to SD and add it to the cache.
It usually goes something like this:
    Bitmap cacheBitmap = Database.getImageFromMemory(exercise.image, getActivity());

    if(cacheBitmap != null) {
        image.setImageBitmap(cacheBitmap);
        progressBar.setVisibility(View.GONE);
    }
    Bitmap localBitmap = ImageDownloader.decodeSampledBitmap(exercise.image, width, height, getActivity());

    if(localBitmap != null) {
        image.setImageBitmap(localBitmap);
        progressBar.setVisibility(View.GONE);
        Database.addBitmapToMemoryCache(exercise.image, localBitmap, getActivity());
    } else {
        ImageDownloader imageDownloader = new ImageDownloader(this.getActivity().getApplicationContext(), image, progressBar, width, height);
        imageDownloader.execute(exercise.image);
    }

Now this is not all the code but it gives you an idea about how to handle it. If you need more code feel free to ask, but it seems like you are on the right track.
Comment: Although you are answering a question that I had in mind, you did not really answer the thread's question, which was how to retain the instance state of a particular fragment when onDetach() was called.


Make Zod parse if available, and if not skip element

Question: I've searched through the documentation but find no solution for this case. I've got the following schemas.
const RelationSchema = z.object({
    guid: z.string(),
    createdDate: z.preprocess(castToDate, z.date()),
    modifiedDate: z.preprocess(castToDate, z.date()).nullable(),
    name: z.string(),
    publicationtype: z.string(),
    contentType: z.string(),
});
export const NobbRelationsSchema = z.array(NobbRelationSchema);

When parsing an array with NobbRelationsSchema.parse() I sometimes get back name as undefined. In these cases I would like Zod not to throw an error, but instead just remove that element and continue with the rest. A kind of filtering.
The option I see is to use safeParse and set name as optional and filter out these afterwards. However, it messes up the TypeScript type checking later in code, as name should always be set for valid elements.
Answer:
The option I see is to use safeParse and set name as optional and filter out these afterwards.

I think the simplest thing to do would be to add something special rather than using z.array: safe parse an unknown array and filter that. For example:
import { z } from 'zod';
// -- snip your code here --
type NobbRelation = z.TypeOf<typeof RelationSchema>;

function parseData(data: unknown) {
  // First parse the shape of the array separately from the elements.
  const dataArr = z.array(z.unknown()).parse(data);

  // Next parse each element individually and return a sentinal value
  // to filter out. In this case I used `null`.
  return dataArr
    .map(datum => {
      const parsed = RelationSchema.safeParse(datum);
      return parsed.success ? parsed.data : null;
    })
    // If the filter predicate is a type guard, the types will be correct
    .filter((x: NobbRelation | null): x is NobbRelation => x !== null);
}

For the most part this shouldn't limit your options. If you have other limitations you want to impose on the array, like a maximum length, you can do that when you process the unknown array.
If you have additional post processing you would like to do with transform, you could do that with a step after the filter.
If you want to have the type for NobbRelationsSchema you could derive that as:
type NobbRelations = NobbRelation[]; // Or just write this inline


Why is my code not recognizing the addActionListener(ActionListener e) method?

Question: My Problem
Compiling this class in NetBeans for Java. I'm trying to simply add an ActionListener to each JPanel. However, when I type in the code:
 `addActionListener(new SquareMouseListener);`

I get the error:
Cannot Find Symbol;
    method addActionListener(MinePanel.SquareMouseListener)
    location: class MinePanel

Here is the full code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.JPanel;

public class MinePanel extends JPanel{
final private int xPos, yPos;
final private int numXPanels, numYPanels;
final private boolean isBomb;

private MineFrame holderFrame;
private boolean seen;

public MinePanel(int xPos, int yPos, int numXPanels, int numYPanels, MineFrame holderFrame)
{
    this.xPos = xPos;
    this.yPos = yPos;
    this.numXPanels = numXPanels;
    this.numYPanels = numYPanels;
    if(Math.random()<.1)
    {
        isBomb = true;
    }
    else isBomb = false;
    seen = false;

    this.holderFrame = holderFrame;
    addActionListener(new SquareMouseListener());

}

@Override
public void paint(Graphics g)
{
    //Color thisColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
    g.setColor(Color.BLACK);
    g.fillRect(0,0,getWidth(),getHeight());
    g.setColor(Color.LIGHT_GRAY);
    g.fillRect(1,1,getWidth()-2,getHeight()-2);
}

private class SquareMouseListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent ae)
    {
        System.out.println("Action Performed");
    }
}
}

What can I do? Netbeans tells me to import:
import static com.sun.java.accessibility.util.AWTEventMonitor.addActionListener;

but I know that's not right because I tried it and it didn't work, and because addActionListener should be included in java.awt.event.*; import above.
Thanks in advance!
Comment: because MinePanel or JPanel doesn't define it
Answer: Just type this.add and press ctrl + space. You will see what type of listeners you can add to JPanel.
Probably you are needing the MouseListener.
this.addMouseListener(new YourListener());
where YourListener implements MouseListener interface.
Answer: I figured out what the problem was, and I wanted to post an answer in case anyone else was looking.
The problem exists in trying to add an ActionListener to a JPanel, which cannot be done. There is no predefined addActionListener() method for JPanel because it is meant as a lower level component. As @Jigar Joshi i said, JPanel does not define Action Listener events.
Thanks everyone for the help!


Como exibir mensagem de "carregando" enquanto a WebView está carregando?

Question: Preciso apresentar uma mensagem em tela enquanto o componente WebView não carregou por completo, mas não sei como detectar se ela já terminou de carregar o conteúdo. Aqui está o meu código:
return (
  <View style={styles.container}>
    <WebView
      style={styles.webview}
      setSupportMultipleWindows={false}
      ref={this.WEBVIEW_REF}
      javaScriptEnabled={true}
      allowsFullscreenVideo={true}
      onNavigationStateChange={this.onNavigationStateChange}
      source={{ uri: 'https://pei.educacao.mg.gov.br/login' }}  />
  </View>
);

Answer: Acho que uma boa solução aqui seria usar o compontente
ActivityIndicator
É um componente nativo que pode ser customizado, vai ser exibido no lugar do componente enquanto ele é carregador, e pode exibir ele baseado no state do seu componente, algo assim:
const App = () => {
  const [visible, setVisible] = useState(false);
  return (
      <View style={styles.container}>
        <WebView
          style={styles.webview}
          setSupportMultipleWindows={false}
          ref={this.WEBVIEW_REF}
          javaScriptEnabled={true}
          allowsFullscreenVideo={true}
          onNavigationStateChange={this.onNavigationStateChange}
          source={{ uri: 'https://pei.educacao.mg.gov.br/login' }}
          onLoadStart={() => setVisible(true)}
          onLoad={() => setVisible(false)}
        />
        {visible ? <ActivityIndicatorElement size="large" /> : null}
      </View>
  );
};

Aqui foi usado o visible e setVisiblie para controlar a visibilidade do WebView e mudar isso com onLoadStart e onLoad
Tenho um componente assim, foi baseado nesse código: react-native-show-progress-bar-while-loading-webview
Comment: A resposta está correta, apenas ressalto aqui para ter atenção quando utilizar arrow functions no render. Conforme mencionado na [documentação](https://pt-br.reactjs.org/docs/faq-functions.html#arrow-function-in-render): "Ao usar uma arrow function no render, uma nova função é criada cada vez que o componente é renderizado, que pode quebrar otimizações com base em comparação de identidade `on strict`." Eu prefiro evitar e faço uso de uma regra do ESLint para me alertar isso: [react/jsx-no-bind](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)


Can diffeomorphisms only be defined on real manifolds?

Question: I am looking at definitions of diffeomorphisms. In (Marathe, 2010) the author keeps the chapter (chap 3) on manifolds fairly general - except when defining diffeomorphims and differential maps, between manifolds. In this case they restrict their attention to real differentiable manifolds. My question is does this restriction need to be made? i.e. can you define diffeomorphims between non-real differentiable manifolds?
Comment: What is a "non-real differentiable manifold"?
Comment: @LordSharktheUnknown I assume the word 'real' here means that the charts of the manifold go to a real Banach space. So non-real would mean one whose charts go from the manifold to a Banach space which is not based on $\Bbb{R}^n$
Comment: @Quantumspaghettification There are a couple of things going on here. First of all, it's not clear what it means for a Banach space to be "based on $\mathbb{R}^{n}$". If a real (resp. complex) Banach space $V$ is finite dimensional, then it is isomorphic to $\mathbb{R}^{n}$ (resp. $\mathbb{C}^{n}$), for some $n < \infty$. If the Banach space is infinite-dimensional it's not clear (to me) what you mean by $\mathbb{R}^{\infty}$. Second, maybe you prefer to work over $\mathbb{C}$ instead of $\mathbb{R}$. In this case the answer is that complex differentiable is stronger than real differentiable.
Answer: There is indeed a notion of differentiable manifold over any complete field (see here). As long as you can make sense of what differentiability over a field means you can make sense of a differentiable manifold over that field. You just literally carry over the definitions for the real case.
However in some cases you are more interested in analytic manifolds and the notion of analyticity is usually stronger than differentiability. See here
for a treatment of the p-adic case.


Expression conversion using de Morgan's laws

Question: I'm sorry strongly, because it's a very dummy question... I have an example in the algebra of logic. I need to convert an expression using the rules of de Morgan - replace by the conjunction of disjunctions, and disjunction - on the conjunction.
I have a solution, but teacher said that it isn't correct. Please help!
Answer: Your middle term would have to be inverted.  Your first term is correct, but the rest are wrong.
DeMorgan's is used to get all terms the same AND/OR to allow the expression to be simplified.
$$\overline {x1\ x4} + x2\ \overline {x3}\ x4 + \overline{x1 + \overline {x1} \ x2 \ x3\ x4}$$
Take deMorgan's to eliminate NORs.
$$\overline {x1}+\overline {x4} + x2\ \overline {x3}\ x4 + \overline{x1} \cdot \overline{\overline {x1} \ x2 \ x3\ x4}$$
Take deMorgan's to eliminate NAND in last term.
$$\overline {x1}+\overline {x4} + x2\ \overline {x3}\ x4 + \overline{x1} \cdot ({x1}+\overline{x2}+\overline{x3}+\overline{x4})$$
$$\overline {x1}+\overline {x4} + x2\ \overline {x3}\ x4 + \overline{x1}{x1}+\overline{x1}\ \overline{x2}+\overline{x1}\ \overline{x3}+\overline{x1}\ \overline{x4}$$
Sum of Products, so it can be simplified.
Apply complement: $\overline X \cdot X = 0$ and identity $X + 0 = X$.
$$\overline {x1}+\overline {x4} + x2\ \overline {x3}\ x4 + 0 +\overline{x1}\ \overline{x2}+\overline{x1}\ \overline{x3}+\overline{x1}\ \overline{x4}$$
Look for common factors (Distributive) and apply annulment $X + 1 = 1$.
$$\overline {x1} (1+\overline{x2} + \overline{x3} + \overline{x4}) + \overline {x4} + x2\ \overline {x3}\ x4$$
$$\overline {x1} + \overline {x4} + x2\ \overline {x3}\ x4$$
The $x4$ term is not needed (redundant) because of the opposite term $\overline {x4}$.
So $ F = \overline {x1} + \overline {x4} + x2\ \overline {x3}$.