How to change a UICollectionView image's borderColor dynamically

Question: I am trying to build a UICollectionView that has an image inside each cell with a black borderColor. When the user touches the item I want it to change its borderColor to red and back.
I have achieved this, but it doesn't work at the first touch:
Video of the problem, I'm sorry but I don't know how to put videos in StackOverflow.
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = myCollectionView?.cellForItem(at: indexPath) as! CategoriesChoosingCell
    if cell.layer.borderColor == UIColor.red.cgColor {
        cell.imgView.layer.borderColor = UIColor.black.cgColor
    } else {
        cell.imgView.layer.borderColor = UIColor.red.cgColor
    }
    myCollectionView!.reloadItems(at: [indexPath])
}

This is the code that I created to achieve this.
Any advice? Thanks
Answer: Inside your model add
class Item {
  var isBlack = true // or false
}

Then inside cellForRowAt
let cell = ///
cell.imgView.layer.borderColor =  items[indexPath.row].isBlack ? UIColor.black.cgColor : UIColor.red.cgColor

Then
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let item = items[indexPath.row]
    item.isBlack  = !(item.isBlack)
    myCollectionView!.reloadItems(at: [indexPath])
}

this is useful for multiselection , for single declare a variable in your vc and check whether
selectedRow == indexPath.row

instead of
items[indexPath.row].isBlack

Comment: What is "items" in the items[indexPath.row]?
Comment: dataSource array of the table `var arr = [Item]()`
Comment: it gives me an error: Use of unresolved identifier 'items'; did you mean 'Item'?
Comment: I'm not using an UICollectionViewController, but this: class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource
Comment: Do I have to create it by myself? I used:
var myCollectionView: UICollectionView?

myCollectionView?.dataSource = self
        myCollectionView?.delegate = self
then I registered it
Comment: I don't have that array: as I said, it gives me an error
Comment: @Vipera74 you should have a datasource.  Can you post your `cellForItemAt` method?  That will tell us how you're populating the collectionView.
Comment: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! CategoriesChoosingCell
        cell.label.text = categories[indexPath.row]
        cell.photoButton.layer.borderColor = UIColor(named: "invertedDarkColor")?.cgColor
        return cell
    }
Comment: `categories` = `items`
Comment: It's just an array of String(?)


tensorflow estimator custom metrics: use sklearn metrics?

Question: Is there a way to use sklearn metrics as custom metrics in tf.estimator ? I have tried the custom score function below.
from sklearn.metrics import recall_score
def my_score(labels, predictions):
    return {'MARecall': recall_score(labels, predictions, average='macro')}

But it does not work :
eval_results = classifier.evaluate(input_fn=tf.estimator.inputs.numpy_input_fn(x={'x': val_x}, y=np.array(val_y), num_epochs=1, batch_size=20, shuffle=False))

... ...
... ...
<ipython-input-81-e433b0457af2> in my_acc(labels, predictions)
      1 def my_acc(labels, predictions):
----> 2     return {'WA': np.array(recall_score(labels, predictions, average='micro'))}
      3

/anaconda/envs/py35/lib/python3.5/site-packages/sklearn/metrics/classification.py in recall_score(y_true, y_pred, labels, pos_label, average, sample_weight)
   1357                                                  average=average,
   1358                                                  warn_for=('recall',),
-> 1359                                                  sample_weight=sample_weight)
   1360     return r
   1361

/anaconda/envs/py35/lib/python3.5/site-packages/sklearn/metrics/classification.py in precision_recall_fscore_support(y_true, y_pred, beta, labels, pos_label, average, warn_for, sample_weight)
   1023         raise ValueError("beta should be >0 in the F-beta score")
   1024
-> 1025     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
   1026     present_labels = unique_labels(y_true, y_pred)
   1027

/anaconda/envs/py35/lib/python3.5/site-packages/sklearn/metrics/classification.py in _check_targets(y_true, y_pred)
     70     """
     71     check_consistent_length(y_true, y_pred)
---> 72     type_true = type_of_target(y_true)
     73     type_pred = type_of_target(y_pred)
     74

/anaconda/envs/py35/lib/python3.5/site-packages/sklearn/utils/multiclass.py in type_of_target(y)
    242     if not valid:
    243         raise ValueError('Expected array-like (array or non-string sequence), '
--> 244                          'got %r' % y)
    245
    246     sparseseries = (y.__class__.__name__ == 'SparseSeries')

ValueError: Expected array-like (array or non-string sequence), got <tf.Tensor 'fifo_queue_DequeueUpTo:2' shape=(?,) dtype=int64>

Is there a way around this? I have a multi-class classification problem at hand, and need to log both macro and micro averaged scores during training and evaluation.
Answer: In order to work properly inside tensorflow training loop, metrics need to be updated. Every function in tf.metrics has an update_op for it. So it's strongly recommended to construct your custom metric using lower level functions like tf.metrics.true_positives I'm not aware of particular formula used in sklearn, you can define your own metric like this
def custom_metric(labels, predictions):
    metric1, update_op_m1 = tf.metrics.any_function(labels, predictions)
    metric2, update_op_m2 = tf.metrics.any_other_function(labels, predictions)
    output = tf.reduce_mean(metric1 + metric2)
    return output, tf.group(update_op_m1, update_op_m2) #Note that you need to group all update ops

Answer: One solution is to use the metric functions from https://github.com/guillaumegenthial/tf_metrics


Recommended SpamAssassin update channels?

Question: I'm currently using SpamAssassin on a couple of mail servers that I look after. SpamAssassin runs in the context of amavisd-new on those servers and with the usual bunch of plugins (FuzzyOCR, DCC, pyzor, razor). Currently the servers are getting their rule updates from the default SpamAssassin update channel (updates.spamassassin.org). Overall the setup seems to be reasonably effective but some types of spam seem to wander right through it even though I've made repeated attempts at training spamassassin. My guesstimate is that about 85%-90% of the spam that gets through policyd-weight makes it through the filters and it's been getting a lot worse recently as spammers are getting better at working their way through filters.
Can someone recommend additional sources of filters to make SpamAssassin more effective? So far I've found OpenProtect's update channel but are there others worth looking at?
Comment: Same question here too... It looks like there are not much fresh rules updates for spamassassin.
Answer: See http://wiki.apache.org/spamassassin/SareChannels, especially the dostech channels.
Comment: **The SARE rules are broken to the point of being harmful. Do not use them. - This is written in big bold letters in the page:)**
Answer: About the only resource that seems to stay current with SpamAssassin is spamtips. Check out their Ultimate Setup Guide - http://www.spamtips.org/p/ultimate-setup-guide.html
Specifically, the "Sought Rules" http://wiki.apache.org/spamassassin/SoughtRules is the channel I'm recommending.


Best way to design Domain with constant in grails

Question: I have lots of domain classes in my project. Many of them has type column. For example: User table has userType column, Book table has bookType column. I often pass these types into GSP g:select source by calling BookType.list() method. But problem is if GSP contains lots of g:select then I have to execute lots of redundant query.
And another problem is when I create a new Domain instance, I have to get these constant types from DB by following way
Book book = new Book();
book.bookType = BookType.findByName(BookTypes.COMICS);

Here I also have the same problem, I have to execute redundant query. Is there any good design to do all these stuff without executing these redundant queries?
Answer: If the types are not very volitile, I assume that is the case because I can see you defined an enum for type. Try using enum, totally -- I mean, don't bother with the database table at all to back that up. For example,
enum SomeType {

    TYPE1(1, "Type 1"),
    TYPE2(2, "Type 2"),
    TYPE3(3, "Type 3")

    final int id
    final String value

    private SomeType(int id, String value) {
        this.id = id
        this.value = value
    }

    // Might be needed for <g:select> tags, I'm not very sure
    int getKey() { id }

    static SomeType byId(int id) {
        values().find { it.id == id }
    }
}

Then, in your domain, do something like,
class SomeDomain {

    static constraints = {
        ...
        type nullable: false
        ...
    }

    ...
    SomeType type
}

Then, you can simply do something like this,
SomeDomain book = new SomeDomain(..., type: SomeType.TYPE1, ...);

Comment: @EmdadulSawon: The answer is already given, notice `byId(...)` method, I defined up there. You're right, `BookType.values()` is the way to go.
Comment: How to handle BookType.list() ?


Exibir PDF JSF primeFaces

Question: Pessoal estou criando um arquivo em pdf até ai beleza. Agora gostaria de exibir esse PDF em um formulário.Xhtml
Segue abaixo o código que uso para criar o pdf caso alguém possa me ajudar:
classe CriarPdfBean
package br.com.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.model.StreamedContent;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import br.com.model.PessoaModel;
import br.com.repository.PessoaRepository;
import br.com.util.Utilidades;

@Named
@RequestScoped
public class CriarPdfBean implements Serializable {
    private static final long serialVersionUID = 1L;

    Utilidades Util = new Utilidades();

    @Inject
    transient PessoaRepository pessoaRepository;

    private StreamedContent arquivoDownload;

    public StreamedContent getArquivoDownload() throws DocumentException, IOException {

        this.GeraPdf();

        return arquivoDownload;
    }

 public File GeraPdf() throws DocumentException, IOException {

        String imagem = "LISTRAS.pdf";

        String nomearquivosaida = "Teste.pdf";

        PdfWriter escritor = null;

        File arquivo = new File("C:/Sistema_Web/".concat(nomearquivosaida));

        Document documento = new Document(PageSize.A4);

        FileOutputStream fs = new FileOutputStream(arquivo);

        escritor = PdfWriter.getInstance(documento, fs);

        documento.open();

        PdfContentByte cb = escritor.getDirectContent();
        cb.setColorFill(BaseColor.BLACK);

        FontFactory.register("C://Windows//Fonts//arial.ttf");
        FontFactory.register("C://Windows//Fonts//arialbd.ttf");
        FontFactory.register("C://Windows//Fonts//COUR.TTF");

        List<String> variaveis= addVariaveis();
        PosicionaVariaveisPdf(escritor, "", cb,variaveis); // Sem Imagem
        //PosicionaVariaveisPdf(escritor, imagem, cb,variaveis); // Com Imagem Imagem
        documento.newPage();

        documento.close();
        escritor.close();
        return arquivo;

    }

}

Formulário para visualizar o Pdf
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Visualizar Pdf</title>
    </h:head>
    <h:body>

    </h:body>

public StreamedContent getPdf() {
           InputStream stream = null;
           try {
               // arquivo é do tipo java.io.File, mas o construtor também aceita o caminho do arquivo como String
               stream = new FileInputStream("C:/Projeto/Sistema_Web/");
           } catch (FileNotFoundException ex){
               ex.printStackTrace();
           }
           return new DefaultStreamedContent(stream, "application/pdf", "Teste.pdf");
        }

    public void setPdf(StreamedContent pdf) {}

erro
java.io.FileNotFoundException: C:\Projeto\Sistema_Web (Acesso negado)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at br.com.amarildo.view.CriarPdfBean.getPdf(CriarPdfBean.java:150)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at org.primefaces.component.media.Media.getValue(Media.java:77)
    at org.primefaces.component.media.MediaRenderer.getMediaSrc(MediaRenderer.java:125)
    at org.primefaces.component.media.MediaRenderer.encodeEnd(MediaRenderer.java:42)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
java.io.FileNotFoundException: C:\Projeto\Sistema_Web (Acesso negado)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at br.com.amarildo.view.CriarPdfBean.getPdf(CriarPdfBean.java:150)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.primefaces.el.InterceptingResolver.getValue(InterceptingResolver.java:53)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at org.primefaces.el.ValueExpressionAnalyzer.intercept(ValueExpressionAnalyzer.java:69)
    at org.primefaces.el.ValueExpressionAnalyzer.getExpression(ValueExpressionAnalyzer.java:45)
    at org.primefaces.util.DynamicResourceBuilder.build(DynamicResourceBuilder.java:49)
    at org.primefaces.component.media.MediaRenderer.getMediaSrc(MediaRenderer.java:125)
    at org.primefaces.component.media.MediaRenderer.encodeEnd(MediaRenderer.java:42)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
java.io.FileNotFoundException: C:\Amarildo\Sistema_Web (Acesso negado)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at br.com.amarildo.view.CriarPdfBean.getPdf(CriarPdfBean.java:150)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:53)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:72)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:643)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
mar 16, 2017 1:40:49 PM org.primefaces.application.resource.StreamedContentHandler handle
GRAVE: Error in streaming dynamic resource. null
mar 16, 2017 1:40:49 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/Sistema_Web] threw exception
java.lang.NullPointerException
    at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:83)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:72)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:643)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

java.io.FileNotFoundException: C:\Amarildo\Sistema_Web (Acesso negado)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at br.com.amarildo.view.CriarPdfBean.getPdf(CriarPdfBean.java:150)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:53)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:72)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:643)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
mar 16, 2017 1:40:49 PM org.primefaces.application.resource.StreamedContentHandler handle
GRAVE: Error in streaming dynamic resource. null
mar 16, 2017 1:40:49 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/Sistema_Web] threw exception
java.lang.NullPointerException
    at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:83)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:72)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:643)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

Comment: Dica: ao formatar o código, selecione-o por completo e clique em `{}` ou control+k.
Comment: Qual versão do primefaces vc está usando?
Comment: Obrigado por responder e versão é
org.primefaces
primefaces
5.1
compile
Answer: Você deve retornar um org.primefaces.model.StreamedContent ao invés de java.io.File.
Para isso pode fazer assim:
public StreamedContent getPdf() {
   InputStream stream = null;
   try {
       // arquivo é do tipo java.io.File, mas o construtor também aceita o caminho do arquivo como String
       stream = new FileInputStream(arquivo);
   } catch (FileNotFoundException ex){
       ex.printStackTrace();
   }
   return new DefaultStreamedContent(stream, "application/pdf", "Nome do arquivo.pdf");
}

public void setPdf(StreamedContent pdf) {}

set apenas pra reconhecer como uma propriedade válida.
Comment: Obrigado Luídne pelo Retorno vou testar aqui vlw

Exibir PDF JSF primeFaces


Let D = ${[ x\in R^2 :|x|\leq1}]$ Is there any onto, Continuous function from D to X. Where X = [-1 , 1]

Question: Let D = ${[ x\in R^2 :|x|\leq1}]$.Is there any on-to,continuous function from D to X. Where X = [-1 , 1]
My Attempt :
If I take an interior point $(y)$ in the interval whose pre-image is in the circle $(x)$ and exclude these two points from their domains we will get the domain D is still connected but the range set is not connected and function will remain continuous.
So there does not exist.
Am I right?
Comment: You have asked 3 questions in a two hours time interval. Take the time to breath, and to work by yourself.
Comment: @JeanMarie I got rewarded for this also... I got downvoted..
Answer: Sure,
$$ x\mapsto \sin2\pi|x|.$$
Comment: @sani Your logic seems to assume that the function is injective. After removing one $x$ that maps to $y$, there may still be other points that map to $y$
Comment: Can u please tell me where I was wrong in my logic?
Comment: My function was unnecessarily complicated by the way cause I assumed the question was about the *open* disk to the *closed* interval :)
Answer: Yes, you can just project onto the x-axis, by $f(x, y) = x$
Comment: If you exclude $(x)$ from $D$, there could still be another point $(x')$ in $D$ that maps to $(y)$, keeping the range connected.
Comment: Can u please tell me where I was wrong in my logic?@B. Mehta
Comment: ohhh..If it was One to One instead of onto my attempt would have been correct..Is not it?@B. Mehta
Comment: Yes, exactly, that argument would then work.
Comment: so what do u do? Where do u live?@B. Mehta
Comment: It seems U don't want to make personal conversation with me.. But u helped me a lot..bahat shukriya...@B. Mehta


How to add a different specific image for each page in a region?

Question: I want to have a different specific image on every page in the same region for each. I don't want to have to create separate blocks for each one. Is there an easier way? I will be getting the images from the directory.
Thanks
Comment: what you mean 'different image'? is that a content type image field? or you want lo load from an image directory? can you elaborate?
Answer: I assume that you have a content type which contains the field image and that image field have to displayed randomly in different pages. If so the solution would be

Create a block view and add the content type as criteria and the field:image
Remove all sort criteria and just add Global: Random as a sort criteria
specify only one content should be displayed in Pager option

That's it. Now you can render it and it will randomly display the image in each page
Comment: Hey good answer. but I think it's doesn't work for images. I've set up the same settings for my view and tested it. but the same image showing on every page. Have you tested it?
Comment: Yes I created one and its still working fine.. remove all sort criteria and just add global:random in sort criteria
Comment: Yes, Great. it's working. +1 to your answer.please mention in the answer that 'remove all sort criteria except `global:random` in sort criteria. :)
Comment: Glad it worked :)
Answer: Try the  Random Image Block module.

This Drupal 7.x Random Image Block module displays random images taken from a specified directory. It obtains its list of images to display by requiring a php file (imageList.php) which defines one function which returns a keyed-array of keyed-arrays. This random image block is not cached so a new image is displayed for each hit to the website.


Finding square of cube?

Question: A cube is built using $64$ cubic blocks of side one unit. After it is built, one cubic block is removed
from every corner of the cube. The resulting surface area of the body (in square units) after the
removal is?

$56$
$64$
$72$
$96$

Somewhere it explained as :
If $64$ cubic blocks are used to make the cube, it must be $4 \times 4 \times 4$ blocks.
The surface area is $6 \times 4 \times 4 = 96$ sq units.
Now picture this...each corner block shows off three faces. When it is removed, three new faces are exposed, thus there appears no net change in the exposed surface area$...
96 $ sq. units

Can you explain in formal way, please?
Comment: Is the text between the horizontal line and the highlighted question an answer from some key, and the highlighted question is from you asking to expand that answer? Your formatting is not clear in what comes from you and what comes from another source.
Comment: Please see Ques-5 at page no-1 http://www.gate.iisc.ernet.in/GATE2016questions/S5_CS.pdf , and explanation here http://www.algebra.com/algebra/homework/playground/test.faq.question.1019445.html
Comment: Your answer is correct and formal
Answer: As long as the removed corner cubes do not intersect, you can reason on each separately. The following image (cube on the left) gives you a visual insight:

For the removed small cube, its top surface projects orthogonally on the bottom (the mid gray "rhombus"), the right-most side projects on the darker gray rhombus, the front side on the light gray square.
Another way is to split the empty small cube as follows:

and see the three-sided outside corner leaves space to the same three-sided carved corner.
Comment: Thanks for very very nice explanation.

Finding square of cube?


Image not showing up correctly when In my left container

Question: So I'm relatively new to Css and trying to learn it by doing some projects , I'm almost through with this one , but the thing that I'm not getting right is that the image is not taking up the same height as that of the left div , why is this so , even though I have set the height of left container to be 100% of the main container
I'm attaching the code for your reference

@import url(https://fonts.google.com/specimen/Fraunces);
@import url(https://fonts.google.com/specimen/Montserrat);
:root {
  --Dark-cyan: hsl(158, 36%, 37%);
  --Cream: hsl(30, 38%, 92%);
  --Very-dark-blue: hsl(212, 21%, 14%);
  --Dark-grayish-blue: hsl(228, 12%, 48%);
  --White: hsl(0, 0%, 100%)
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-size: 14px;
  background-color: var(--Cream);
  color: black;
}

.container {
  background-color: var(--White);
  width: 33%;
  height: 33%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  margin: 4rem auto;
}

.left-side {
  width: 50%;
  background-size: cover;
  background-position: center;
  height: 100%;
  overflow: hidden;
}

.left-side img {
  width: 100%;
  object-fit: cover;
}

.right-side {
  width: 50%;
  height: 100%;
  padding: 2rem;
}

h5 {
  font-family: "Montserrat", sans-serif;
  font-weight: 500;
  letter-spacing: 0.4rem;
  color: var(--Dark-grayish-blue);
  margin: 0 0 2em 0;
}

h1 {
  font-family: "Fraunces", serif;
  font-weight: 700;
  letter-spacing: 0.07rem;
}

.content {
  font-family: "Fraunces", serif;
  font-weight: 500;
  color: var(--Dark-grayish-blue);
  margin: 1.75em 0;
  line-height: 1.5;
}

.prices {
  font-family: "Fraunces", serif;
  display: inline;
  margin: 0 0.5em;
}

.old-price {
  text-decoration: line-through;
}

.new-price {
  font-weight: 700;
  color: var(--Dark-cyan);
}

.btn {
  padding: 0.5em 1.8em;
  background-color: var(--Dark-cyan);
  color: var(--White);
  width: 95%;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin: 1.75em 0 0 0;
}

.btn:hover {
  opacity: 0.5;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <title>Frontend Mentor | Product preview card component</title>

PERFUME

Gabrielle Essence Eau De Parfum

A floral, solar and voluptous interpretation composed bu oliver polge,Perfumer-Creator for the house of chanel

$149.99

$169.99

        <button class="btn">
         Add To Cart
      </button>

Comment: Do you mean there is still some space above and below the image? try changing the `width` property of `.left-side img` to `height
Answer: .left-side{
    width: 50%;
    background-size: cover;
    background-position: center;
    height: 100%;
    overflow: hidden;

}
.left-side img{
    width:100%;
    object-fit: cover;

Only thing i can think of is that you have given it two different properties, try combining these in the same css stack
Answer: .container {
    /* ... */
    align-items: stretch; /* Add this line */
}

.left-side {
    /* ... */
    height: 100%; /* <- Remove this line */

    /* Add these two lines: */
    min-height: 100%;
    background-image: url("images/image-product-mobile.jpg");
}

Also, remove the  from the left-side div; now it's on the CSS (.left-side), so you can cover and center the background.
Demo:
https://jsfiddle.net/adqb1v8r/
Comment: I have Tried out what you said but What I'm actually getting is just a blank container on left side without any Image , When I inspect it , it shows that the height of the container is 0 , why is this so
Comment: @Kannav02 I added a fix (remove `height: 100%;`) and a demo.
Comment: oh this fixed it , but why did you did this ? Thank You So Much!


Is the convergence linear, superlinear, quadratic?

Question:
The Fibonacci sequence is generated by the formulas
  \begin{cases}  r_0=1 & r_1=1\\ r_{n+1}=r_n+r_{n-1} \end{cases}  The
  sequence therefore starts out $1, 1, 2, 3, 5, 8, 13, 21, 34, \dots$.
  Prove that the sequence $[2r_n/r_{n-1}]$ converges to $1+\sqrt{5}$. Is
  the convergence linear, superlinear, quadratic?

Proof: Suppose we are given the following recurrence relation $$r_{n+1}=r_n+r_{n-1},$$ where $r_0=1$ and $r_1=1$. We want to show that the sequence $[2r_n/r_{n-1}]$ converges to $1+\sqrt{5}$. i.e. We want to show that $$\lim_{n\to \infty} \dfrac{2r_n}{r_{n-1}}=1+\sqrt{5}.$$ Before, we prove this limit is true, we need to find the solution to this recurrence relation with the given initial conditions.
The corresponding characteristic polynomial to the recurrence relation is $$p(\lambda)=\lambda^2-\lambda-1=0.$$ Hence the roots of the characteristic polynomial are $\lambda=\dfrac{1\pm\sqrt{5}}{2}$. Hence the general solution for the relation is $$r_n=A\left(\dfrac{1+\sqrt{5}}{2}\right)^n+B\left(\dfrac{1-\sqrt{5}}{2}\right)^n.$$
Next, we want to find the values of $A$ and $B$ with the given initial conditions. With the starting values $r_0=1$ and $r_1=1$, we get the following system of equations:
\begin{cases}
1=r_0=A+B \\
1=r_1=A\left(\dfrac{1+\sqrt{5}}{2}\right)+B\left(\dfrac{1-\sqrt{5}}{2}\right)
\end{cases}
Multiply the first equation by $\dfrac{1+\sqrt{5}}{2}$.
\begin{cases}
\dfrac{1+\sqrt{5}}{2}=r_0=A\left(\dfrac{1+\sqrt{5}}{2}\right)+B\left(\dfrac{1+\sqrt{5}}{2}\right) \\
1=r_1=A\left(\dfrac{1+\sqrt{5}}{2}\right)+B\left(\dfrac{1-\sqrt{5}}{2}\right)
\end{cases}
Next, subtract equation (1) from equation (2), which results with
$$\dfrac{\sqrt{5}=1}{2}=B\sqrt{5} \iff B=\dfrac{\sqrt{5}-1}{2\sqrt{5}}.$$
Furthermore $$A=1-\dfrac{\sqrt{5}-1}{2\sqrt{5}}=1-\dfrac{\sqrt{5}}{2\sqrt{5}}+\dfrac{1}{2\sqrt{5}}=1-\dfrac{1}{2}+\dfrac{1}{2\sqrt{5}}=\dfrac{1}{2}+\dfrac{1}{2\sqrt{5}}=\dfrac{\sqrt{5}+1}{2\sqrt{5}}.$$
Hence, the general solution for the relation is
\begin{equation*}
\begin{aligned}
r_n & =\left(\dfrac{\sqrt{5}+1}{2\sqrt{5}}\right)\left(\dfrac{1+\sqrt{5}}{2}\right)^n+\left(\dfrac{\sqrt{5}-1}{2\sqrt{5}}\right)\left(\dfrac{1-\sqrt{5}}{2}\right)^n \\
& =\dfrac{1}{\sqrt{5}}\left[\dfrac{(1+\sqrt{5})^{n+1}-(1-\sqrt{5})^{n+1}}{2^{n+1}}\right].
\end{aligned}
\end{equation*}
Now we can show that the sequence $[2r_n/r_{n-1}]$ converges to $1+\sqrt{5}$.
\begin{equation*}
\begin{aligned}
\lim_{n\to \infty} \dfrac{2r_n}{r_{n-1}}
& = \lim_{n\to \infty} \dfrac{\dfrac{2}{\sqrt{5}}\left[\dfrac{(1+\sqrt{5})^{n+1}-(1-\sqrt{5})^{n+1}}{2^{n+1}}\right]}{\dfrac{1}{\sqrt{5}}\left[\dfrac{(1+\sqrt{5})^{n}-(1-\sqrt{5})^{n}}{2^{n}}\right]} \\
& = \lim_{n\to \infty} \dfrac{(1+\sqrt{5})^{n+1}-(1-\sqrt{5})^{n+1}}{(1+\sqrt{5})^{n}-(1-\sqrt{5})^{n}} \\
& = \lim_{n\to \infty} \dfrac{\dfrac{(1+\sqrt{5})^{n+1}-(1-\sqrt{5})^{n+1}}{(1+\sqrt{5})^n}}{\dfrac{(1+\sqrt{5})^{n}-(1-\sqrt{5})^{n}}{(1+\sqrt{5})^n}} \\
& = \lim_{n\to \infty} \dfrac{(1+\sqrt{5})-(1-\sqrt{5})\cdot \left(\dfrac{1-\sqrt{5}}{1+\sqrt{5}}\right)^{n}}{1-\left(\dfrac{1-\sqrt{5}}{1+\sqrt{5}}\right)^{n}} \\
& = \dfrac{(1+\sqrt{5})-(1-\sqrt{5})\cdot 0}{1-0} \\
& = 1+\sqrt{5}.
\end{aligned}
\end{equation*}
Note: Since $0<\dfrac{1-\sqrt{5}}{1+\sqrt{5}}<1$, then $$\lim_{n\to\infty} \left(\dfrac{1-\sqrt{5}}{1+\sqrt{5}}\right)^{n}=0.$$
To finish the question I need to state whether the convergence is linear, superlinear, or quadratic. I know that

If the limit equals 0, then the convergence is superlinear.
If the limit equals 1, then the convergence is linear.
If the limit equals 2, then the convergence is quadratic.

However, my limit is equal to $1+\sqrt{5}$. Am I missing something?
Comment: Check [rate of convergence](https://en.wikipedia.org/wiki/Rate_of_convergence) on wikipedia.
Comment: Are you sure that the value of the limit of the expression determines the speed of convergence ?
Comment: No. I just assumed because it was a follow-up question that I needed to use the value of the limit.
Comment: So to make sure I need to compute the limit of $$\lim_{n\to \infty} \dfrac{|r_{n+1}-L|}{|r_n-L|}$$ where $L=\dfrac{1+\sqrt{5}}{2}$ and then just use my conditions above to determine that it's either superlinear, linear, or quadratic?
Comment: You are using $r_n$ here in your most recent comment, but you aren't asked whether the terms in the Fibonacci sequence converge and how fast they do (*they dont*), you are asked to discuss the convergence of *the ratio of consecutive Fibonacci terms*.  I.e. you should be investigating $$\lim\limits_{n\to\infty}\frac{|\frac{r_{n+1}}{r_n}-L|}{|\frac{r_n}{r_{n-1}}-L|}$$  According to the wiki article, if the limit exists and is strictly between $0$ and $1$, then it converges linearly.  If the limit exists and is zero, then it converges superlinearly.  Quadratic is a special case of superlinear
Comment: So then what should my $L$ be? Is $1+\sqrt{5}$?
Comment: You need to have $L$ be whatever the limit is so that you have both the numerator and the denominator approaching zero simultaneously.  In the way I wrote it above, $L$ would be $\frac{1+\sqrt{5}}{2}$.  If you want $L$ to be $1+\sqrt{5}$ then instead of $\frac{r_{n+1}}{r_n}$ you should use instead $\frac{2r_{n+1}}{r_n}$.  Similarly the fraction on the bottom will change as well.
Comment: You can save yourself a lot of writing and make it easier to  check your  algebra for errors, if you let $(1+\sqrt 5\;)/2=f$ and ($-1+\sqrt 5\;)/2=g=-f^{-1}.$
Comment: @JMoravitz I did the limit using the second approach however I got $\dfrac{2+\sqrt{5}}{2}$ has the value of the limit. But $\dfrac{2+\sqrt{5}}{2}>2.$
Comment: That should not be possible.  That would imply that the earlier you are in the sequence the closer you are to the limit, which directly contradicts the concept of convergence.  If done correctly, the *only* possible values should be in the range $[0,1]$.
Answer: Trying to match your notation: Let $r_n$ represent the $n$'th Fibonacci number, let $q_n=\frac{2r_n}{r_{n-1}}$, and let $L=1+\sqrt{5}$
In the first part of the problem, you should have shown $\lim\limits_{n\to\infty}q_n=L$
We now investigate what happens to the limit:
$$(\dagger):~~~~~~~~~\lim\limits_{n\to\infty}\frac{|q_{n+1}-L|}{|q_{n}-L|}$$
$q_{n+1}$ will tend to be closer to $L$ than $q_{n}$ implying that $|q_{n+1}-L|<|q_{n}-L|$ implying that the limit $(\dagger)$ above will if it exists be somewhere in the range $[0,1]$.  If the limit is $1$ we say that $q_n$ converges to $L$ "sublinearly", if the limit is between $0$ and $1$ we say that $q_n$ converges to $L$ "linearly", and if the limit is $0$ we say that $q_n$ converges to $L$ "superlinearly."  In the case that it is sublinear or superlinear, we can futher classify just how quickly or slowly that is by raising the denominator to various powers and investigating those limits.
Now... again, we are tasked with investigating the limit $(\dagger)$.  Remembering that $q_n=\frac{2r_n}{r_{n-1}}$ and that $r_n=\frac{\varphi^n-\psi^n}{\sqrt{5}}$ where $\varphi=\frac{1+\sqrt{5}}{2}$ and $\psi=\frac{1-\sqrt{5}}{2}$.  Notice that $\frac{L}{2}=\varphi$ and that $\varphi\cdot \psi=-1$.
We have then $q_n=2\cdot \frac{\varphi^n-\psi^n}{\varphi^{n-1}-\psi^{n-1}}$.  We have now $q_{n+1}-L=2\cdot \frac{\varphi^{n+1}-\psi^{n+1}-\varphi(\varphi^n-\psi^n)}{\varphi^n-\psi^n}$
$=2\cdot \frac{\varphi^{n+1}-\psi^{n+1}-\varphi^{n+1}-\psi^{n-1}}{\varphi^n-\psi^n}=2\cdot \frac{-\psi^{n+1}-\psi^{n-1}}{\varphi^n-\psi^n}$
Similarly we calculate $q_{n}-L$ to be $2\cdot \frac{-\psi^n-\psi^{n-2}}{\varphi^{n-1}-\psi^{n-1}}$

 As a sanity check here, notice that $\lim\limits_{n\to\infty}|q_n-L|=0$ as the numerator approaches zero while the denominator grows large.  This confirms, or rather rederives, what we should have learned in the earlier part of the question.

So this leads us to our limit $(\dagger)$ being:
$\lim\limits_{n\to\infty}\frac{|q_{n+1}-L|}{|q_n-L|}=\lim\limits_{n\to\infty}\frac{|2\cdot \frac{-\psi^{n+1}-\psi^{n-1}}{\varphi^n-\psi^n}|}{|2\cdot \frac{-\psi^n-\psi^{n-2}}{\varphi^{n-1}-\psi^{n-1}}|}=$
Which after a bit more algebra and a little bit of handwaving results in
$\frac{\frac{|\psi^2+\psi|}{|\psi+1|}}{\varphi}=\frac{|\psi|}{\varphi}=\frac{\sqrt{5}-1}{1+\sqrt{5}}\approx 0.382$

 The handwaving comes into play when we try to move the different parts of the fraction around to get like groups together.  The group of the form $\frac{\varphi^n-\psi^n}{\varphi^{n-1}-\psi^{n-1}}$ we notice that as $\lim\limits_{n\to\infty}\psi^n=0$ the only terms that truly survive are the $\varphi'$s.  This can be made more formal, but this suffices for now.

I.e. twice the ratio of consecutive fibonacci terms converges to $L$ linearly.


JSF e JavaScript

Question: Estou com a seguinte duvida:
Como o JSF trabalha com o JavaScript ?
Vou ser mais especifico. Eu estou em um projeto onde estou usando JSF (primefaces), porém não consigo fazer algo simples com JavaScript, que seria um
var btnCarregaAnexo = document.querySelector('carregaAnexo')
btnCarregaAnexo.style.display = 'none'

Apresenta um erro no console, de que a variável btnCarregaAnexo esta "null".
Porém no button que estou querendo pegar, está com "id" = carregaAnexo;
Já testei também com getElementById, mas sem sucesso...
Então conclusão, o JSF (primefaces) ou o JBoss, que estou utilizando, interfere no caminho dos ID'S? Não consigo de maneira nenhuma pegar um componente com JS...
Obrigado, desculpe se não me expressei da melhor maneira, mas estou a disposição para conversarmos.

Alterei para realizar a seleção por classes CSS e o erro persiste…
XHTML

JavaScript
var btnCarregaAnexo = document.querySelector('botaoAnexo');
            btnCarregaAnexo.style.display ='block';

CSS
.botaoAnexo{
    display: none;
}

ERRO NO CONSOLE
Uncaught TypeError: Cannot read property 'style' of null

Comment: Em qual posição você colocou esse script? No head ou no final do body?
Comment: Posta seu código
Comment: Bom, não sei qual o seu conhecimento de **Javascript**, mas, não é assim que o `querySelector` funciona, pelo seu exemplo o correto seria **querySelector('#carregaAnexo')**.
Comment: Então LeAndrade, eu testei tambem com '#' porem apresenta mesmo erro, postei logo abaixo com uma tentativa de pegar pela classe CSS, mas apresenta o mesmo erro no console...

Laerte o script esta no fim do body !, mas ja testei tambem com o script no inicio do body, testei tambem colocar o script em outra file... e importar ele no html, mas sempre mesmo erro...
Comment: Os ids dos componentes jsf são gerados dinamicamente. Você precisaria definir uma class e usar o findByClassName.
Comment: vc não considerou usar o componente de upload de arquivos do primefaces?
Comment: AdrianoGomes, estou utilizando o componente upload do prime, porém a versao do prime qe utilizo é uma versão mais antiga, e esta versao não é acessivel(deficientes visuais)... E quero tentar fazer com que fique acessivel utilizando javaScript, porém nem o basico esta dando certo, não sei se o Jboss interfere, ou primefaces não esta deixando eu pegar componentes cm JS.
Comment: Vc está tentando fazer algo via javascript que eu creio ser mais fácil via EL. O que exatamente vc precisa fazer? Controlar a renderização do commandButton?
Answer: Se vc precisa controlar o style de um componente, tente usar EL. O exemplo abaixo exibe um div em escala de cinza se ele estiver aguardando encerramento (o controlador.aguardandoEncerramento é um booleano):
<h:panelGroup id="pnlFoto">
    <ui:param name="escalaDeCinza" value="#{controlador.aguardandoEncerramento ? 'filter: grayscale(1);' : ''}" />

</h:panelGroup>

Nesse caso, só é necessário fazer um update no pnlFoto para alterar o style.

JSF e JavaScript


Non Focusable ListView?

Question: I have a list of items that my user can select from, but I want them all to be "focused".
At the moment, only the focused item has dark text - the others are all greyed out, but I want them all to be equally visible.  Is that possible? How would I do that?
Answer: Nvermind - I figured it out. I can use android:textColor and android:textColorHighlight on the each item to achieve this.
Answer: focused means, a single view have the (input-) or (view-) focus. known by that only one
view can have a focus the same time.
i think you want to color a row?

Non Focusable ListView?


Volume of Revolution. Am I doing it right?

Question: How do I find the volume when revolving the region bounded by $y=1-\frac{1}{2}x$, $y=0$, and $x=0$ about the line $ x=-2$?
Would it be $x=2-2y$
so radius $r(y) = 2-2y -(-2) $ => $r(y)= 4-2y$
$π\int (4-2y)^2 dy$ ?
What would be my limits of integration? Would it be from 0 to 2?? yes?
Answer: Hint: You've done everything right except for the integration limits. Since you are integrating over $y$, the limits should be from $y=0$ to where the given line intersects the $y$-axis, which is not $y=2$.


Can the same entity type (bundle) have different fields in different instances?

Question: I have a question about adding fields to an entity I've defined in a drupal 7 module upgrading from d6 which has 4 types.  The modules get a list of fields from a 3rd party server and if the user enables them through the admin interface they are added to the node object as cck fields before the node gets saved.  Can I add fields to a bundle in a similar fashion using field_create_instance?  Is it okay if the same type entity has different fields in different cases, or does the field get added to every entity of that type once it's added?
There are different resources (think data coming from different servers with potentially different fields) each with the same 4 entity types, and different fields could be enabled for each resource.  I'm considering adding the fields which are enabled to the entity before it is saved.  Entity type 1 could have different fields selected for resource 1 and resource 2.  This is the first time I have used d7 entities which is why I'm asking how they work.
Answer: field_create_instance already adds a field instance to a bundle. You can't add fields to an entity type or an entity itself.
I'm not quite sure if I understood you right:
Guess 1:
You want for example two nodes of type person where one has a field phone number and the other one not, which is not possible. Your node type has to define all possible field types, but they may be optional, so if the external system doesn't provide data for it, simply leave it empty.
Guess 2:
You want to adjust a whole entity type (this means all existing entities) based on external systems, user input or whatever. Thats possible with the Field CRUD API.
Comment: I'm going to end up adding fields to my bundles with field_create_instance and just leave them empty if they are not enabled on a particular server.  Thanks for helping me hash this out.  Sorry I was so confusing in my question.
Comment: Glad to help!

What just came into my mind: The terms *field* and *field instance* are a little confusing. *field instance* doesn't refer to an actual field value (which could be assumed in terms of OOP).
For example there is the field *text* and the field instance would be the field *first_name* connected to the node type *person*.


Alter Statement Filling Transaction Log File Fast and not completing

Question: I have ran below alter statement which was part of deployment but while running this tr-log file getting full quickly.
ALTER TABLE [dbo].[MY_ORDER_LINE] ALTER COLUMN [CREATED_BY]  INT NULL ;   --This has not yet been updated – column data type is still 'smallint'

ALTER TABLE [dbo].[MY_ORDER_LINE] ALTER COLUMN [LAST_UPDATED_BY] INT NULL;  --  This has not yet been updated – column data type is still 'smallint'

ALTER TABLE [dbo].[MY_ORDER_LINE] ALTER COLUMN [LAST_UPDATE_LOGIN] INT NULL;  --  This has not yet been updated – column data type is still 'smallint'

GO

SQL Server Version:
Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64)
Oct 19 2012 13:38:57
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)

OS: Windows Server 2008 R2 standard 64 bit
RAM: 8 GB
Log file size: 53 gb
I have arranged the space but now this query is running from past 120 mins and not completing.
There is no blocking also.
What to do to get it complete?
Answer: First, try each individual ALTER statement by itself, see if that helps.
Unfortunately, beyond that, you can't do an ALTER in batches of, say, 1000 records like you can with an UPDATE or DELETE.
You can do the following, though:

Create a new table [My_Order_Line_New] with the proper column definitions
Do an INSERT to copy all rows from the old table into the new. This you can do in batches, so your log doesn't explode.
Rename the tables: change [My_Order_Line] to [My_Order_Line_Old], then [My_Order_Line_New] to [My_Order_Line].
Answer: Switch to Simple Recovery, run the ALTER statement, then switch back to Transactional Recovery.
Comment: This answer works in many cases, but not for an `ALTER TABLE`. Even in simple mode, the entire transaction must complete at once or be rolled back.
Comment: I have tried this currently these alter statement running on SIMPLE RECOVERY


$L^1$ integrability of a Fourier transform of a given function

Question: For a $L^1$ function $\phi : R^n \to C$, we define its Fourier transform by
$$\hat\phi{(\xi)}= \int_{R^n}\phi(x) e^{-2\pi ix\cdot\xi} \,dx, \,\,\,\,(\xi \in R^n).$$
Fix $0 < \alpha < 1$. Let $f:R^n \to C$ be defined by
$$f(x):= e^{-\|x\|^{\alpha}}.$$
Similarly for $1 \le j \le n$, we define
$$g_j(x):= x_je^{-\|x\|^{\alpha}}.$$
How to show that $\hat {f}$and $\hat{g_j},(1 \le j \le n)$, i.e. Fourier transform of $f$ and $g_j$ respectively belong to $L^1(R^n)$ ?
Note:$ f,g_j$ do not belong to Schwartz class as $0 <\alpha <1.$
Answer: So first the intuition: these functions decay quickly at infinity so their Fourier transforms are regular. However the functions are not smooth at $x=0$, which implies that their Fourier transforms do not decay so fast at infinity. So, to know if they are in $L^1$, we need to isolate the singular part and see what decay it gives.
Now the proof. Take $\varphi \in C^\infty_c$ a smooth function supported on the unit ball such that $0\leq \varphi \leq 1$ and $\varphi=1$ around $0$. Then we write
$$
f = f_0 + f_1 = \varphi \, f + (1-\varphi)\,f.
$$
It is not difficult to check that $f_1$ is a Schwartz function, and so its Fourier transform is $L^1$ (since it is also a Schwartz function).
Now it remains to look at $f_0$, which is compactly supported but not infinitely smooth. Using the fact that the Fourier transform of a product gives a convolution and a second order Taylor series for the exponential,
$$
\widehat{f_0} = \sum_{k=0}^\infty \frac{(-1)^k}{k!} \widehat \varphi * \widehat{|x|^{k\alpha}} = \widehat\varphi  + \sum_{k=1}^\infty \frac{(-1)^k}{k!} \widehat \varphi * \mathrm{pf}(|x|^{-n-k\alpha})
$$
where $\mathrm{pf}(|x|^{-c})$ is the Hadamard finite part of $|x|^{-c}$, which is essentially the tempered distribution that coincides with $|x|^{-c}$ outside of the point $0$, and is what appears when doing the Fourier transform of fractional polynomials (see e.g. here on MSE). Convolution with these functions could also be written as a fractional Laplacian. The point is that $\widehat\varphi$ being a Schwartz function, it is not difficult to prove that the functions
$$
\psi_c = \widehat\varphi * \mathrm{pf}(|x|^{-c})
$$
are smooth and behave like $|x|^{-c}$ for large values of $x$. Hence
$$
\widehat{f_0} = \widehat \varphi  + \sum_{k=1}^\infty \frac{(-1)^k}{k!} \psi_{n+\alpha k}.
$$
This is a (uniformly converging) sum of smooth functions that decay faster and faster when $k$ grows. Hence the decay of $f_0$ is the same as the decay of the first one, that is $\widehat{f_0}\sim |x|^{-n+\alpha}$ at infinity, and so is integrable.
The Fourier transform  of the functions $g_j$ are just the derivatives of $\widehat f$ and so decay even faster. Hence they are also integrable.

Remark: here is another method perhaps more elementary, but which does not give the asymptotic behavior. It uses the fact that $H^s\subset \mathcal F(L^1)$ when $s>n/2$. Indeed, by the Cauchy-Schwartz inequality
$$
\int_{\Bbb R^n} |\widehat{f}| \leq C_s \left(\int_{\Bbb R^n} |\widehat{f}|^2 (1+|2\pi\,x|^{2s})\,\mathrm d s\right)^\frac{1}{2} = C_s \left(\|f\|_{L^2}^2 + \|f\|_{\dot{H}^s}^2\right)^\frac{1}{2}
$$
with $C_s = \int_{\Bbb R^n} \frac{\mathrm d x}{1+|2\pi\,x|^{2s}} < \infty$. Of course $f$ is in $L^2$. Now, taking $k$ derivatives with $k> n/2$ it is easy to get that
$$
|\nabla^k(e^{-|x|^\alpha})| \leq C \left(|x|^{k\alpha-k} + |x|^{\alpha-k}\right) e^{-|x|^\alpha}.
$$
Up to removing some decay in the exponential, we can just keep the worst local term, that is
$$
|\nabla^k(e^{-|x|^\alpha})| \leq C\, |x|^{\alpha-k}\, e^{-|x|^\alpha/2}.
$$
Hence,
$$
\|f\|_{\dot H^k} \leq C \int_{\Bbb R^n} \frac{e^{-|x|^\alpha}}{|x|^{2k - 2\alpha}} \,\mathrm d x
$$
which is finite as soon as $2k - 2\alpha < n$, that is $k< n/2 + \alpha$. Of course, here one needs $n/2 < k < n/2 + \alpha$ with $k$ an integer, which is not always possible (it works if $n$ is odd and $\alpha > 1/2$). With more work, the assumption that $k$ is an integer can be relaxed (by working with a fractional Laplacian for example, or via Littlewood-Paley techniques).


How to link 2 docker containers one with backend code and other with react both are on node.js

Question: I have 2 docker containers running one with node which is my backend code and another with react build running on node, how do I link between the containers so that my react API calls are fulfilled via my node backend container.
I'm running the containers using ECS and routing using ALB, both my containers are in different target groups and the same cluster.
Actual Result:-
Both the containers are running individually but there is no response to the API calls made using react.
Expected Result:-
API requests should be fulfilled using the other node container.
Answer: There is no way to link two different task definition, You should run both containers in one task definition. you can only link container if it is the single task definition otherwise you need to use service discovery or internal load balancer if the there is two different task definition and having two different target group so better to use an internal load balancer or service discovery.
If you want to configure in the same task definition then you can refer or access the container using container name along with port. But I will not suggest docker linking in case of AWS I think such an approach is not good for production.
One of the biggest disadvantages is that if you want to scale one container in the service, all the container will be the scale of the task definition.
You can link this way, Go to task definition -> Container -> Networking -> just add the name of the second container as pasted in the image.

You can explore here and here further about service discovery and load balancer.


Who assigns subnet masks?

Question: When I type ipconfig I get a list of data points as expected, one of them being,
IPv4 Address. . . . . . . . . . . : 192.168.43.106(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0

My laptop is currently connected to WiFi via my cellphone.
What I don't understand is where does the subnet mask come from? Does my phone give it to my laptop? And if so, why does it need to allow so many devices? Shouldn't it be more like 255.255.255.250? Only 3 or 4 devices can use my phone as a hotspot at the same time anyway.
I'd really appreciate if someone could help me clear up this confusion
Answer: Subnet masks are determined by administrators. A device will either receive them through DHCP or it will be configured manually.
I'm not sure what the DHCP settings are on your phone, but in private networks it doesn't really matter if you waste address space. It's always best practice to use a subnet mask that fits your needs best.
I also think you meant 255.255.255.248 would be a better subnet mask for the DHCP on your phone. This subnet mask will provide 6 usable IP addresses.
Answer: Subnet size is set by the device providing the IP addressing.   I'm sure that your phone by default is large is because that works for the majority of cases.
Also 255.255.255.250 is not a valid subnet mask.  Here's a handy link.
Comment: Why don't the manufacturers of the phone set a smaller subnet mask?

Who assigns subnet masks?


find all $ a \in \mathbb{R}$?

Question:
find  all $a \in \mathbb{R}$ such that   if $f$  is  any contnious   function on $[1,3]$  with  $\int_{1}^{ 3}f(x) dx= 1$ , then  there  exist  some  $x_0 \in (1,3)$  with $f(x_0) = a$

My attempt :
I take $f(x) = \frac{x}{4}$  then  $\int_{1}^{ 3}f(x) dx= 1$
It  is given that  $x_0 \in (1,3)$  and we  have   $f(x) = \frac{x}{4}$
so  $'a'$  will be   $\frac{1.1 }{4}, \frac{1.2}{ 4},............,\frac{2.9}{4}$
Is its  true ?
Comment: @jasmine Because for $f(x)=\frac12$ you don't have $x_0\in(1,3)$ with $f(x_0)=\frac{1.2}4$
Comment: Don't forget that $f$ is any continuous function, so consider the function $f(x)=\frac{1}{2}$. Shouldn't $a=\frac{1}{2}$ ?
Comment: okss@FareedAbiFarraj but  why not  $a= 1.2 /4$ ?
Answer: Since $f$ is any continuous function, with the condition that $\displaystyle\int_1^3 f(x) dx=1$, then $f(x)=\frac{1}{2}$ is an example of such a function.
So there must be some $x_0 \in (1,3)$ such that $f(x_0)=a$ but since this $f$ is a constant function then $\forall x\in (1,3)$, $f(x)=\frac{1}{2}$ thus $a=\frac{1}{2}$
It remains to prove that for any other function with these condition we can find an $x_0\in (1,3)$ such that $f(x_0)=\frac{1}{2}$, we can see this clearly by knowing the integral gives us the area under the curve, if the function gets below the horizantal line $y=\frac{1}{2}$ then for sure in some other point the curve will be above this line in order for the area to stay equal to $1$; which means that definetly at some point $x_0 \in (0,3)$ we will have $f(x_0)=\frac{1}{2}$
Comment: More precisely : the mean value theorem for integrals can be applied to any function on the interval to get the desired conclusion
Answer: Find a non-trivial continuous function $f: [1,2] \rightarrow \mathbb{R}$ such that $\int_1^2 f(x) d\text{x} = 0$ and $f(1) = f(2) = 0$ (a spike function would do, for example), then extend $f$ to $[1,3]$ such that $\int_1^3 f(x)d\text{x} = 1$, for example by having $f(x) = 2(x-2)$ for $x \in [2,3]$. This proves that the set consists of the whole $\mathbb{R}$.

find all $ a \in \mathbb{R}$?


How to get the value of the clicked radiobutton?

Question: There are many radiobuttons got from database in my form :
             ...
';
                        for ( $i = $data["figure"]["cnt"] / 2; $i < $data["figure"]["cnt"]; $i++) {
                         $tabFields[4]['html'] .= '

                        	';

                        }
                    $tabFields[4]['html'] .= '

' ;

                        for ( $i = $data["figure"]["cnt"] / 2; $i < $data["figure"]["cnt"]; $i++) {
                        $tabFields[4]['html'] .= '

                        <input type="radio" name="fig_code" value="' . $data["figure"][$i]["fig_code"] . '"  />
                        	';

                        }
                        $tabFields[4]['html'] .= '

I want to know the value of the radio which is clicked. How to achieve that ?
Answer:
I want to know the value of the radio which is clicked

If I understand the question right and clicked = checked, you want this:
$('input[type="radio"]:checked').val()

Answer: By make use of val();
var selected = $('input[type="radio"]:checked').val()

Answer: something like this
$(document).ready(function(){
      $("input[type='radio']:checked").val();
});

Answer: Try this if you to get the selected radio button's value only once the page is loaded.
$(document).ready(function(){
    var selected = $('input:radio:checked').val();
});

If you want to get the value of selected radio button, whenever there is a change, you can try this:
$(document).ready(function(){
    $('input:radio').change(function(){
        var selected = $('input:radio:checked').val();
    });
    var selected = $('input:radio:checked').val();
});

Comment: I bound the "change" event to all radio. So is it equivalent as your code ?
Comment: Yes. If you want to bind the change event to all the radio buttons in the page, the above given code will work.


Stylesheet com cookie funciona só na segunda vez

Question: Tenho um site que o style é definido pelo cookie "padrao" ou "escuro"
Porém, se você entra a primeira vez nele ele grava o cookie com valor "padrao", mas, não assume o style.
Ele só funciona quando dá um reload na página.
Na primeira linha da página header.php tem:
<?php require('/style/css_cookie_check.php'); ?>

na parte do stylesheet:
<link id="style_cor" rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style/<?php echo $estilo_cor; ?>/style.css" type="text/css" media="screen" />

Na página "css_cookie_check.php":
<?php
    global $estilo_cor;
    if(!isset($_COOKIE['cor_estilo'])) {
        $estilo_cor = setcookie('cor_estilo', 'padrao', (time() + (2 * 3600)));
    } else {
        $estilo_cor = $_COOKIE['cor_estilo'];
    }
?>

Answer: Esta linha sua tem um problema:
$estilo_cor = setcookie('cor_estilo', 'padrao', (time() + (2 * 3600)));

Ela não vai pegar o valor do cookie setado, apenas um true ou false.
Veja uma solução que atribui valor à variável para a página atual e para o cookie:
<?php
    global $estilo_cor;
    if( isset( $_COOKIE['cor_estilo'] ) ) {
        $estilo_cor = $_COOKIE['cor_estilo'];
    } else {
        $estilo_cor = 'padrao';
        setcookie( 'cor_estilo', $estilo_cor, ( time() + ( 2 * 3600 ) ) );
    }
?>

Se o cookie estiver setado, usamos seu valor. Senão, define $estilo_cor e cria um cookie com o que foi definido.
A propósito, seria legal definir um padrão pro nome das coisas, você está usando $estilo_cor, e 'cor_estilo'. Pode até funcionar, mas só gera confusão manter um código assim (já basta o PHP, que é todo inconsistente).
Tirando o global:
Na verdade, nesse caso é até perigoso fazer desta forma, pois cria a ilusão que dá pra chamar a função em outras partes do código, o que não é verdade por se tratar de um cookie, mas fica como exemplo de como usar algo de outro source sem global:
css_cookie_check.php
<?php
    function getStyle() {
       if( isset( $_COOKIE['cor_estilo'] ) ) {
           $estilo_cor = $_COOKIE['cor_estilo'];
       } else {
           $estilo_cor = 'padrao';
           setcookie( 'cor_estilo', $estilo_cor, ( time() + ( 2 * 3600 ) ) );
       }
       return $estilo_cor;
   }
?>

E no PHP principal:
<?php
   require('/style/css_cookie_check.php');
   $estilo_cor = getStyle();
?>

Na verdade, no seu caso, não precisaria nem do meu exemplo e nem do global, mas deixei pra ilustrar.
Comment: Cookies não podem ser usados exatamente no mesmo momento que são criados. Eles só assumem depois que a página é recarregada. Isso é padrão. Essa dica do @Bacco deveria resolver, porque quando não existe, além de setar o cookie, ele já define na variável o valor padrão (que poderá ser utilizado no primeiro acesso).
Comment: Clayderson Ferreira, não sabia disto do cookie. Valeu man
Comment: Demais cara, valeu!!!
Comment: Esse negócio de escopo em PHP é meio chato. Eu evito ao máximo usar `global`. Global me lembra escopo de variável de ASP clássico, dá calafrios.


Apache Spark: is the show() function an expensive and unsafe operation?

Question: In Apache Spark, I know that when you perform actions on the data that ends up collecting the result on the driver end, for example, applying a collect() on the data, is an unsafe operation that can lead to an Out Of Memory Error if the collected size is larger than what the driver can house in its memory.
Is the show() function, which is applied to dataframes, a function that can lead to a OOM for the same reason or can I safely use the show() function (maybe for debugging reasons)?
Answer: show is as safe as the execution plan of the evaluated Dataset. If the Dataset contains wide transformations (non-broadcasted joins, aggregations, repartitions, applications of window functions) or resource hungry narrow transformations (expensive UDF calls, "strongly" typed transformations with wide schema) calling show can trigger  executor failure.
Unlike collect it will fetch only a small subset of data (20 records by default). So excluding local mode it is unlikely it will ever trigger driver failure.
Even if none of the above is true, it is still possible that show will evaluate all records. This might happen if pipeline contains highly restrictive selections (filter) which result in spare leading partitions.
Overall show, same as similar restricted operations like take (with small n) are as safe as you can get, but cannot guarantee successful execution.


singular covariance matrices = estimates of zero random-effects variance in a model with random-intercepts

Question: I was wondering why for mixed-effects models that have degenerate or singular covariance matrices (some linear combinations of the random effects are estimated to having no variability) are said to correspond to:

Estimates of zero random-effects variance in a model with random-intercepts only

To make this discussion concrete, please let's use the model fit below (in R).
library(lme4)

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

fit <- lmer(math ~ ses*sector + (ses|sch.id), data = hsb)

lme4::allFit(fit) # You'll see several `boundary (singular) fit` messages under different optimizations
```

Answer: I'm not sure where the allFit function comes from, but your code produces errors on my system.
Anyway, I don't really agree with the premise that a model with a singular fit are said to correspond to estimates of zero random-effects variance in a model with random-intercepts only.
That could be one reason, but in my experience it is more often the case that singular models occur when the random effects are overfitted - very often too many random slopes - relative to the data. Another common reason is where there is very little variation in the slopes within some grouping factor, such that random slopes for the variable in question are not needed. It is easy to construct a simple example:
set.seed(15)
n.school <- 20

dt <- expand.grid(sch.id = 1:n.school, ses = 1:10)
dt$Y <- 1
X <- model.matrix( ~ ses, data = dt)

myFormula <- "Y ~ ses + (ses | sch.id)"

foo <- lFormula(eval(myFormula), dt)
Z <- t(as.matrix(foo$reTrms$Zt))

betas <- c(1, 2)

s1 <- 3   #  SD of random intercepts
s2 <- 0.1 #  SD of random slopes

rho <- 0.4  # correlation between intercepts and slopes

cormat <-  matrix(c(s1, rho, rho, s2), 2, 2)  # correlation matrix
covmat <- lme4::sdcor2cov(cormat)    # covariance matrix (needed for mvrnorm)

umat <- MASS::mvrnorm(n.school, c(0, 0), covmat, empirical = TRUE)  # simulate the random effects

u <- c(rbind(umat[, 1], umat[, 2]))  # lme4 needs the random effects in this order interleaved)

e <- rnorm(nrow(dt), 0, 2)   # residual error

dt$Y <- X %*% betas + Z %*% u + e

lmer(myFormula, dt) %>% summary()

which resuls in a singular fit (correlation estimated at 1) where the real problem is that there is too little variance among the random slopes.
In my opinion, the reason we see this so often is due to the infamous paper by Barr et al (2013) "Keep it Maximal" where the advice is basically to fit random slopes, with correlations, for all fixed effects. Even one of the models in their paper has a singular fit, which they were not aware of (see the paper by Bates 2015 Parsimoneous Mixed Models for more details).
Comment: Rob, I think [this question](https://stats.stackexchange.com/questions/490891/specifying-the-random-part-of-a-mixed-model-in-r) is right up your alley.
Comment: Thanks Robert! The above quote was from Douglas Bates' et al where he criticizes keeping it maximal. Also, if we do `lme4::rePCA(fit)` does that reveal the problem better?
Comment: `rePCA` does  a principal components analysis on the VCV matrix which is a good way to identify where the problem in the random effects structure is.  I've written an answer about this previously: https://stats.stackexchange.com/questions/449095/how-to-simplify-a-singular-random-structure-when-reported-correlations-are-not-n/449122#449122
Comment: Note that the quote you took from Bates' paper is missing the end of the sentence: *"This corresponds to estimates of zero random-effects variance in a model with
random-intercepts only **or a correlation of ±1 in a model with correlated random intercepts and slopes**."*
Comment: Ahh, well, it means that if you had very small variance of random intercepts, even with meaningful variation in random slopes, you could get a singular fit. If you change the seed to 5, s1 to 0.1 and s2 to 3 in the above code you will get a singular fit for that reason.
Comment: I see, lastly, the singularity could also occur if no correlation exists between the slopes and intercepts as well? Does `rePCA()` reveal whether that could be the case?
Comment: No, I don't see why a correlation of zero would cause a singular fit. Go ahead and run the code above in a loop with different seeds, with s1=2 and s2=1 and rho=0. I bet you won't find many cases of singular fit
Comment: But won't the model be overparameterized and not converged when we ask for a correlation that in realty (or at least in the current dataset) doesn't exist?
Comment: No, a correlation of zero is a perfectly valid correlation.
Comment: Will take a look soon


How to switch python3 versions on MacOs

Question: I am using python version 3.10.2 but I want to downgrade to 3.9 because it is not compatible with a library in my project. How can I do this with terminal command?
So when I type python3 --version my version is 3.10.2 I want to downgrade it. IDE is pycharm
Comment: Personally, I use `conda` (just install miniconda and a virtual environment with python-3.9 for that project). Do no change system interpreter. The operating system may require python 3.10. (so use a parallel version just for your project, and possibly use a different environment for every project). -- PyCharm and conda are well integrated. PyCharm can use many python versions in parallel (also within the same project)
Comment: Depends on what [package manager](https://stackoverflow.com/q/58218592/10794031) you are using. If you are using and installation of the Python interpreter without virtual environment you'll have to download and install a new Python version. You don't say what kind of venv you are using so there's no way to answer the question.
Answer: Install pyenv with Homebrew on macOS:
brew update
brew install pyenv

Define your vitual env variables:
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
source ~/.bash_profile
Restart your shell so the path changes take effect

exec "$SHELL"

Check the available python versions:
pyenv install --list

Install the required python version:
pyenv install 3.9

Set it as your global version:
pyenv global 3.9

Comment: thank you for your response
 I do not understand this kind of codes(below). Will I write to terminal? also what should I write for $HOME?

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
source ~/.bash_profile
Restart your shell so the path changes take effect

exec "$SHELL"
Comment: I did same thing..

still;

pyenv global 3.9.0......

admin@192 aynam % python3 --version......
Python 3.10.2
Comment: You can also clone the repo to get the latest version of pyenv `git clone https://github.com/pyenv/pyenv.git ~/.pyenv'

How to switch python3 versions on MacOs


A quotient space is isomorphic if we have closedness

Question:
Let $\mathcal{X}$ and $\mathcal{Y}$ be Banach spaces, $T\in L(\mathcal{X},\mathcal{Y})$, $\mathcal{N} =\{x: Tx = 0\}$, and $M = range(T)$. Then $\mathcal{X}/\mathcal{N}(T)$ is isomorphic to $\mathcal{M}$ iff $\mathcal{M}$ is closed.

I know that by definition $T(x)$ is closed, it seems pretty obvious that $M$ is then closed unless I am missing something but I don't grasp the idea of how the quotient space $\mathcal{X}/\mathcal{N}(T)$ is isomorphic to $M$ depending on $M$ being closed.
Any ideas or suggestions is greatly appreciated I am really confused with this one.
Answer: One side is trivial: if the two spaces are isomorphic, then $\mathcal{M}$ has to be closed since $\mathcal{X}/\mathcal{N}(T)$ is closed.
Fundamental algebra shows $\mathcal{X}/\mathcal{N}(T)\cong\mathcal{M}$ as linear spaces. More precisely, $T$ induces a canonical bijective linear operator $\bar{T}:\mathcal{X}/\mathcal{N}(T)\rightarrow\mathcal{M}$ by $\bar{T}:x+\mathcal{N}(T)\mapsto T(x)$. It's plain that $\bar{T}$ is continuous by checking quotient topology. But there is still one more step to go to make $\bar{T}$ an isomorphism.
What role does $\mathcal{M}$ being closed play? One may recall the open mapping theorem. If $\mathcal{M}$ is complete, thus a Banach space, then $\bar{T}$ is an open map, hence an isomorphism. But any closed subspace of a complete space is complete. Now we're done.
Answer:
Let $\mathcal{X}$ and $\mathcal{Y}$ be Banach spaces, $T\in L(\mathcal{X},\mathcal{Y})$, $\mathcal{N}(T) =\{x: Tx = 0\}$, and $\mathcal{M} = \textrm{range}(T)$. Then $\mathcal{X}/\mathcal{N}(T)$ is isomorphic to $\mathcal{M}$ iff $\mathcal{M}$ is closed.

Proof :
($\Rightarrow$) Suppose that $\mathcal{X}/\mathcal{N}(T)$ is isomorphic to $\mathcal{M}$. By Exercise 15 a.) (in Folland's book), we know that $\mathcal{N}(T)$ is a closed subspace of  $\mathcal{X}$. By Exercise 12 d.), we know that $\mathcal{X}/\mathcal{N}(T)$ is a complete normed vector space, that is, it is a Banach space.
Let $S : \mathcal{X}/\mathcal{N}(T) \to \mathcal{M}$ be an isomorphism. Let us prove that $\mathcal{M}$ is closed in $\mathcal{Y}$.
Let $\{y_j\}_{j\in \mathbb{N}}$ in $\mathcal{M}$ such that $y_j \to y \in \mathcal{Y}$.  Then $\{y_j\}_{j\in \mathbb{N}}$ is a Cauchy sequence. Since $S^{-1}$ is continuous linear mapping, it is uniformly continuous and so $\{S^{-1}(y_j)\}_{j\in \mathbb{N}}$ is a Cauchy sequence in $\mathcal{X}/\mathcal{N}(T)$. Since $\mathcal{X}/\mathcal{N}(T)$ is complete, there is $x \in \mathcal{X}/\mathcal{N}(T)$ such that $S^{-1}(y_j) \to x$. Since $S$ is continuous, we have
$$ y_j = S(S^{-1}(y_j)) \to S(x)$$
So we have that $y=S(x)$, which means $y \in \mathcal{M}$. So we proved that $\mathcal{M}$ is closed in $\mathcal{Y}$.
($\Leftarrow$) Suppose $\mathcal{M}$ is closed. Then we have that $\mathcal{M}$ (with the norm of $\mathcal{Y}$) is a complete normed vector space, that is, $\mathcal{M}$ is a Banach space.
Let $S : \mathcal{X}/\mathcal{N}(T) \to \mathcal{M}$, defined by $S(x+\mathcal{N}(T))=T(x)$.  By Exercise 15 b.) (in Folland's book), we know that $S \in L(\mathcal{X}/\mathcal{N}(T), \mathcal{Y})$ and so $S \in L(\mathcal{X}/\mathcal{N}(T), \mathcal{M})$.
It is easy to prove that $S$ is bijective. In fact, if $S(x+\mathcal{N}(T))=0$, then $T(x)=S(x+\mathcal{N}(T))=0$, then $x\in \mathcal{N}$, which means $x+\mathcal{N}(T)=0+\mathcal{N}(T)$. So $S$ is injective. Since $\textrm{range}(S)=\textrm{range}(T)=\mathcal{M}$, $S$ is surjective.
Now, apply the Inverse Mapping Theorem (corollary 5.11 in Folland's book) and we can conclude that $S$ is an isomorphism.
(Or, if you prefer, you can apply the Open Mapping Theorem, theorem 5.10 in Folland's book, to conclude that  $S$ is an isomorphism.)
Remark: Note that in ($\Rightarrow$) part, the fact that the isomorphism $S$ is linear has a critical role, so we can, from continuity of $S^{-1}$, ensure $S^{-1}$ is uniformly continuous.
Compare to the following exemple: $f: \mathbb{R} \to (-\frac{\pi}{2},\frac{\pi}{2})$, defined by $f(x) =\arctan (x)$. Note that $f$ is a continuous bijective function whose inverse is continuous, but $(-\frac{\pi}{2},\frac{\pi}{2})$ is not closed in $\mathbb{R}$.