"support files should use exactly same version" Android studio error

Question: I have following dependencies in my app-level build.gradle file
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.android.support:cardview-v7:27.0.2'
}

These works fine without any error. But, When I try to put a new third party dependency of CircleImageView implementation 'de.hdodenhof:circleimageview:2.2.0', the gradle build fails and there is error on implementation 'com.android.support:appcompat-v7:27.0.2' line saying All com.android.support libraries must use the exact same version.... I am wondering how this third party library creating problem in support libraries. What is wrong there?
Comment: Also update dependencies for cardview  `implementation 'com.android.support:cardview-v7:27.1.1'`
Comment: @NileshRathod Thanks, worked fine!
Comment: Possible duplicate of [All com.android.support libraries must use the exact same version specification](https://stackoverflow.com/questions/42374151/all-com-android-support-libraries-must-use-the-exact-same-version-specification)
Comment: Use this `implementation 'com.android.support:appcompat-v7:27.1.1'`
Comment: @NileshRathod still there is an error
Comment: Because that third party library internally also uses the app compat library and because the version used by your project is different from the library version, it gives the error. But your app should work fine even with the error.
Answer: That library is implementing support libraries as well, but different versions. Specifically, it uses the support-annotations 27.1.0 library.
There are two things you can do.

Update your dependencies. 27.0.2 is outdated. 27.1.0 is as well, but less so.
Exclude that library from your implementation and implement it yourself:
implementation ("de.hdodenhof:circleimageview:2.2.0") {
    exclude group: "com.android.support" module: "support-annotations"
}
implementation 'com.android.support:support-annotations:27.1.1'

You should update all your support dependencies to 27.1.1.
Answer: The third party library internally uses the app compat library and because the version used by project is different from the library version, it gives the error. Updating appcompat, design and cardview dependencies to version 27.1.1 worked fine as follows.
dependencies {
  implementation fileTree(dir: 'libs', include: ['*.jar'])
  implementation 'com.android.support:appcompat-v7:27.1.1'
  implementation 'com.android.support.constraint:constraint-layout:1.0.2'
  implementation 'com.android.support:design:27.1.1'
  testImplementation 'junit:junit:4.12'
  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
  implementation 'com.android.volley:volley:1.1.1'
  implementation 'com.github.bumptech.glide:glide:4.8.0'
  implementation 'com.android.support:cardview-v7:27.1.1'
  implementation 'de.hdodenhof:circleimageview:2.2.0'
}

Comment: [It's OK to Ask and Answer Your Own Questions](https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/)
Comment: @Mohsen I have to wait 2 days for accepting my own answer
Comment: Seems this is what TheWanderer told you in his answer. Answering your own question should be reserved for questions that have no duplicates on SO and for new information not to state which advice you followed
Answer: The support libraries should have the same version as the other dependencies which are related.
Change them to v 27.1.1 (The point is they should have the same version):
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'

And then if you saw any errors which points to "should have same version", run :
./gradlew dependencies

To see which library is using old version.
Mostly, it can be fixed by adding the updated version of the library (same as the support library) in your build.gradle dependencies.
Comment: Why 28? The library uses 27.1.1 and OP uses 27.0.2, which means their compile and target SDK are set to 27. This would cause more problems. And `support-media-compat` has nothing to do with CircleImageView.
Comment: They _should_ use the same version. Using 28.0.0 means they _aren't_.
Answer: If you want all support libraries including third party libraries internally use the same support library version, then add below code in your project level gradle
ext {
    support_library_version = '27.1.1'
}

subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->

            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex')) {
                details.useVersion "$support_library_version"
            }
        }
    }
}


Google App Engine PHP requests seem to always go to the catch all handler

Question: I am new to google app engine and am using PHP to create a website for a project on google app engine. The website will need to have multiple files. At the moment I am able to go on one page and when I click the 'contact' link to go to the contact page, the page still says the same and doesn't change.
My app.yaml handlers are:
<code>handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css))
  static_files: \1
  upload: (.*\.(gif|png|jpg|ico|js|css))

- url: /.*
  script: mainpage.php

- url: /contact.php
  script: contact.php
</code>
So I can go to mainpage.php and when I click on the 'contact' link, the URL chances to ****.appspot.com/contact.php. But the page doesn't actually change to 'contact.php'
Answer: Invert your handlers. The way handlers work is that it looks top to bottom, as soon as there's ONE match, it returns that.
So if your first handler is a catch all, there is no way to go to the second one :)
Comment: Oh ok that makes sense. Thank you. So how would both handlers look?
Comment: The same way, just inverse them. Put your main one AFTER the contact one


Convex Functions and their maximums?

Question: Show that the maximum of a convex function on a convex polytope occurs at one of the extreme points of the polytope. I am really stuck here and don't know where to begin.
Comment: Let $M$ be the set of points where the maximum is attained. Show that $M$ is an extremal set of the polytope. Hence it contains at least one extreme point.
Comment: How would I show that M is an extremal set of the polytope?
Answer: Hint: For the following reasoning use

The definition of convexity of a function
The fact that the convex polytope over which the function is maximized contains all convex combinations of points in it. In fact every point in the convex polytope can be expressed as a convex combination of it's extreme points.
The definition of an exterme point (that it cannot be written as a linear combination of two distinct points).

General idea of proof (you need to write it in more detail): Consider the point $$x_0=λx_1+(1-λ)x_2 \quad \in C$$ where $λ \in [0,1]$ and $x_1, x_2 \in C$. Since $f$ is convex (I named your convex function $f$) you know that $$f(λx_1+(1-λ)x_2)\le λf(x_1)+(1-λ)f(x_2)$$ for every $x_1, x_2 \in C$ (I named the convex polytope $C$), $λ \in [0,1]$. But this implies that the inner point $x_0:=λx_1+(1-λ)x_2$, for $λ \in (0,1)$ (which is in $C$, since $C$ is convex) cannot have a maximum since it's value under $f$ is dominated by the RHS of the above expression (where $x_1$ and $x_2$ can be chosen to be extreme points).
(Note of course, than when the inequality holds with a equality, then the maximum is attained in the inner point $x_0$ as well as in the extreme points $x_1, x_2$ so the theorem is again valid.)
Comment: I am not able to see when point 3 is used. Aren't 1 and 2 enough since $\lambda f(x_1)+(1-\lambda)f(x_2)\leq max\{f(x_1), f(x_2)\}$ and $x_1$ and $x_2$ can be extreme points?
Answer: for example:
Now, note that for any fixed $t\geq0$, the function $g_{t}:R^{r}\rightarrow R$ defined by $g_{t}(x)=-\frac{1}{2}\sum_{k=1}^{r}ln(1+2tx_{k})$ is convex. Hence, its maximum over the simplex $\{x\in R^{r}: \sum_{k=1}^{r}x_{k}=1,x\geq 0\} $ is attained at a vertex of the simplex.
 so $g_{t}(x)=-\frac{1}{2}\sum_{k=1}^{r}ln(1+2tx_{k})\leq-\frac{1}{2}ln(1+2t)$
I want to ask how to understand this?

Convex Functions and their maximums?


Explanation of ROC data output in SAS Logistic Regression

Question: I have run the logistic regression in SAS on binary data set available online.
http://www.ats.ucla.edu/stat/data/binary.csv
below is the sample output:
<code>_PROB_   _POS_ _NEG_ _FALPOS_   _FALNEG_    _SENSIT_    _1MSPEC_
0.941210953 1   127 0   272 0.003663004 0
0.928012776 2   127 0   271 0.007326007 0
0.927643195 3   127 0   270 0.010989011 0
0.925136849 4   127 0   269 0.014652015 0
0.921044923 5   127 0   268 0.018315018 0
0.91222972  6   127 0   267 0.021978022 0
0.903114817 7   127 0   266 0.025641026 0
0.902970992 8   127 0   265 0.029304029 0
0.901363504 9   127 0   264 0.032967033 0
0.897147605 10  127 0   263 0.036630037 0
0.891836956 11  127 0   262 0.04029304  0
0.891466706 12  127 0   261 0.043956044 0
0.89118058  13  127 0   260 0.047619048 0
0.887809967 14  127 0   259 0.051282051 0
0.886286835 15  127 0   258 0.054945055 0
0.884789828 15  126 1   258 0.054945055 0.007874016
0.883748771 16  126 1   257 0.058608059 0.007874016
0.883658492 17  126 1   256 0.062271062 0.007874016
0.883005072 18  126 1   255 0.065934066 0.007874016
0.881642156 19  126 1   254 0.06959707  0.007874016
0.881636206 20  126 1   253 0.073260073 0.007874016
0.881161673 21  126 1   252 0.076923077 0.007874016
0.880570499 21  125 2   252 0.076923077 0.015748032
0.879641459 22  125 2   251 0.080586081 0.015748032
0.878868995 23  125 2   250 0.084249084 0.015748032
</code>
...
How should I interpret this and how these values are calculated?
Thanks.
Comment: This is a rather broad question. Is there a specific term or concept you don't understand here? Each row in the above represents the classifier's performance for a specified decision threshold (_prob_). It tell you how many 0s and 1s were correctly predicted at different thresholds.
Answer: As the writer of the first logistic regression procedure in SAS I feel quite guilty about putting measures such as proportion "classified" "correctly" in the procedure, and when the procedure was re-written by SAS Institute, they carried along the measures I had programmed.  Measures such as classification accuracy, sensitivity, and specificity should never have been applied to logistic regression.  Logistic regression is all about estimating probabilities, and any measures you choose should be functions of estimated probabilities and observed outcomes, and should use no binning (categorization) of any kind.


ocfs2_dlmfs file system not found while running tunefs.ocf2s command

Question: While running the following tunefs command to enable the discontig-bg file system feature:
tunefs.ocfs2 --fs-features=discontig-bg /dev/drbd0

I receive the following error:
tunefs.ocfs2: ocfs2_dlmfs file system was not found while opening device "/dev/drbd0"

When running mount I don't see the ocfs2_dlmfs mount as expected, only the /dev/drbd0.

We did upgrade the kernel from 4.19.0-25-amd64 to 5.10, after which we encountered the error. Unfortunately downgrading to 4.19 did not resolve the issue. We're not even sure if the kernel version is related.

System information:
Operating system: Debian 10 (buster)
Kernel version: 4.19.0-25-amd64
TuneFS version: tunefs.ocfs2 1.8.5
Answer: Found a solution, first run
dpkg-reconfigure ocfs2-tools

Where you get the following option:

Would you like to start an OCFS2 cluster (O2CB) at boot time?

When you answer this with Yes, the dlmfs mount will persist and my original
tunefs.ocfs2 --fs-features=discontig-bg /dev/drbd0

command completes without any errors.


check the tomcat running or not?

Question:
Possible Duplicate:
Is Tomcat running?

hi,
i installed tomcat server in virtual machine. i want to check the tomcat server daily, it is running or not. if it is running or not it will send mail to my mail id. how i achieve?
can i do this one by using batch files
Thanks
Murali
Answer: You can cron the following script which checks the status of the tomcat pid present in the $CATALINA_PID file. If the pid is dead, an email is sent.
kill -0 `cat $CATALINA_PID` > /dev/null 2>&1
if [ $? -gt 0 ]
then
    echo "Check tomcat" | mailx -s "Tomcat not running" email@example.com
fi

Answer: There are multiple answers to this, depending on what you mean by "running".  For instance, @dogbane's answer tells you if a Tomcat process exists (modulo edge cases), and @Prabhakaran's answer tells you if Tomcat is listening on port 8080 (modulo different edge cases).  But neither of these will pick up cases where Tomcat has stopped responding to requests.
@Elite's answer tells you if the default (e.g. ROOT) servlet is running, but this is probably not enough.
I'd recommend the following approach:

Pick some webapp pages that you care about.  Ideally these should include pages that depend on back-end services / databases.
Create request URLs to fetch the pages, perform the queries, or whatever/
Use curl or wget to send the request URLs.
Use some kind of pattern matching to make sure that you are getting good results and not error pages.
If you get timeouts, unexpected response codes or error pages, crank out a mail message1.

This kind of thing is easier to do if you are running on a UNIX / Linux platform than on Windows because the tools you need to implement it should be either installed already, or easy to install using the package manager.

1 - Actually, that's a recipe for spamming yourself.  A better idea is to deploy an event monitoring system that understands system states, does duplicate suppression and so on.
Answer: If tomcat is running, the easiest way (platform independent) is to type this url to any web browser (assuming your http port is configured to "80"): http://localhost:8080/. You can change localhost to any host server of choice. This will open a Tomcat page with the following message:

If you're seeing this page via a web browser, it means you've setup Tomcat
  successfully. Congratulations!

Otherwise netstat and see if anything runs on port 8080.

PS I just read that you want to send email notification if not running, the best way is to create a job that periodically 1) listens to port 8080 or 2) find if a tomcat process is up and running. Failure to meet 1) or 2) sends an email to system administrator.
Answer: if your tomcat is in linux environment then you can use netstat command to check for the tomcat listening port 8080 and send mail using shell script

check the tomcat running or not?


How can I add a playlist to content type?

Question: I need to add a playlist of mp3 or waves to custom content type. I installed some modules, but nothing seems to work:

I installed audiofield that allows upload of files.
I installed some plugins, such as wordpress player, but it isn't accessible to screen readers (flash buttons are unlabeled).
I installed jPlayer, but there are many errors when I attempt to display content, such as undefined index.continuous, undefined index.entity etc.
I installed able player, an accessible able player, but tracks are not visible.
I try to install jw_player, but it doesn't install due an error index.description undefined.
I tried to set file field as an audio file, but track are not visible.
I tried to change theme, switched to bootstrap instead of bartik, but nothing change.

I don't know how to do. Is Drupal able to play audio files?
Comment: What exactly is your goal? What do you mean by playlist? What level of accessibility you want to achieve? Please extend your question.
Answer: The aptly named AudioField module has the functionality you're describing

Audio Field module adds new field that allows you to upload and play audio files in HTML5 audio player or one of selected Flash players. Currently it supports 6 different Flash players

It definitely works, I've used it, and it has support for both of the formats you mentioned. Follow the installation instructions and you shouldn't have any problems.
Just to nitpick, and perhaps clear up some confusion: Drupal cannot play audio files, no - your browser can, when it is given the right HTML (or when flash is used). But Drupal just generates the HTML, it doesn't have anything to do with the audio files themselves (beyond facilitating upload/storage) or how the browser interprets them.
Answer: You might also want to give the Media module a try. Make sure you download the latest 7.x-2.0-rc3 release. One of its features:

Makes files fieldable, enabling the use of text fields to store
  captions on images, taxonomy fields for audio file genres, etc.
Comment: Thanks to all, I solved. I installed html5 tools and able player. It's an audio/video player accessible to screen readers and with html5 tools works fine. Thanks again!


Drupal Commerce SKU generator

Question: I am building a Drupal Commerce site and I had the weirdest request:
Upon creating a new product, the client want's to select the product's category from a select list or something similar. This should result in the first part of the product's SKU, say
"CAT007"
Then he want's to select another attribute for that specific product which produces the second part of the SKU, say
048
So the complete SKU of the product would be CAT007.048 thus resulting in a unique identifier. The reason for this is that he doesn't want to look within huge arrays in order to produce the correct SKU.
My problem is that I can't seem to find a decent solution with which I can give the client access and management over the arrays.
Can anyone come up with something?
EDIT something that came to mind was taxonomy terms that contain a field with their SKU prefix/suffix. The problem that arises from that is how can I pass the tid from the user's selection (javascript) to the php side in order to do a term_load() and get the field's value.
Answer: By using taxonomy_vocabulary_machine_name_load() and taxonomy_get_tree() I was able to extract the 2 taxonomies I needed for creating the prefix and suffix of the SKU.
I created tables of key, value pairs that contained the tids and the SKU codes.
By using json_encode() I was able to pass those tables into an inline js script I attached to commerce's product form using $form['#attached']['js'].
Now by having a JavaScript array mapping tids to SKU parts, it's easy using jQuery to fill in the SKU textfield accordingly. :)

Drupal Commerce SKU generator


O conteúdo dos Enums estão chegando nulos ao banco de dados [Java + Spring boot + JPA + Hibernate + PostgreSQL]

Question: Estou com o seguinte problema: tenho 3 enums e nenhum deles está sendo salvo no banco após submeter o formulário (os outros campos sim). Já coloquei a anotação @Enumerated(EnumType.STRING) nos campos e ainda assim não resolveu.
Segue abaixo os trechos de código relevantes:
Enum:
public enum Turno
{
    MATUTINO("Matutino"),
    VESPERTINO("Vespertino"),
    NOTURNO("Noturno"),
    INTEGRAL("Integral");

    private final String descricao;

    Turno(String descricao)
    {
        this.descricao = descricao;
    }

    public String getDescricao()
    {
        return descricao;
    }
}

HTML:

        Turno:
        <select class="form-control" th:field="*{turno}">
            <option th:each="turno : ${T(br.com.academy.enums.Turno).values()}"
                    th:value="${turno}" th:text="${turno.descricao}">
            </option>
        </select>

Entidade:
@Entity
public class Aluno {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String nome;

    private String matricula;

    @Enumerated(EnumType.STRING)
    private Curso curso;

    @Enumerated(EnumType.STRING)
    private Turno turno;

    @Enumerated(EnumType.STRING)
    private Status status;

    /* Getters e Setters dos outros atributos omitidos*/

    public Turno getTurno()
    {
        return turno;
    }
}

PostMapping no Controller:
@PostMapping("cadastrarAluno") /* Anotação para enviar dados */
public ModelAndView cadastrarAluno(Aluno aluno)
{
    ModelAndView mv = new ModelAndView();
    mv.setViewName("redirect:/aluno/listAlunos");
    repositorio.save(aluno);
    return mv;
}

Alguém sabe me dizer onde está o erro?
Desde já agradeço!
Answer: Descobri o problema: havia confundido o fato dos atributos de um Enum não possuírem setters com o Enum em si como atributo de uma entidade possuir setter ou não e com isso percebi que havia apagado os setters do Enum na entidade Aluno. Desse jeito era óbvio que não ia settar no banco de jeito nenhum!kkkkkkk
Peço desculpas pelo problema idiota.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Mongoose: Unhandled promise rejection

Question: I know there are other posts with similar issues, but none of the suggestions I've tried have worked.
The following works if the _id is valid, but throws an unhandled promise rejection error if it isn't:
const Movie = mongoose.model(`Movie`, movieSchema);

router.get(`/api/movies/:id`, async (req, res) => {
    let movie = await Movie.findById(req.params.id);

    if(!movie) {
        res.status(404).send(`Movie with given ID not found.`);
        return;
    };
});

Per the docs, it looks like findById() is supposed to return null if the id can't be found, so I'm not sure what the issue is. Do I need to put a catch block somewhere and put the 404 in there? I've tried putting it everywhere I can think to.
Answer: As per the Mongoose documentation...

Model.findById()
Returns:

«Query»

Looking into the Query API, when used like a Promise, it will invoke the Query.prototype.then() implementation

Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error.

To use this, you would need something like
try {
  const movie = await Movie.findById(req.params.id)
  // do stuff with movie
} catch (err) {
  res.sendStatus(404)
}

Comment: I tried this too, same result. I should've mentioned this though, good shout.
Comment: Tried what? There are two code snippets in my answer
Comment: I tried using let movie = await Movie.findById(req.params.id).exec();
Comment: @William the docs for the return value of `exec()` aren't super clear (it just says `«Promise»`, not very helpful) but it seems perhaps that code comment mentioning `null` isn't accurate. I would go with the `try..catch` implementation
Answer: use .then() and .catch() will sort your issue.

Mongoose: Unhandled promise rejection


Ler determinadas colunas de arquivo xls em Python com XLRD

Question: sou principiante na linguagem e estou tentando exibir o conteúdo de uma planilha eletrônica no front end com Python. Com esse código estou exibindo o resultado das colunas nome, sobrenome, cidade e nota, constantes na planilha, e nessa ordem.
def exibir(request):
    workbook = xlrd.open_workbook("teste.xlsx", encoding_override="cp1252")
    worksheet = workbook.sheet_by_index(0)
    dados = []

    for row_num in range(worksheet.nrows):
        if row_num == 0:
            continue
        row = worksheet.row_values(row_num)
        usuario = Usuario(row[0], row[1], row[2], float(row[3]))
        dados.append(usuario)
    return render(request, 'lista.html', {'lista': dados})

Agora eu quero fazer com que eu receba o arquivo e exiba o resultado de 3 colunas específicas da planilha, selecionadas pelo nome da coluna (nome, cidade e email). Não posso selecionar pelo índice porque cada planilha pode variar a quantidade de colunas, já os nomes não variam. Alguém pode me ajudar?
Answer: Opa,
Acredito que você esteja procurando pelo método col_values. Veja a documentação.

col_values(colx, start_rowx=0, end_rowx=None)

Returns a slice of the values of the cells in the given column.
Para o seu caso, seria algo como:
workbook = xlrd.open_workbook("teste.xlsx", encoding_override="cp1252")
worksheet = workbook.sheet_by_index(0)
columnValues = sheet.col_values(columnIndex)  # columnIndex é o índice da coluna. Começando em 0 para a coluna A.

Caso você tenha uma linha de cabeçalho, pode fazer algo como:
columnValues = sheet.col_values(columnIndex, 1)

Espero que ajude.


How to make ReactiveCommand Async ?

Question: I am using ReactiveCommand to get Async behavior. According to Paul Betts comment in this discussion

If you're using RxUI 5.0, just use ReactiveCommand, they are now merged and have a better API.

I have the following code to test to see if it does the Async behavior. And it turns out to be not. It freezes up the UI for 5 seconds.
MyReactiveCommand.Subscribe(s =>
{
    Thread.Sleep(5000);
});

What am I missing?
Answer: Try:
MyReactiveCommand
.RegisterAsyncAction(_ =>
                         {
                           Thread.Sleep(5000);
                         });

And if you need to return a result:
MyReactiveCommand
.RegisterAsyncFunction(o =>
                          {
                            Thread.Sleep(5000);
                            return o.ToString();
                          })
.Subscribe(s => MessageBox.Show(string.Format("{0} was returned", s)));

Answer: I fixed it by using TaskPoolScheduler. Not sure if this is how it is meant to be.
MyReactiveCommand
.ObserveOn(RxApp.TaskPoolScheduler)
.Subscribe(s =>
{
    Thread.Sleep(5000);
});

Answer: I'm new to ReactiveUI, but I believe the async and not freezing the UI are different issues. Async can happen on 1 thread, ie it doesn't wait for some result, but can continue processing other things. I think if you make the thread sleep and you only have 1 thread, then it won't be able to do any other work.
Something like Task.Delay I believe will let you wait for some time without blocking the thread.
If you want to use multiple threads, you can use the thread pool as you provided in your answer, but to run the subscription implementation on a thread pool thread I believe it should be:
.SubscribeOn(RxApp.TaskPoolScheduler)

Then if you want to do something with the UI needing thread affinity, you need to move back onto the UI thread with:
.ObserveOn(RxApp.MainThreadScheduler)

ObserveOn is where your IObserverable methods OnNext/OnComplete/OnError context is and SubscribeOn is where the subscribe implementation context is.

How to make ReactiveCommand Async ?


How to make a grid In matlab with loop

Question: I want to make a grid (Uniform Mapping) in matlab without Meshgrid.
I have make grid with meshgrid but now I just want to make it with a loop or any Second Method (without meshgrid)
This is my code using meshgrid:
  figure(6)
  [X,Y] = meshgrid(-1:0.1:1, -1:0.1:1)
  plot(X,Y,'k-')
  hold on
  plot(Y,X,'k-');

Answer: use repmat, or multiply by ones vectors for even more basic functionality:
x = -1:0.1:1;
y = -1:0.1:1;
% with repmat
X1 = repmat(x(:)',[numel(y),1]);
Y1 = repmat(y(:),[1,numel(x)]);
% multiply with ones
X2 = ones(numel(y),1)*x(:)';
Y2 = y(:)*ones(1,numel(x));
% meshgrid
[X3,Y3] = meshgrid(x, y);
isequal(X1,X2,X3) && isequal(Y1,Y2,Y3) % true

plot(X1,Y1,'k');
hold on
plot(Y1,X1,'k');

Comment: depends what do you want to plot. if you want vertical lines do `plot(X1,Y1,'k-')`. do you plan to plot some surface with these grids?
Comment: No i dont , just i want to design the same previously grid with other method.. i use plot(X1,Y1,'k-') but the vertical lines doesnt show , the code :
      x = -1:0.1:1;
      y = -1:0.1:1;
      % with repmat
      X1 = repmat(x(:)',[numel(y),1]);
      Y1 = repmat(y(:),[1,numel(x)]);
      plot(X1,Y1,'k-')
Comment: The result is identical to what you are getting from meshgrid so it must be another issue in your code. Maybe you're plotting something afterwards without doing 'hold on'?

How to make a grid In matlab with loop


403.16 - Client certificate is untrusted or invalid - IIS 6 - Windows Server 2003

Question: i get the following error page if i try to open a https page on my server: "Client certificate is untrusted or invalid"
The Server was already working, i had to renew the certificate because it expired.
I checked all certificates twice (mmc) but don't see any outdated certificate.
I also try http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/bb089a80-c8ba-4004-9c0f-f10fb6b36416.mspx?mfr=true but without success.
Any other suggestions?
Thanks for your help!
Answer: This is usually caused by something incorrect in the cert chain.  I would check the FAQ for your cert authority and download and install all certs that they require.  A reboot is often needed when you change intermediate certs.
Also, if you view the properties of the cert, and the last tab, it will show the cert chain.  You can check with your cert authority to confirm that it's the correct chain.  Sometimes old root or intermediate certs can clash with some authorities' certs.
Answer: If you are getting a client certificate error, then you should look on the client side. Make sure your client has all the intermediate certificates in the chain present and is sending it to the server. If the server has no other network connectivity, ensure that the intermediates are also present on the server side, so it can build and validate the client certificate chain.
I would suggest using Wireshark or other network tracing tool to capture the traffic and look at what is going on. If the client authentication is done through renegotiation (aka second handshake encrypted using the existing session), then look at the size the messages to judge whether the entire client chain is being sent over or just part of it.


PostMessage and HWND_BROADCAST

Question: I'm trying to send message to all windows, by:
PostMessage( HWND_BROADCAST, 0x0401, 0, 0 );
or
SendMessage( HWND_BROADCAST, 0x0401, 0, 0 );

The problem is, that no window receives this message. Windows has own threads.
The question is... how to send message to all windows in my application, or why this function doesn't work...
Thanks in advance.
Comment: How have you determined that the windows are not receiving the messages?  Why are you sending 0x401, which is for private windows classes?  Messages in the WM_USER range should be sent only to specific windows that are of the class that recognizes that value.
Comment: Oh... I see... I change to WM_ACTIVATE and it works... Thanks... So, I know now why it throws error code 87...
Answer:
The question is, how to send message to all windows in my application, or why this function doesn't work.

Messages in the WM_USER range (and incidentally, you really should stop using magic constants like 0x0401) are reserved for private window classes. On the other hand HWND_BROADCAST results in the message being delivered to all top-level windows in the system.
These two facts conflict and PostMessage knows that. If PostMessage were to do your bidding then it would, for sure, deliver bogus messages to windows that would lead to undesirable behaviour. Hence PostMessage does not deliver your message to all the top-level windows.
Now, as mentioned, HWND_BROADCAST results in the message being delivered to all top-level windows in the system. You don't want that. You only want it to go to windows in your application. Which means that HWND_BROADCAST is not for you. If you want to deliver messages to specific windows in your application, you will have to maintain or obtain the list of windows, and deliver the messages one by one.
Answer: Are you trying to use this to go to all top windows? This API doesn't work for child windows. You should also make sure you use value returned by RegisterWindowMessage rather a hardcoded value. This link should help you go to child windows.
http://forums.codeguru.com/showthread.php?130766-How-to-Send-messages-to-ALL-child-windows
Comment: Also, UIPI may be blocking the messages
Comment: Could it be that your message is an illegal value? I would implement the EnumWindows/EnumProc idea just to be able to watch the process more closely
Comment: Try throwing in a GetLastError call. If you get an accessed denied. You've got a privilege problem. You may also want to try look at an EnumWindow setup to study the problem in a debugger
Comment: That's strange... it throws error no 87... ( the parameter is incorrect )

PostMessage and HWND_BROADCAST


Excel restart numbering after blank cell

Question: I have 3 columns of data. Column B holds some data about tasks, column C holds data about who's doing it.  In column B there will be a heading of the main task and underneath will be subtasks.
What i want to do in column A is look at C1 which is blank and in A1 0.  When i copy down, it A2 will look at C2, sees something is in there, looks at A1 and sees that 0 is in there and puts 1 in A2.
A3 will look at C3, see data there, look at A2 and see that it is greater than 0 and add 1 to whatever is in A2 and so on.
I've tried for ages using different combinations of formula but i can't get it right.
Anyone did this before and how?!
Answer: The key is to start the formula at A2 rather than A1.  In A1, enter 0. In A2, enter the following formula and fill down.
=IF(C2="",0,A1+1)

EDIT:
Based on your screen capture, this will give you exactly what you have there.
Leave A1 blank.  Then in A2 enter the following and fill down.
=IF(C2="","",IF(A1="",1,A1+1))

Comment: Many thanks.  So simple and I thought it was harder than that
Answer: =IF(C2=" ",0,C1+1) in A2 and drag down for your table. After that, copy and past values and in the and find and replace zero with blank.


Falha no acesso do SPServices em uma lista do SharePoint

Question: Criei um SPServices que consulta uma lista no SharePoint 2010 e retorna o valor de um único campo. Porém, esta consulta esta retornando o seguinte erro:
soap:ServerException of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.Não existe nenhuma Web chamada "/blog/Lists/Postagens/_vti_bin/Lists.asmx".

Meu código é o seguinte:
var queryText = "<Query>"+
                    "<Where>"+
                        "<Eq>"+
                            "<FieldRef Name='ID'/>"+
                                "<Value Type='Number'>" + IDPost + "</Value>"+
                        "</Eq>"+
                    "</Where>"+
                "</Query>";

 $().SPServices({
    operation: 'GetListItems',
    async: false,
    listName: 'Postagens',
    webURL: 'http://site/subsite/Lists/Postagens/',
    CAMLViewFields: '<ViewFields>'+
                        '<FieldRef Name="Curtir" />'+
                    '</ViewFields>',
    CAMLQuery : queryText,
    completefunc: function (xData, Status) {
        $(xData.responseXML).SPFilterNode('z:row').each(function() {
            CurtirTot = $(this).attr('ows_Curtir');
        });
    }
});

Procurei no google, mas o resultado mais próximo que cheguei foi "Falha na conectividade"
Alguém sabe me dizer se eu preciso configurar algo mais no SharePoint para funcionar corretamente o SPServices ou existe algum erro no código ?
Answer: A opção webURL deve indicar o caminho de um site. No seu código que ele indica o caminho de uma lista.
Modifique o valor da opção para conter o caminho apenas até o site, isto é, supondo que o site se chame "subsite" e esteja no caminho do domínio "site", ficaria assim:
...
    webURL: `'http://site/subsite/'`,
...

Comment: Sobre esse parâmetro, ele deve ser utilizado somente quando você for fazer requisições de um site a outro. Se você está no próprio site *blog*, então ele é realmente dispensável.
Comment: Tentei tirar o parâmetro "WebURL" e funcionou. Obrigada


Symbol for null proposition in mathematical logic

Question: Is there a symbol in mathematical logic expressing a null statement?
That is an equivalent expression to:
$$p\land\lnot p$$
Comment: I've seen $\bot$, as opposed to $\top$ for tautology.
Check this [list](https://en.wikipedia.org/wiki/List_of_logic_symbols)
Comment: $\bot$, $F$ or $0$, depending on how you do represent truth/tautology ($\top$, $V$ or $1$.)
Comment: @Archimedesprinciple I've heard it called "absurdity" and "contradiction;" I slightly prefer the former.
Comment: So is this called a universal fallacy?
Comment: See [False (or : *falsum*)](https://en.wikipedia.org/wiki/False_(logic)).
Answer: There are several. The ones I've seen most often are $\bot$ and $0.$ Ultimately, they all represent contradiction. The kicker is that the Principle of Explosion shows that a contradiction implies (or, from a Boolean algebra standpoint, is "less than or equal to") all other statements.


RxJs Operator simplification : switchMap, combineLatest

Question: I have the following RxJS subscription :
combineLatest([obs1$, obs2$])
  .pipe(
     filter(val=>!!val[0] && !!val[1]), // no null value on both
     switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$(v2)]))
   )
   .subscribe(([val1, val3]) => { ... });

The code works like intended but it feels cumbersome. I am quite sure the switchMap into combineLatest with an of() opertor is improvable.
Note : In order to call the getObs3$(v2) I need to be sure that the value in obs1$ first. Also, i do need the val1 in the subscription since i will use it later on.
Any one got an idea on how to optimize this one ?
Answer: One possibility:
combineLatest([obs1$, obs2$]).pipe(

  // no null value on both
  filter(val=>!!val[0] && !!val[1]),

  switchMap(([val1, val2]) => getObs3$(val2).pipe(
    map(val3 => [val1,val3])
  ))

).subscribe(([val1, val3]) => { ... });

This is the general pattern you'll see quite often for this. Here we insert val3 into a tuple, so it's not much different from combine latest, but if it was enriching an object (however deeply nested) the same pattern would apply.


How to retrieve all taxonomy term using json api

Question: I want to retrieve all  taxonomy term name using json api.
I have tried:
http://local-tes/jsonapi/taxonomy_term/specialties

but its only return 50 values, I want to fetch  all taxonomy terms values.
Comment: I believe this is capped so the application doesn't crash from loading hundreds+ of potential entities. You'll need to loop and paginate over it or use a contrib module that increases the number returned.
Answer: See https://www.drupal.org/docs/core-modules-and-themes/core-modules/jsonapi-module/pagination#s--cant-i-set-a-page-limit-higher-than-50:

Why can't I set a page limit higher than 50?
First, read the example given above. Understand that JSON:API must run
individual access checks for every entity in a response. Second,
understand that the JSON:API module aims to be "zero configuration."
You shouldn't have to install, alter or configure anything to use the
module.
The reason for this is to protect your application from a DDoS attack.
If a malicious API client set a page limit of 200,000 resources, the
JSON:API module would need to run entity access checks for every one
of those entities. This would quickly lead to out-of-memory errors and
slow responses. The server needs to set a maximum. The limit of 50 was
somewhat arbitrarily chosen as a nice round number.
Please understand that there have been many long conversations around
this decision and a compromise had to be made between support burden,
sane defaults, and frontend performance. While the JSON:API module
maintainers do understand that this may not be ideal for every use
case, they're confident that if your client follows the
recommendations in these docs, it should have little to no impact on
you :)

There is the JSON:API Page Limit module and also JSON API Defaults (part of the popular JSON:API Extras module) to change the limit.
After you have installed the JSON API Defaults module go to
http://example.com/admin/config/services/jsonapi/add/resource_types/taxonomy_term/[vocabulary]
and change the page limit at the bottom of the config form.
Then you can request a higher number of items with the query parameter page[limit]:
http://example.com/jsonapi/taxonomy_term/[vocabulary]?page[limit]=1000


Additivity of quadratic variation

Question: Let $t<u$. $[X,Y]_t$ and $[X,Y]_u$ are the quadratic cross variations of the processes $X$ and $Y$ at times $t$ and $u$. By that I mean
$$\lim_{\text{mesh}(\pi(t))\rightarrow 0}\sum_{i=0}^{n-1} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}}) \rightarrow [X,Y]_\tau \quad \text{in probability}$$
where $\pi(t) = \{s_i\}$ and $0 = s_0 < s_1 < \ldots < s_n = \tau$. $\text{mesh}(\pi(t))$ is the length of the largest of the intervals $(s_i,s_{i+1})$.
The question is to show that
$$\lim_{\text{mesh}(\pi(t))\rightarrow 0}\sum_{i=0}^{n-1} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}}) \rightarrow [X,Y]_u - [X,Y]_t\quad \text{in probability}$$
where $t = s_0 < s_1 < \ldots < s_n = u$.
My attempt is as follows. Since $[X,Y]_t$ and $[X,Y]_u$ both converge to the first sum above for $\tau = t$ and $\tau = u$ in probability, respectively, their difference converges to the difference of these sums in probability. (Here I used a result that I had seen in a book on SDE's). For $[X,Y]_u$ it is very tempting to choose a mesh such that $0 = s_0 < s_1 < \ldots < s_n = u$ where $s_m = t$ for some $m \leq n$. However I haven't been able to justify why this would be a valid move.
Answer: Your argumentation is absolutely correct, but since you are still not convinced, let's have a closer look. For simplicity of notation, I'll denote by $\Pi[a,b]$ a partition of the form $\{a=s_0<\ldots < s_n=b\}$ for any $a \leq b$.
By assumption,
$$\lim_{\text{mesh}(\Pi[0,t])\rightarrow 0}\sum_{s_i \in \Pi[0,t]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}}) \to [X,Y]_t \qquad \text{in probability.}$$
This means that for any $\epsilon>0$, $r>0$ we can find $\delta=\delta(t)>0$ such that
$$\mathbb{P} \left( \left| \sum_{s_i \in \Pi[0,t]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}})- [X,Y]_t \right| >r \right) < \epsilon$$
for any partition $\Pi[0,t]$ with $\text{mesh}(\Pi[0,t]) < \delta$.
Now let $\Pi[t,u]$ be an arbitrary partition of the interval $[u,t]$ such that $\text{mesh}(\Pi[t,u]) < \delta:= \min\{\delta(t),\delta(u)\}$. Denote by $\Sigma[0,t]$ an equidistant partition of $[0,t]$, i.e. $$s_k := \frac{k}{n} t, \qquad k=0,\ldots,n$$ where $n \in \mathbb{N}$ is chosen sufficiently large such that $\frac{1}{n} < \delta$. Then
$$\mathbb{P} \left( \left| \sum_{s_i \in \Sigma[0,t]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}})- [X,Y]_t \right| >r \right) < \epsilon \tag{1}$$
and
$$\mathbb{P} \left( \left| \sum_{s_i \in \Sigma[0,t]+\Pi[t,u]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}})- [X,Y]_u \right| >r \right) < \epsilon. \tag{2}$$
($\Sigma[0,t]+\Pi[t,u]$ denotes the partition obtained by "glueing" both partitions together. Note that $\text{mesh}(\Sigma[0,t]+\Pi[t,u])<\delta$.)  Now it follows from the triangle inequality that
$$\begin{align*}&\mathbb{P} \left( \left| \sum_{s_i \in \Pi[t,u]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}})- ([X,Y]_u-[X,Y]_t) \right| >2r \right) \\ &\leq \mathbb{P} \left( \left| \sum_{s_i \in \Sigma[0,t]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}})- [X,Y]_t \right| >r \right) \\ &\quad + \mathbb{P} \left( \left| \sum_{s_i \in \Sigma[0,t]+\Pi[t,u]} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}})- [X,Y]_u \right| >r \right)\\ &< 2\epsilon \end{align*}$$
Since this holds for any partion $\Pi[t,u]$ with mesh size $<\delta$ and $r, \epsilon$ are arbitrary, this shows that
$$\lim_{\text{mesh}(\Pi[t,u])\rightarrow 0}\sum_{i=0}^{n-1} (X_{s_{i+1}}-X_{s_{i}})(Y_{s_{i+1}}-Y_{s_{i}}) \rightarrow [X,Y]_u - [X,Y]_t\quad \text{in probability}.$$
Comment: Thanks a lot. I really appreciate it.

Additivity of quadratic variation


Is changing your data from long form into wide form by summing it a valid statistical analysis step?

Question: If for example i have a data set of multiple stores that looks something like this:
+---------+-----------+-------+----------+
| StoreID | Customers | Sales | Date     |
+---------+-----------+-------+----------+
| 1       | 2         | 100   | 1/1/2018 |
| 1       | 5         | 200   | 2/1/2018 |
| 2       | 1         | 50    | 1/1/2018 |
| 2       | 10        | 300   | 2/1/2018 |
+---------+-----------+-------+----------+
Would it make sense to group up everything by storeID so as to have one row per storeID in order to perform statistical analysis on the data set?
Making it look something like this:
+---------+-----------+-------+-------------------+
| StoreID | Customers | Sales | Date              |
+---------+-----------+-------+-------------------+
| 1       | 7         | 300   | 1/1/2018-2/1/2018 |
| 2       | 11        | 350   | 1/1/2018-2/1/2018 |
+---------+-----------+-------+-------------------+
Comment: No reason why you should not do that but it is not what people usually mean by transforming from long to wide format.
Answer: First, as @mcdewey pointed out, this is not usually what people mean by "long to wide"; that usually refers to creating a data set with a lot more variables and fewer observations.
Second, adding up the data in the way you suggest doeesn't violate any statistical rules, but it loses a lot of information and changes the nature of the questions you can ask about the data.  You would now be able only to ask about totals.  Whether that is a good idea depends on what you are trying to find out.
Comment: (+1) It's just a case of what defines an observation (case, record, item, whatever) for the researcher's purpose. In the question the data arrive as daily observations for each store and they're combined as totals for each store. **_Aggregation_** is one of many words that might be used. Changes between long and wide format (structure, layout) generally are rearrangements of the data, not reductions.
Comment: Thank you for all of your responses. I am really new to statistics and just wanted to ensure that Aggregating up the data would still allow me to perform hypothesis statistics. I found that aggregating values up to keep "participants" to a per row level, easier to understand based on the examples i have found.  Your answers are very appreciated and have helped me a lot.


Two ways to show that $\sin x -x +\frac {x^3}{3!}-\frac {x^5}{5!}< 0$

Question: Show that: $\large \sin x -x +\frac {x^3}{3!}-\frac {x^5}{5!}< 0$ on: $0<x<\frac {\pi}2$
I tried to solve it in two ways and got a little stuck:
One way is to use Cauchy's MVT, define $f,g$ such that $f(x)=\sin x -x +\frac {x^3}{3!}$ and $g(x)=\frac {x^5}{5!}$ so $\frac {f(x)}{g(x)}<1$ and both are continuous and differentiable on  $x\in (0,\frac{\pi}2)$ so
$$\large \frac {f(x)}{g(x)}=\frac{f(x)-f(0)}{g(x)-g(0)}=\frac {f'(c)}{g'(c)}\Rightarrow
\frac{\sin x -x +\frac {x^3}{3!}} {\frac {x^5}{5!}}=\frac {\cos y -1 +\frac{y^2}{2}}{\frac{y^4}{24}}$$
Such that $y\in (0,x)$.
Now what ? I need to show that $\frac {f'(y)}{g'(y)}<1$ but I tried to input $\frac{\pi} 2$ as a value to $f'/g'$ but it was larger than 1.

The other way: With Taylor expansion.
$\large \sin x=x-\frac {x^3}{3!}+\frac {x^5}{5!}+R_{5,0}(x)\Rightarrow\\
\large \sin x-x+\frac {x^3}{3!}-\frac {x^5}{5!}=R_{5,0}(x)$
Now we're left with showing that $R_{5,0}(x)<0$
So $\large R_{5,0}(x)=\frac{-\sin(c)c^7}{7!}$ for $c\in (0,x)$, now can I say that because it's negative and $(\sin(c)c^7>0)$ for all $c\in(0,x)$,  $R_{5,0}(x)<0$ ?
Also, would it be correct to say that: $\large R_{5,0}(x)=\frac{cos(c)c^6}{6!}$?
Comment: As for the Taylor expansion, since $\sin x$ and $x$ are both greater than $0$ for $x\in(0,\pi/2)$, $R_{5,0}<0$.
Comment: @SanathDevalapurkar would it be correct to say that: $\large R_{5,0}(x)=\frac{cos(c)c^6}{6!}$ ? This would make it a bit complicated because it isn't negative.
Comment: Why would you want $R_{5,0}(x)=\dfrac{\cos(c)c^6}{6!}$? The $-\dfrac{\sin (c)c^7}{7!}$ is simpler to work with.
Comment: Yeah I know, just to know how to tackle all the possibilities.
Answer: Use increasing functions.
For example
$$ 1- \frac{x^2}{2} <\cos x$$
take
$$f(x)=\cos x +\frac{x^2}{2}-1$$ then
$$f^{\prime}=-\sin x + x  >0$$ so $f$ is increasing, and $f(0) <f(x)$ gives the desired inequality. Next take $x-\frac{x^3}{3} < \sin x$ then go back to the corresponding $cos$ expansion and finally your ready to prove your inequality. Each step relies on the last.
Comment: Don't you need to prove that: $\sin x<x :\forall x$ ?
Comment: @GinKin. How about proving it from $\cos x <1$.
Comment: Yeah that could work: $-\frac {x^2}{2}<0$
Comment: $\sin x <x $ follows by the same method $f=\sin (x) -x$, $f^{\prime}=\cos x -1 <0$ so $f$ is decreasing, $f(x) < f(0)=0$.
Comment: BTW, should something be stated about the $y\in (0,x)$ ? Every time we apply Cauchy's MVT the interval get's shorter.
Answer: Repeat use of the Cauchy Mean Value theorem $3$ times we have to prove:
$\dfrac{sinx}{6x} < 1$. But since $x > 0$, we need to prove: $h(x) = sinx - 6x < 0$.
$h'(x) = cosx - 6 < 0$, so $h(x) < h(0) = 0$. Done.
Comment: I hoped to avoid repeating it more than once but I see now that it's pretty fool proof.
Answer: Using the Mean value theorem is the right idea. You need the MVT to prove the following useful lemma:

If $f'(x)>g'(x)$ for all $a\ge x>0$ and $f(0)=g(0)$, then $f(x)>g(x)$ for all $a\ge x>0$.

Letting $g(x)=\sin(x)$ and $f(x)=x-\frac{x^3}{3!} +\frac{x^5}{5!}$ and then iterating this lemma will give you your answer.
Proof of the lemma:

Suppose we are given $f$ and $g$ such that $f'(x)>g'(x)$ for all $a\ge x>0$ and $f(0)=g(0)$. Let $h(x)=f(x)-g(x)$, then $h(0)=0$ and $h'(x)>0$. By MVT there is an $x_0\in [0,x]$, for any $0<x\le a$, such that
  $$h'(x_0)=\frac{f(x)-g(x)-(f(0)-g(0))}{x}=\frac{f(x)-g(x)}{x}>0.$$
  Since $x>0$, we know $f(x)-g(x)>0$ for any $x\in [0,a]$.
Answer: Observe first that $f_0(x):=1-\cos x>0$ for $0<x\leqslant\pi/2$. Then
$$f_1(x):=\int_0^xf_0(t)\,\mathrm dt=x-\sin x>0$$
for $0<x\leqslant\pi/2$. Continue in this way, with
$$f_{n+1}(x):=\int_0^xf_n(t)\,\mathrm dt>0$$
for $0<x\leqslant\pi/2$ and $n=0,1,...$, and we arrive at your result at the stage $n=4$.
It is easy to generalize this procedure to show by induction that
$$(-1)^n\left(\sum_{k=0}^n(-1)^k\frac{x^{2k}}{(2k)!}-\cos x\right)>0$$
and
$$(-1)^n\left(\sum_{k=0}^n(-1)^k\frac{x^{2k+1}}{(2k+1)!}-\sin x\right)>0$$
for $0<x\leqslant\pi/2$ and $n=0,1,...$.


How can I render an URL path from a custom route?

Question: In my module.routing.yml (and using D8), I have a module_new route associated with the /module/name path.
I want to render this path in my module. How can I show http://example.org/module/name on a page?
Answer: Twig
You can use the route name in the twig function url():
{{ 'View my module content'|t }}

Controller
Or you can do the same in a controller:
use Drupal\Core\Url;

  $url = Url::fromRoute('module_new', [], ['absolute' => TRUE]);

  // get the path as string (not recommended)
  $path = $url->toString;

  // better put the complete url object in a render array and let the template render it
  $build['link'] = [
   '#title' => $this->t('My module content'),
   '#type' => 'link',
   '#url' => $url,
  ];

  return $build;

Comment: :D , I change it to string with ->toString() but not show http :// mysite in string . How can I do this ?
Comment: How can I use this in my controller handler ?
Comment: I use Url::fromRoute('module_new')  but it's not string and not work .
Comment: Not work and not show http:// example .org in my link . I don't want to use $link . I want create http:// example .org/module/name to use in other variables .
Comment: it's better to use the url as object in a render element to build the link, but you can get the path as string, see the edit
Comment: Thanks @4k4 but I want just show text of url not link .
Comment: you can set the option `absolute`, then you get the full path, see edit


How to store DataTable in Apache Ignite?

Question: Based on our current code implementation, we need to store System.Data.DataTable in cache. It works fine when using HttpRuntime.Cache, but not in Apache Ignite.
The following is the code snippet.
IIgnite ignite = Ignition.Start();
ICache<string, object> cache = ignite.GetOrCreateCache<string, object>("cache");
DataTable table = new DataTable();
cache.Put("1", table);

It will throw "Unable to cast object of type 'Apache.Ignite.Core.Impl.Binary.BinaryWriter' to type 'System.IConvertible'" error.
Based on the info at https://apacheignite-net.readme.io/docs/serialization,
DataTable implements ISerializable and has Serializable attribute. It should be able to serialize. I am not sure why I got this error. Any thoughts?
Environment: Ignite.NET 2.1, Visual Studio 2015
Answer: I've reproduced the issue, and I would say that this is a bug in System.Data.DataTable. Here is the code:
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
    SerializationFormat remotingFormat = RemotingFormat;
    bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true;
    SerializeDataTable(info, context, isSingleTable, remotingFormat);
}

Exception comes from
Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture)

The assumption that Context can be converted to bool does not look correct, see MSDN:

additional: Any additional information to be associated with the
  StreamingContext.

Ignite uses this to store BinaryWriter object for internal purposes.
Anyway, .NET framework is not going to be fixed, so I've filed an Ignite.NET bug: https://issues.apache.org/jira/browse/IGNITE-5927


Dúvida com nível de acesso e login em PHP

Question: Bom tenho uma dúvida e queria a opinião de pessoas mais experientes.
Tenho um sistema em PHP que usa Mysql. Tenho uma tabela chamada 'acesso' onde salvo as opções que o usuário tem para acessar o sistema. O problema e que toda vez que carrego a página tenho que fazer o 'select' no BD.
Quero melhorar a performance do sistema, e tenho tomado várias medidas para isso. E uma delas é tentar diminuir os 'select'.
Bom vamos a dúvida, o que eu quero saber é:
1- Essa e a melhor forma de fazer isso?
2- Seria mais fácil salvar as permissões do usuário na sessão, para evitar o select?
3- A leitura da sessão e mais rápida do que o select no BD?
Bom, aguardo a ajuda para uma boa solução.
Comment: Desculpa a demora, mas já vi que o @ItaloRodrigo fez uma boa resposta! +1 para você e para a resposta.
Comment: Quais são as informações que vc busca no seleção? E com que frequência elas são alteradas?
Comment: Bom elas raramente são alteradas, pois elas são salvas quando o usuário e cadastrado. Bom ela e uma tabela que se chama 'acesso', e conta uns 40 campos. Exemplo: o campos 'editar_produto' nele eu salvo 's' ou 'n'. Com isso eu sei se o usuário pode editar os produtos.
Answer: 1- Essa e a melhor forma de fazer isso?
Não, pois cada vez que você acessa o banco de dados, perde tempo.
2- Seria mais fácil salvar as permissões do usuário na sessão, para evitar o select?
Sim, essa é a melhor solução na minha opinião (pode ser que existam outras), pois assim você não vai ter que consultar o banco cada vez que abre a página.
3- A leitura da sessão e mais rápida do que o select no BD?
Sim
Comment: eu uso certificado ssl, e possível que alguém altere os dados da sessão ou tenha acesso a eles?


Deleting a Database

Question: Basically, I just want to obliterate my entire database and create a new one. How do I actually do that, in explicit steps?
Comment: `drop database ;create database ;`? what's with the username lol
Comment: where do i type that? (im working in android studio)
Comment: @Chris: There is no `drop database` command in SQLite.
Answer: As a user, you can:

Uninstall the app, the way you would uninstall any other app (e.g., Settings > Apps > (the app's page) > Uninstall).
Clear the data of the app (e.g., Settings > Apps > (the app's page) > Clear data or  Settings > Apps > (the app's page) > Storage > Clear data)

As a developer, manually, you can:

Uninstall the app, using adb uninstall your.package.name.here, where adb is located in the platform-tools/ directory of your Android SDK, and where your.package.name.here is your applicationId (if you specified that in build.gradle) or your package value on the <manifest> element in your AndroidManifest.xml file
Clear the data of the app, using adb shell pm clear your.package.name.here (see previous bullet for details of adb and your.package.name.here)

As a developer, programmatically, you can call deleteDatabase() on any Context (e.g., an Activity), passing in the name of your database.
Comment: where do I know the name of my database? all i know is the name of the tables i want to add
Comment: @stackoverflow_sucks: "where do I know the name of my database?" -- you chose it when you created it, via `SQLiteOpenHelper`, `createDatabase()`, etc.
Comment: i wound up finding it. i just changed the name of the database, and thereby effectively created a new one. the ghost of the old one may still haunt me, but it's just a ghost now. thanks for your help

Deleting a Database


congruence issue

Question: I need to understand why this :
$$(1+4+\ldots+4^{n−1})\equiv n \pmod3$$
Is that because
\begin{align}
1&\equiv -2 \pmod3\\
4&\equiv 1 \pmod3\\
4^{2}&\equiv1 \pmod3\\
\ldots&\equiv\ldots\\
4^{n-1}&\equiv1 \pmod3
\end{align}
Am I right? Would you please explain to me more?
Comment: Modulo 3, each summand is $1$.  There are $n$ of them.
Comment: See $\#10$ of http://mathworld.wolfram.com/Congruence.html
Answer: $$1 \equiv 1 \pmod 3$$
$$4 \equiv 1 \pmod 3$$
$$4^2 \equiv 1 \pmod 3$$
$$\dots$$
$$4^{n-1} \equiv 1 \pmod 3$$
$$1+4+ \dots +4^{n-1} \equiv 1+1+ \dots +1 \equiv n \pmod 3$$
Answer: Rewrite $4^n$ as $(3+1)^n$. Then, using the binomial expansion,http://en.wikipedia.org/wiki/Binomial_theorem  we get $$3^n+(nC1)3^{n-1} +(nC2)3^{n-2}+...+(nCk)3^{n-k}...(nC(n-1))3 +1^n $$ , where $nCk$ means $\frac {n!}{k!(n-k)!}$ . Notice every term except the last one is divisible by 3 , so that the sum itself --meaning $3^n$ itself , is $1mod3$.
Comment: Once you've convinced yourself of that (or otherwise) you may then use $a^k \equiv (a \bmod n)^k \pmod{n}$ without further proof :)

congruence issue


indexing jsonb fields with sunspot

Question: How can I index field that I needed in jsonb fields with sunspot?
I have the model Man:
 #<Man id: 1, name: "John Doe", type: "Man", r_id: "5734", fields: {"message"=>"hello world!", "sex"=>2, "uid"=>5734, "domain"=>"www.old-man.com"}, created_at: "2018-07-12 12:44:07", updated_at: "2018-07-12 12:44:07">

So, I'm trying to indicate searchable fields like this:
  searchable do
      text :fields, stored: true
    end

and it will index all fields.
But how to indicate only field "message" in fields as a searchable field?
Answer: From gem documentation:
searchable do
  text :title, :body
  text :comments do
    comments.map { |comment| comment.body }
  end
  ...
end

That doesn't work for you?
searchable do
  text :fields do
    fields["message"]
  end
end

Comment: fields.select { |k, _v|  fields[k] if searchable_fields_arr.include? k } helps %)

indexing jsonb fields with sunspot


Animating canvas to look like tv noise

Question: I have a function named generateNoise() which creates a canvas element and paints random RGBA values to it; which, gives the appearance of noise.

My Question
What would be the best way to infinitely animate the noise to give the appearance of movement. So that it may have more life?

JSFiddle
function generateNoise(opacity) {
    if(!!!document.createElement('canvas').getContext) {
        return false;
    }
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        x,y,
        r,g,b,
        opacity = opacity || .2;

        canvas.width = 55;
        canvas.height = 55;

        for (x = 0; x < canvas.width; x++){
            for (y = 0; y < canvas.height; y++){
                r = Math.floor(Math.random() * 255);
                g = Math.floor(Math.random() * 255);
                b = Math.floor(Math.random() * 255);

                ctx.fillStyle = 'rgba(' + r + ',' + b + ',' + g + ',' + opacity + ')';
                ctx.fillRect(x,y,1,1);

            }
        }
        document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";

}
generateNoise(.8);

Comment: `window.setInterval('generateNoise(.8)',50);`
Comment: You can reduce your `Math.random` and `Math.floor` calls by doing something like
`x = Math.floor(Math.random() * 0xffffff);
r = x & 0xff;
g = (x & 0xff00) >>> 8;
b = (x & 0xff0000) >>> 16;`
Comment: also all i had to add was `requestAnimationFrame(generateNoise);` and it does what you need place it in the first line in the function.
http://jsfiddle.net/eS9cc/
Comment: Some tips:
1) `!!!document.createElement('canvas').getContext` to `!document.createElement('canvas').getContext`
2) set up if/else so that users who don't have canvas won't get errors
3) put spaces between commas and text after, and space between `(param) {` for functions
Comment: @PaulS. do I make that work? i'm totally a nerb?  it looks correct but I cant get it to work; new colors: r = Math.floor(Math.random() * 155);
    g = Math.floor(Math.random() * 255);
    b = Math.floor(Math.random() * 155);
Comment: Also avoid repainting a canvas very often, it is resource-intensive. If you can use the [improved for loop](http://stackoverflow.com/questions/17484227/javascript-improved-native-for-loop) that will help. Set up a canvas that is only 10px, and scatter that, then you will save a lot of painting. Check Chrome Developer Tools or Firebug for performance stuff. Something that could make it look alive is using a css animation to really quickly move it would be good. Check out my [pen](http://codepen.io/ilanbiala/pen/CgGIw) and see what I mean. You can play around with the values and timing.
Comment: @IlanBiala would you do the math.random() fixes that Paul S. said and put an offical answer?
Comment: @llan Biala, that is an intersting way todo it, however it looks a little wierd not like actual noise.
Comment: @Mouseroot would you know why when I do it yoru way opacity doesnt work?
Comment: it could be that your iterating over the x,y pixel positions while im itering over each pixel and adding 4 for r,g,b and alpha and im using 255 (black) for the r,g,b and a random value between 155 and 254, also im directly altering the pixels while your placing each individual pixel.

so my loop alters all the pixels in the array and then applying it, while your is altering each pixel and setting it.
Comment: @Mouseroot Nice. RAF is awesome, but you could probably achieve the same thing with css animation on the body background position. I think RAF is also not fully supported yet as per http://caniuse.com/#feat=requestanimationframe
Comment: @MatthewHarwood you want a demo of mine or something else?
Comment: its not fully supported in all browsers but there exists a polyfill for browsers that still rely on vender prefixes and that fallback on setInterval for browsers that just flat out dont support rAF.
Answer: Update 1/2017: I rewrote the entire answer as it started to become rather messy, and to address some of the issues pointed out in the comments. The original answer can be found here. The new answer has in essence the same code but improved, and with a couple of new techniques, one utilizes a new feature available since this answer was first posted.

For a "true" random look we would need to use pixel-level rendering. We can optimize this using 32-bit unsigned buffers instead of 8-bit, and we can also turn off the alpha-channel in more recent browsers which speeds up the entire process (for older browsers we can simply set a black opaque background for the canvas element).
We create a reusable ImageData object once outside the main loop so the main cost is only putImageData() and not both inside the loop.

var ctx = c.getContext("2d", {alpha: false});       // context without alpha channel.
var idata = ctx.createImageData(c.width, c.height); // create image data
var buffer32 = new Uint32Array(idata.data.buffer);  // get 32-bit view

(function loop() {
  noise(ctx);
  requestAnimationFrame(loop)
})()

function noise(ctx) {
  var len = buffer32.length - 1;
  while(len--) buffer32[len] = Math.random() < 0.5 ? 0 : -1>>0;
  ctx.putImageData(idata, 0, 0);
}
/* for browsers wo/2d alpha disable support */
#c {background:#000}
<canvas id=c width=640 height=320></canvas>

A very efficient way, at the cost of some memory but reduced cost on the CPU, is to pre-render a larger off-screen canvas with the noise once, then place that canvas into the main one using random integer offsets.
It require a few extra preparation steps but the loop can run entirely on the GPU.

var w = c.width;
var h = c.height;
var ocanvas = document.createElement("canvas");     // create off-screen canvas
ocanvas.width = w<<1;                               // set offscreen canvas x2 size
ocanvas.height = h<<1;

var octx = ocanvas.getContext("2d", {alpha: false});
var idata = octx.createImageData(ocanvas.width, ocanvas.height);
var buffer32 = new Uint32Array(idata.data.buffer);  // get 32-bit view

// render noise once, to the offscreen-canvas
noise(octx);

// main loop draw the offscreen canvas to random offsets
var ctx = c.getContext("2d", {alpha: false});
(function loop() {
  var x = (w * Math.random())|0;                    // force integer values for position
  var y = (h * Math.random())|0;

  ctx.drawImage(ocanvas, -x, -y);                   // draw static noise (pun intended)
  requestAnimationFrame(loop)
})()

function noise(ctx) {
  var len = buffer32.length - 1;
  while(len--) buffer32[len] = Math.random() < 0.5 ? 0 : -1>>0;
  ctx.putImageData(idata, 0, 0);
}
/* for browsers wo/2d alpha disable support */
#c {background:#000}
<canvas id=c width=640 height=320></canvas>

Do note though that with the latter technique you may risk getting "freezes" where the new random offset is similar to the previous one. To work around this problem, set criteria for the random position to disallow too close positions in a row.
Comment: I don't get the point... You are talking about *performance optimization* but create the `idata` and `buffer32` on each iteration step. There's no benchmark required to see that this is much slower, than caching/creating them just before the loop (on resize). The buffer length could be also calculated by `w*h` ;)
Comment: yckart's right. In Firefox (48.0.1), the noise animation hangs every second or so (garbage colletion?). [Runs fine](http://jsfiddle.net/vX7NK/347/) once all the variables are outside of noise(). That is, it still uses > 10% CPU (i5-6500 CPU @ 3.20GHz) for 1680x954.
Comment: it should be noted that you could use a `Uint8ClampedArray` so you can do `pixels[i+4] *= alpha;` without having to worry about manual clamping as shown in this html5rocks post http://www.html5rocks.com/en/tutorials/webgl/typed_arrays/
Comment: `requestAnimationFrame` is amazing and I always forget about it. This seems to fill the whole page rather than setting a background (but that wasn't enough to prevent me `+1`ing).
Comment: @Mouseroot yes, but with a 8-bit array you need to iterate 4x as many pixels. So the question becomes is the browser clamping or the 4x iteration speed more efficient.. :)
Comment: @PaulS. yes, rAF is pretty neat! :) You could BTW toggle the frame rate to 30 fps (the old TVs had 50/60 hz interlaced or 25/30 FPS depending on PAL/NTSC). That would also save some resources.
Comment: @Ken doing `i = i + 4` would give you exactly the same number of iterations and you don't need to `new`. Doing it your with the 32 bit array way might have been more efficient for my answer though as I spit the bits the other way around
Comment: @PaulS. hmm, you could be right about that here.. :-| Though, there is a loop-up factor involved. Need to test... The new just creates a reference to the internal buffer though (the same array buffer is used for both).
Comment: @Ken, thats a good question I would assume, clamping may be faster, but thats best left to a javascript engine engineer, or perhaps someone could create a jspref to test it?
Comment: @Mouseroot we should really test it for future references (or at least for the fun of it) :-)
Comment: @Ken Can you link to a good source on buffers? I really like your implementation btw and would like to know more about the thought behind it.
Comment: when I tried to remove the `new` keyword i got a typeerror in chromium.

`Uncaught TypeError: Constructor Uint32Array requires 'new' `
Comment: @Mouseroot Ok guys, the winner is... http://jsperf.com/iterate-8-vs-32-bits-typed-array (seems to be 32-bit buffer on my machine FF and Canary)
Comment: @Mouseroot you will need the new keyword. It creates a setup to make sure the value written to the array buffer is correct, but the buffer is the same (given as a reference in the constructor).
Comment: @IlanBiala I just made this one from the top of my head, but I remember Html5rocks has some good stuff on typed arrays: http://www.html5rocks.com/en/tutorials/webgl/typed_arrays/
Comment: Unfortunately, this isn't working in my browser (just so you know): Windows 8.1, IE 11.
Comment: @user-12506 did you get any error message in console?
Comment: I also noticed this didn't work in IE 11. I've gotten an error in the console: `Typed array constructor argument is invalid` @ `new Uint32Array(noisePatterns[noisePatterns.length - 1].data.buffer)`
Comment: Strangely the demo works in Firefox 111 but not Chrome 111.
Answer: I tried to make a similar function a while ago. I set each pixel random value, and in addition to that, I overlayed a sinusodial wave that traveled upwards with time just to make it look more realistic. You can play with the constants in the wave to get different effects.

var canvas = null;
var context = null;
var time = 0;
var intervalId = 0;

var makeNoise = function() {
  var imgd = context.createImageData(canvas.width, canvas.height);
  var pix = imgd.data;

  for (var i = 0, n = pix.length; i < n; i += 4) {
      var c = 7 + Math.sin(i/50000 + time/7); // A sine wave of the form sin(ax + bt)
      pix[i] = pix[i+1] = pix[i+2] = 40 * Math.random() * c; // Set a random gray
      pix[i+3] = 255; // 100% opaque
  }

  context.putImageData(imgd, 0, 0);
  time = (time + 1) % canvas.height;
}

var setup = function() {
  canvas = document.getElementById("tv");
  context = canvas.getContext("2d");
}

setup();
intervalId = setInterval(makeNoise, 50);
<canvas id="tv" width="400" height="300"></canvas>

I used it as a preloader on a site. I also added a volume rocker as a loading bar, here's a screenshot:
Answer: I re-wrote your code so each step is separate so you can re-use things without having to create and re-create each time, reduced in-loop calls and hopefully made it clear enough to be able to follow by reading it.
function generateNoise(opacity, h, w) {
    function makeCanvas(h, w) {
         var canvas = document.createElement('canvas');
         canvas.height = h;
         canvas.width = w;
         return canvas;
    }

    function randomise(data, opacity) { // see prev. revision for 8-bit
        var i, x;
        for (i = 0; i < data.length; ++i) {
            x = Math.floor(Math.random() * 0xffffff); // random RGB
            data[i] =  x | opacity; // set all of RGBA for pixel in one go
        }
    }

    function initialise(opacity, h, w) {
        var canvas = makeCanvas(h, w),
            context = canvas.getContext('2d'),
            image = context.createImageData(h, w),
            data = new Uint32Array(image.data.buffer);
        opacity = Math.floor(opacity * 0x255) << 24; // make bitwise OR-able
        return function () {
            randomise(data, opacity); // could be in-place for less overhead
            context.putImageData(image, 0, 0);
            // you may want to consider other ways of setting the canvas
            // as the background so you can take this out of the loop, too
            document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
        };
    }

    return initialise(opacity || 0.2, h || 55, w || 55);
}

Now you can create some interval or timeout loop which keeps re-invoking the generated function.
window.setInterval(
    generateNoise(.8, 200, 200),
    100
);

Or with requestAnimationFrame as in Ken's answer
var noise = generateNoise(.8, 200, 200);

(function loop() {
    noise();
    requestAnimationFrame(loop);
})();

DEMO
Comment: why do you have functions inside functions?
Comment: @IlanBiala, closures, to expose the inner function to the outer function variables, for a really good explenation look up Douglas Crawford `javascript, the good parts`
Comment: @IlanBiala I only really needed to have one (that gets returned) but I wrote many so each "step" is clear.
Answer: Ken's answer looked pretty good, but after looking at some videos of real TV static, I had some ideas and here's what I came up with (two versions):
http://jsfiddle.net/2bzqs/
http://jsfiddle.net/EnQKm/
Summary of changes:

Instead of every pixel being independently assigned a color, a run of multiple pixels will get a single color, so you get these short, variable-sized horizontal lines.
I apply a gamma curve (with the Math.pow) to bias the color toward black a little.
I don't apply the gamma in a "band" area to simulate the banding.

Here's the main part of the code:
var w = ctx.canvas.width,
    h = ctx.canvas.height,
    idata = ctx.createImageData(w, h),
    buffer32 = new Uint32Array(idata.data.buffer),
    len = buffer32.length,
    run = 0,
    color = 0,
    m = Math.random() * 6 + 4,
    band = Math.random() * 256 * 256,
    p = 0,
    i = 0;

for (; i < len;) {
    if (run < 0) {
        run = m * Math.random();
        p = Math.pow(Math.random(), 0.4);
        if (i > band && i < band + 48 * 256) {
            p = Math.random();
        }
        color = (255 * p) << 24;
    }
    run -= 1;
    buffer32[i++] = color;
}

Answer: I happen to have just written a script that does just this, by getting the pixels from a black canvas and just altering random alpha values and using putImageData
Result can be found at http://mouseroot.github.io/Video/index.html
var currentAnimationFunction = staticScreen
var screenObject = document.getElementById("screen").getContext("2d");
var pixels = screenObject.getImageData(0,0,500,500);
function staticScreen()
        {
            requestAnimationFrame(currentAnimationFunction);
            //Generate static
            for(var i=0;i < pixels.data.length;i+=4)
            {
                pixels.data[i] = 255;
                pixels.data[i + 1] = 255;
                pixels.data[i + 2] = 255;
                pixels.data[i + 3] = Math.floor((254-155)*Math.random()) + 156;
            }
            screenObject.putImageData(pixels,0,0,0,0,500,500);
            //Draw 'No video input'
            screenObject.fillStyle = "black";
            screenObject.font = "30pt consolas";
            screenObject.fillText("No video input",100,250,500);
        }

Answer: Mine doesn't look identical to real TV static, but it's similar nonetheless. I'm just looping through all the pixels on canvas, and changing the RGB colour components of each pixel at a random coordinate to a random colour. The demo can be found over at CodePen.
The code is as follows:
// Setting up the canvas - size, setting a background, and getting the image data(all of the pixels) of the canvas.
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
canvasData = ctx.createImageData(canvas.width, canvas.height);

//Event listeners that set the canvas size to that of the window when the page loads, and each time the user resizes the window
window.addEventListener("load", windowResize);
window.addEventListener("resize", windowResize);

function windowResize(){
  canvas.style.width = window.innerWidth + 'px';
  canvas.style.height = window.innerHeight + 'px';
}

//A function that manipulates the array of pixel colour data created above using createImageData()
function setPixel(x, y, r, g, b, a){
  var index = (x + y * canvasData.width) * 4;

  canvasData.data[index] = r;
  canvasData.data[index + 1] = g;
  canvasData.data[index + 2] = b;
  canvasData.data[index + 3] = a;
}

window.requestAnimationFrame(mainLoop);

function mainLoop(){
  // Looping through all the colour data and changing each pixel to a random colour at a random coordinate, using the setPixel function defined earlier
  for(i = 0; i < canvasData.data.length / 4; i++){
    var red = Math.floor(Math.random()*256);
    var green = Math.floor(Math.random()*256);
    var blue = Math.floor(Math.random()*256);
    var randX = Math.floor(Math.random()*canvas.width);
    var randY = Math.floor(Math.random()*canvas.height);

    setPixel(randX, randY, red, green, blue, 255);
  }

  //Place the image data we created and manipulated onto the canvas
  ctx.putImageData(canvasData, 0, 0);

  //And then do it all again...
  window.requestAnimationFrame(mainLoop);
}

Comment: I think that for true randomness, it would not make sense to randomize the pixel that is being written, since the value is random already.
Answer: You can do it like this:
window.setInterval('generateNoise(.8)',50);
The 2nd arg 50 is a delay in milliseconds. Increasing 50 will slow it down and decreasing visa versa.
though.. this is going to severely affect web page performance. If it were me, I'd do the rendering server-side and render a handful of frame iterations and output as an animated gif. Not quite the same as infinite randomness, but would be a huge performance boost and IMO most people won't even notice.

Animating canvas to look like tv noise


How to do the equivalent of setting an array element with a sequence in numpy?

Question: I just ended up being confused about this for a while, so I thought I'd document in Q&A format - although more thorough explanations are more than welcome.
Let's say, I have a 2D numpy array, say xm below:
$ python3
Python 3.8.9 (default, Apr  3 2021, 09:30:04)  [GCC 10.2.0 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
import numpy as np
x = y = np.linspace(0,1.0, 4)
xm,ym = np.meshgrid(x,y)
xm
array([[0.        , 0.33333333, 0.66666667, 1.        ],
       [0.        , 0.33333333, 0.66666667, 1.        ],
       [0.        , 0.33333333, 0.66666667, 1.        ],
       [0.        , 0.33333333, 0.66666667, 1.        ]])
>>>

... and I want to replace each element, with an array of 3 elements - say, with: the basis [1.0, 1.0, 0.5], multiplied by the scalar value of each element of the 2D array.
Multiplication of a numpy array with a scalar is trivial:
xm*2
array([[0.        , 0.66666667, 1.33333333, 2.        ],
       [0.        , 0.66666667, 1.33333333, 2.        ],
       [0.        , 0.66666667, 1.33333333, 2.        ],
       [0.        , 0.66666667, 1.33333333, 2.        ]])

... but attempting to do "scalar (element od 2D array) times list" trivially does not work:
xm*np.array([1,1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,4) (2,)

... and trying to cheat by iterating through all the elements of the 2D array, and replacing each with a list/array, also fails:
for ir, irow in enumerate(xm):
  for ic, icol in enumerate(irow):
    xm[ir][ic] = icol*np.array([1, 1, 0.5])
...
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: setting an array element with a sequence.

Yeah - but I do want do set an array element with a sequence - or at least, obtain the equivalent kind of array. How do I do that?
Answer: Turns out, I "simply" have to reshape the arrays - basically:

first reshape xm of shape (4, 4) to 1D numpy array, which then has shape (16, 1);
multuplying each (scalar) element of that with the 1d numpy array basis, which has shape (3,), is trivial -- and we obtain a result with is an array of 3-element arrays, with a shape of (16, 3);
reshape that result into a numpy array of shape (4, 4, 3) - basically, we got a 3D array/matrix now

np.reshape( np.reshape(xm, (-1,1))*np.array([1,1,0.5]), (xm.shape[0], xm.shape[1], 3) )
array([[[0.        , 0.        , 0.        ],
        [0.33333333, 0.33333333, 0.16666667],
        [0.66666667, 0.66666667, 0.33333333],
        [1.        , 1.        , 0.5       ]],

       [[0.        , 0.        , 0.        ],
        [0.33333333, 0.33333333, 0.16666667],
        [0.66666667, 0.66666667, 0.33333333],
        [1.        , 1.        , 0.5       ]],

       [[0.        , 0.        , 0.        ],
        [0.33333333, 0.33333333, 0.16666667],
        [0.66666667, 0.66666667, 0.33333333],
        [1.        , 1.        , 0.5       ]],

       [[0.        , 0.        , 0.        ],
        [0.33333333, 0.33333333, 0.16666667],
        [0.66666667, 0.66666667, 0.33333333],
        [1.        , 1.        , 0.5       ]]])

Answer: Use:
xm[:, :, np.newaxis]*np.array([[1.0, 1.0, 0.5]])

Output:
array([[[0.        , 0.        , 0.        ],
    [0.33333333, 0.33333333, 0.16666667],
    [0.66666667, 0.66666667, 0.33333333],
    [1.        , 1.        , 0.5       ]],

   [[0.        , 0.        , 0.        ],
    [0.33333333, 0.33333333, 0.16666667],
    [0.66666667, 0.66666667, 0.33333333],
    [1.        , 1.        , 0.5       ]],

   [[0.        , 0.        , 0.        ],
    [0.33333333, 0.33333333, 0.16666667],
    [0.66666667, 0.66666667, 0.33333333],
    [1.        , 1.        , 0.5       ]],

   [[0.        , 0.        , 0.        ],
    [0.33333333, 0.33333333, 0.16666667],
    [0.66666667, 0.66666667, 0.33333333],
    [1.        , 1.        , 0.5       ]]])


Liszt - Hungarian Rhapsody No. 2 (Piano Solo) - Measure 306

Question: In the picture below, there is a significant stretch where the melody in the upper staff is at a lower pitch than the accompaniment in the lower staff.
Does Liszt intend for me to cross my right-hand over my left?  Or am I meant to begin playing the upper staff with my left hand and the lower staff with my right?
If he means for me to cross over, is there a generally accepted preference between crossing my right hand over my left vs. under my left or vice-versa?
Answer: As I understand it, this would be played by crossing your right hand over your left and playing the lower notes with your right hand.
In general, I think the hand that moves will be on top of the 'anchor' hand (the one that remains in position).
Comment: Alternatively, he could have anticipated an evolution in humanity by now whereby you would have a third hand with which to play this section.  Food for though.
Comment: Ahh, this is how my hands naturally wanted to play it, so that's good.  Thanks for the input!!


Perfomance problem when posting

Question: Sometimes when I submit a new post (story node) or update one, it take 10-15 minutes for the page to finish loading. I figured it was some problem with the database so I did a SHOW FULL PROCESSLIST the next time I noticed it happening. It was stuck deleting from the boost_cache_relationships table. Why is this taking so long and what can I do to fix this?
Here's part of the output from SHOW FULL PROCESSLIST showing the problem query:
+---------+---------+-----------+-----------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| Id      | User    | Host      | db              | Command | Time | State          | Info                                                                                |
+---------+---------+-----------+-----------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| 2208461 | upgrade | localhost | dane101_upgrade | Query   |   28 | Sending data   | SELECT SUM(score) FROM search_index WHERE word = 'when'                                              |
| 2208478 | upgrade | localhost | dane101_upgrade | Query   | *1088* | updating       | **DELETE FROM boost_cache_relationships WHERE base_dir = 'cache/normal/www.dane101.com' AND page_callb**  |
|

Comment: If you clear the boost cache, does saving speed up again? Are you using InnoDB for tables? Are you on shared hosting or your own box?
Comment: Hi Shane and welcome to Drupal Answers. A simple delete query should not be a problem, and it might not be the actual problem. Most likely there is some underlying problem somewhere. It's pretty much impossible to say what the problem is, with the current info provided. If I understand your data correct, it only took 1 sec to delete the record, long but not horrible. Anyways steps to help debugging would be to look at the error log, look at the watchdog or record queries with devel and review the time it took each query to execute. Also is this on your dev environment or a host site?
Comment: I should have provided more information in my question. This is on a production site, private server. I'm using INNODB for the tables. The delete query took 1088 seconds which is over 15 minutes. I'll take a look at the watchdog and check the queries running with devel to get more information.  THanks for the suggestions.
Answer: It appears you may be having the same issue as this person - http://drupal.org/node/1136822
May I suggest you apply the tweaks mentioned in the issue, and if it improves your performance, perhaps consider writing a patch to place back in the issue queue.
I have cross linked the drupal.org issue with this, so that everything is visible
Answer: Boost db usage is (currently) not suitable for site using Views and has large number of nodes. Check this issue http://drupal.org/node/715450 and the suggestion in #6
Comment: Giving this a try. I'm surprised the boost module page doesn't have some kind of warning about this.
Answer: Try to make an EXPLAIN on the DELETE query to see if it's using the index in a correct way.
Andrew Berry wrote an interesting post regarding this matter on Lullabot's blog: Slow Queries? Check the Cardinality of Your MySQL Indexes.
Comment: Giving this a try.
Answer: Generically & correctly handling views logic in terms of cache expiration is tricky to say the least. There's a reason that by default drupal does a clear_cache_all on node_save; makes worrying about old cached content showing up a thing of the past. I figured one could do better, and for my use case, boost's expiration logic works great with views and panels. For other peoples use cases it might not work as well. If your not using the latest dev, I recommend giving it a shot as it works better in this aspect.
Due to where I work, I have a fairly good idea in terms of what needs to happen to make this a better setup; yes we use boost, but mainly for the relational data it generates (the part your complaining about). Time is the issue. Been busy with more pressing issues; I've sunk the last 6 months into the Advanced CSS/JS Aggregation module and there is still a little bit more dev work to do on it.
The big plan is to move the complicated views/panels relational logic into sub-modules of the expire module, but thats still a long ways off. Getting one of the async js loaders working 100% with panels, wysiwyg & chrome (LABjs, HeadJS) will give us more bang for the buck from our perspective. AdvAgg is laying the foundation for better front end performance; & HeadJS is starting to take full advantage of that.
Long story short, I'm aware of the issues; but they are not affecting us at work thus I can't allocate much time to fixing them. Boost is a very critical bit of our infrastructure (controls varnish & other systems), so things will eventually happen; just don't hold your breath. BTW we are up to 600k nodes on one of our 70 databases so it really is a case of your mileage may vary.

Perfomance problem when posting


Help with custom jQuery validation function

Question: I have a form attribute like so:
onsubmit="return valMyForm(this);"

And a jQuery function like so:
function valMyForm(f) {
  $(f,"input").each(function() {
      if($(this).length < 1) {
          alert("All Fields Required.");
          return false;
      }
          else
          return false;
  });
}

The form still submits even if I remove all of the code and just put return false;
Comment: Not to nit-pick, but the last `else` isn't necessary. ;-)
Comment: @Brad, thank you, I am always looking for shorter ways to write code.
Answer: The return false inside the each function is just exiting out of the each loop. It's not returning the value for valMyForm
You should use something like a valid variable and return that:
function valMyForm(f) {
  var valid = true;
  $("input", f).each(function() {
      if($(this).val().length < 1) {
          alert("All Fields Required.");
          valid = false;
      }
  });

  return valid;
}

Here is a working example for you: http://jsfiddle.net/adpMT/
Comment: here's a demo of what I've come up with: http://www.jsfiddle.net/Unny3/1/ in case you're interested.
Comment: @Brad Christie - Ah, I actually just posted a fiddle for you in my answer
Comment: I think you're is best answer. I can't seem to get short-hand of `[value=""]` wot work from Darin's example. So +1 to you. ;-)
Answer: When you return you are inside the .each function so you are not actually returning anything from the valMyForm method.
I would recommend you avoid mixing markup with javascript and do this unobtrusively:
<form action="/foo" id="myform">
   ... some input fields
</form>

and then:
$(function() {
    $('#myform').submit(function() {
        // see if the form contains some empty inputs
        return $(this).find(':input[value=""]').length > 0;
    });
});

Comment: @Brad: Yep, I know. That's why `$(f).find('input')` is better. It doesn't need to run through a bunch of tests before it just flips it around and starts over. :o)
Comment: @Darin: I may be wrong, and don't know how the function is being called, but I think the input selector needs to be reversed too, to: `$('input',f)`. But again, I don't know how the function's being called.
Comment: @Darin Dimitrov, ha it would help if I told it to check the length of the value.
Comment: @Brad, the form is passing my function a parameter of 'this'.
Comment: @nick: Brad is right. Your selector is looking for `f` within the context of all the `input` elements on the page. You should be looking for `input` elements in the context of `f`. `$('input',f)` or better `$(f).find('input')`
Comment: @Darin, the function works, as in it shows the alert box, but then when I hit ok it posts the form :(
Comment: @nick, what is the value of the `$(this).find('input[value=""]').length > 0` expression inside the submit event?
Comment: @patrickdw: `$('input',f)` is short-hand for `$(f).find('input')`, according to the jQuery docs. ;-) Also, @DarinDimitrov: +1 for the short-hand solution. ;-)
Comment: @DarinDimitrov: It appears jQuery isn't fond of [value=""], at least in my tests...
Comment: @Brad, I did a mistake. The correct selector should be `var isValid = $(this).find(':input[value=""]').length < 1`. Here's a [live demo](http://jsfiddle.net/whgXU/3/).


datasource failing to map to the transformed json using pagination

Question: I am using pagination.js to load asynchronous data using below code snippet.
$('#demo').pagination({
    dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?',
    locator: 'items',
    totalNumber: 120,
    pageSize: 20,
    ajax: {
        beforeSend: function() {
            dataContainer.html('Loading data from flickr.com ...');
        }
    },
    callback: function(data, pagination) {
        // template method of yourself
        var html = template(data);
        dataContainer.html(html);
    }
})

As my json structure is different, I need to transform my json before mapping it to datasource, so I have changed the above code to as shown below:
$('#demo').pagination({
      dataSource: getTransformedJson(),
      locator: 'items',
      totalNumber: 120,
      pageSize: 25,
      ajax: {
        beforeSend: function() {
          container.prev().html('Loading products data ...');
        }
      },
      callback: function(response, pagination) {
        var dataHtml = '
';
          console.log('response', response)
        $.each(response, function (index, item) {
          dataHtml += '
' + item.productName + '
';
        });

        dataHtml += '
';

        container.prev().html(dataHtml);
      }
    })
  });

However in the callback,   console.log('response', response) always shows empty array response [], in the browser console. Below is my getTransformedJSON() function:
function getTransformedJson() {
      $.getJSON('./products.json', function(data) {
        transformedData = data;
        totalCount = data['response']['totalCount'];
        transformedData['items'] = data['response']['results'];
        delete transformedData['response']["results"];
        console.log(transformedData);
          });

          return transformedData;
    }

But in my getTransformedJson() function, console.log(transformedData); shows the properly transformed json data.  Any fixes for this please.
Comment: $.getJSON is async. Your function is returning before $.getJSON is finished.
Comment: svela, how can i ensure function does not end before $.getJSON  is finished or how can make sure my datasource will be properly mapped the transformed json
Comment: Please find my answer below
Answer: Something like this:
dataSource: function(done) {
    $.getJSON('./products.json', function(data) {
        transformedData = data;
        totalCount = data['response']['totalCount'];
        transformedData['items'] = data['response']['results'];
        delete transformedData['response']["results"];
        done(transformedData);
     });

 }

Comment: It is giving me the error, uncaught ReferenceError: done is not defined. can you please tell me what should that done definition should be
Comment: Have you included pagination.js correctly? https://jsfiddle.net/3ud6mfct/1/
Comment: ...or with the use of $.getJSON: https://jsfiddle.net/3ud6mfct/2/