Accessing data from Google App Engine datastore in a javascript file

Question: What are the options for accessing information from Google App Engine datastore in a javascript file?
BACKGROUND:
I am running an app on Google App Engine which uses the Google Chart Tools API. All the data which I would like to graph is in my Google App Engine datastore.
WHAT I'VE TRIED
I can access the data within my python script. Also, in the python script, I encode the data to JSON. My idea was to save this in a js file, which I could import into the HTML, then build the chart there. However, this does not work, because writing to local files is not supported in App Engine.
Comment: Is the channel api not an option/applicable?
my first thought: send the data to memcache and with a channel and a python handler send the json to the client side JS...but that's just a first thought mind you.
Comment: It seems that the channel api is an option, but it might be overkill for what I am doing. The channel api creates a persistent connection for updating information immediately, where as my application will not need to send users such updates.
Answer: XMLHttpRequest
From the python file: Write the JSON data to a URL.
In App Engine, this is done with
self.response.write(data)

From the Javascript, make the XHR request like this:
function getData() {
    var dataObject = new XMLHttpRequest();
    dataObject.open('GET', 'URL', true);
    dataObject.send();
    return dataObject;
}

This will return a XMLHttpRequest object with the data in a string in the response or responseText attribute.
Comment: To be clear, the returned object won't have the data yet.  You need to use the `onreadystatechange` event to handle the data being received.  See http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
Answer: On App Engine you typically generate an HTML page that you serve to a client.  You don't need to save your JSON to a js file, you can embed it directly as text into your HTML page that you serve to your client.
Answer: You can use something like Jersey to create a REST api for the backend.  It's a bit of work.  You can also make a GWT application with the appengine project, which has really extremely easy backend hookups.  Then you can interface this with your javascript application or have hooks that your javascript application can use.


How do I figure out what mode this Pater Noster is in?

Question: I have been singing this Pater Noster:
Before Pater Noster starts we have the Oremus. Let's assume that C is Do.
Then the recitation notes, we have two, would be A and B. This seems strange to me. The finalis would be A.
When Pater Noster starts the recitation note would be B and G the finalis.
Then at "sed libera..." we have the same finalis but go back to A as the recitation note.
In another sheet music for this melody we have something, what I think, is a bit strange going on.

This version seems to assume C as Do.
If so, then they have changed the melody. If they assume Bb as Do they would have two flats instead of just one. This is strange. It thought it was in some kind of Lydian mode before I saw the Gregorian sheet music.
The melody does sound more major than minor.
How do I figure out what mode this Pater Noster is in?
Comment: I don't have a definitive answer. But I am confused by your confusion about the sheet music. What do you mean by "This version seems to assume C as Do. If so, then they have changed the melody"? They are clearly taking Bb for the original keynote, and the melody is unchanged. They have made a decision to harmonise the melody using E naturals instead of Eb's. As a practical choice catering for modern ears this seems reasonable since the melody sits comfortably in F major, and feels more awkward to harmonise with Eb's (although you could do a version which avoids E's altogether).
Comment: @PiedPiper this question is much less basic than "What key is this song in?".
Comment: It closely resembles Psalm Tone 1 but notated up a step. Normally that tone would begin F-G-A, mediant G-Bb-A-G-A, final A-G-F-G-A-A. Psalm tone 1 matches with mode 1 but they are not the same thing. Not every chant is in a mode. Mode is mostly helpful for matching chants with antiphons, which you wouldn't need to do here.
Comment: @JamesMartin in the terminology of Solesmes, for example in the US edition of the _Liber usualis,_ the C clef is the _Doh_ clef and pitch is explicitly relative.  Thus, putting the chant into modern notation where the "doh clef" is C -- in other words, without transposition -- may be called "using C for doh."  Since the modern arrangement shown here has transposed it down a whole step ("use B flat for doh"), one would indeed normally expect two flats in the signature, but as you note it's quite natural to use the one-flat signature because of considerations of harmony and tonality.
Comment: I thought it was Lydian since it had Mi as the recitation note.
Comment: In Guidonian solmization, A is only mi in the soft hexachord.  This piece does not use the soft hexachord.  The modern harmonization is transposed down a whole step, but, as @JamesMartin notes, harmonized in the key of F major rather than in F mixolydian.  It is not particularly unusual for a harmonization to use a different key from the melodic mode, especially since neither major and minor keys (nor Ionian and Aeolian modes) existed in the medieval music theory.
Comment: @musarithmia that is a good point, but nonetheless psalm tone 1 being in mode 1 implies a final of D, which isn't the case here.
Comment: In the square notation, the first pitch is A but all pitch is relative. This would be solmized in the hard hexachord (on G) where G-A-B is ut-re-mi (do was invented later). In the harmonized example, the same melody is notated in the soft hexachord (on F), where F-G-A is ut-re-mi. As a description of how the melody sounds, both notations achieve the same effect and are equivalent (ignoring the harmonization).
Answer: Consensus online seems to be that it is very early chant, which explains its lack of compliance with the usual description of the medieval ecclesiastical modes.  The closest fit is hypomixolydian, since the final is G and the melody ranges below the final.  This would normally mean a reciting tone of C, but here we have a reciting tone of A.  Well, this won't be the last time that a theoretical framework fails to describe a piece of music.
The fact that a modern harmonization has transposed it down a whole step but harmonized it in F instead of B flat doesn't have any bearing on the modal analysis of the melody in medieval theory.  Had the original melody included some Fs the arranger might have made a different choice, but as noted by James Martin in the comments, harmonizing this chant tonally is natural for modern ears (and a tendency to raise the leading tone in the mixolydian and hypomixolydian modes was one of the forces leading toward the development of tonality).
Speaking of that, there is no such thing as do in medieval music theory.  I am not an expert in solmization, but the entire tune fits in the hard hexachord except for that one E, so that would mean that the initial A of the oremus is re with the G of pater being ut,  Only the E requires mutation to the natural hexachord, where it is mi.  The remainder of the chant requires mutation back to the hard hexachord because of the B.
By the 19th century, church musicians were using modern solfège syllables, where C is do and B is si, so in this sense "fixed do," but the pitch was not absolute, so in that sense "movable do."
Comment: I also came up with Mixolydian. On further examination, the first part uses A as a reciting tone and the latter part uses B (and a bit of A). Chants with more than one reciting tone sometimes are just called "Tonus Perigrinus." (  Falcon Tone and his brother Franchet?) I don't know if the "Wandering Tone" is a cop-out or if one could analyzing parts of the chant as transposed.
Comment: In Gregorian chant notation we have a Fa clef and a Do clef. We really do!   And yes, the A would be Re as you said.
Comment: It is also interesting to note that we have some chants with only three notes. The theory of church modes do not seem to be made with those in mind. So standard theory can be problematic in certain cases?
Comment: @harryjansson the Do and Fa clefs are originally C and F clefs, which is why they have the shape of those letters.  The idea of calling them Do and Fa clefs could not have arisen before the late Renaissance.  (And in medieval theory, C could be ut, fa, or sol, while F could be ut or fa.)  Whether modal ambiguity of a melody is problematic is a matter of opinion.  It's also not possible to say whether such a melody is in a major or minor key in modern tonal practice.
Comment: Or before the 18th century in fact, if Wikipedia is to be believed about the timing of the invention of _si._
Comment: @ttw my understanding is that "tonus peregrinus" refers to a specific psalm reciting tone where the tenor is on A for the first half of the verse and G for the second half (it makes an appearance in the _te decet_ of Mozart's Requiem among many other places).  The Pater noster is not like this at all (and the B is only prominent in the oremus, which isn't necessarily the same piece).  Most liturgical chant sung by clergy and congregation is like this, cadencing on or near the reciting tone rather than far below it.  The chants with wider ranges are those to be sung by the choir.
Comment: E in hard hexachord = la, no mutation needed
Comment: @musarithmia it's not the same hard hexachord as the other notes, though; it's in the wrong octave.  An ascending minor third is re-fa or mi-sol, not la-ut.


Building a "re"- streaming video server with vlc as core

Question: I am creating a re-streaming video server based on VLC (streaming, transcoding,etc). The main goal of this software component is to abstract users from the video source (webcam, screen,ip-cameras,files,etc) avoiding to view the video without previous auth. The problem is that the same video can be requested with different properties by distinct users. The questions are.

How can i do this with VLC?
How can i stream to multiples location with VLC?
Is VLC a good choices for that work?
Answer: You need a software called media server to effectively handle this task. VLC or ffmpeg or other software like that is good to process input streams and transcode them. Media servers may take the processed stream and handle end-users connections.
Please specify what protocol you'd like to use for users' playback to see what's the best choice for your case.
Comment: What i am building is something like a media server then. I am using C# for this work. There exists some basic project to start (C#)


Is $\frac{x^3}{x^2+y^4}$ continuous at (0,0)?

Question: In an exam I was asked to determine if a function $f:\mathbb R^2\to \mathbb R$ is continuous at a point $(x_0,y_0)$, I needed to check if $$\lim_{(x,y) \to (x_0,y_0)} f(x,y) = f(x_0,y_0)$$
We consider the function given by $f(x,y)=\frac{x^3}{x^2+y^4}$ if $(x,y)\neq (0,0)$ and $f(0,0)=0$.
We want to know if $f$ is continuous at $(0,0)$. What I did is the following :
We have that for $(x,y) \neq (0,0)$, $0\leq \frac{x^2}{x^2+y^4}\leq1$ and if $x>0$ $\implies 0\leq \frac{x^3}{x^2+y^4}\leq x$.
And if $x<0$, $x\leq \frac{x^3}{x^2+y^4}\leq 0$
Then I used the squeeze theorem and said something very weird and stupid : $$"\lim_{(x,y) \to (0^+,0)} f(x,y)=\lim_{(x,y) \to (0^-,0)}f(x,y)=0"$$
First of all we never spoke or defined multivariable limits like that with $0^+$ and $0^-$, I am starting to realize when I am writing this that I could have been smarter and said that $-\lvert x \rvert \leq \frac{x^3}{x^2+y^4} \leq \lvert x \rvert$ and squeeze theorem to give me the continuity in $(0,0)$. The second point is that WolframAlpha tells me that the limit does not exist even though I tried many different paths such as $(t,t), (t^2,0)...$ to see if the function was discontinuous. Who is right ?
Comment: your argument with the squeeze theorem and absolute value seems correct. Wolfram alpha may make mistakes or be confused sometimes. (What you wrote is more or less correct with $0^+$ and you may or should get some partial credit at least ... even if that is not formally defined.)
Comment: @Mirko Yes, Wolfram Alpha may make mistakes, but there was no mistake here. Take a look at my answer.
Comment: @Mirko In fact I feel like approaching in $x$ a positive and negatives directions only and the corrector will surely tell me "what happens if I choose to zigzag between x positive and negative to approach $(0,0)$ ?"
Comment: @José I tried to make Wolfram understand that the variables are real, without much success, though it at least produced a graph and Taylor expansion from which it is clear the the limit is 0. I know there ought to be a way to tell Wolfram what I need, but I will leave it as is. https://www.wolframalpha.com/input/?i=lim_%7B%28x%2Cy%29+to+%280%2C0%29%7D+%5Cfrac%7Bx%5E3%7D%7Bx%5E2%2By%5E4%7D+where+x+and+y+are+real+variables (Actually I need to think if the Taylor expansion shown there is useful.)
Answer: And Wolfram Alpha is indeed right. And so are you. In $\Bbb R^2$, that limit is indeed $0$. But in $\Bbb C^2$ that limit does not exist. For instance,\begin{align}\lim_{n\to\infty}f\left(\left(\frac1n+\frac1{n^3}\right)^2,\frac{1+i}{n\sqrt2}\right)&=\lim_{n\to\infty}\frac{\frac{1}{n^6}+\frac{6}{n^8}+\frac{15}{n^{10}}+\frac{20}{n^{12}}+\frac{15}{n^{14}}+\frac{6}{n^{16}}+\frac{1}{n^{18}}}{\frac{4}{n^6}+\frac{6}{n^8}+\frac{4}{n^{10}}+\frac{1}{n^{12}}}\\&=\frac14.\end{align}And what Wolfram Alpha says is that the value of the limit may depend on the path in the complex plane.
Comment: WA should know that nobody uses $x, y$ for complex numbers :)
Comment: Ah okay ! I didn't know about it in $\mathbb C^2$ thanks !
Comment: I'm glad I could help.
Answer: This is just an additional answer, addressing an extra question in the comments:
In fact I feel like approaching in $x$ a positive and negatives directions only and the corrector will surely tell me "what happens if I choose to zigzag between $x$ positive and negative to approach $(0,0)$ ?"
Then you would have to come up with a story, and say that your $(x,y) \to (0^+,0)$ notation meant that the point $(x,y)$ has $x$-coordinate $\ge0$, like $$\lim_{(x,y) \to (0,0)\\ x\ge0} f(x,y)=0$$ While this notation is not standard, one could argue that it makes sense and could be defined rigorously (so $(x,y)\to(0^+,0)$ means $(x,y)$ remains in the right-hand side closed half-plane $x\ge0$, not necessarily on any particular path).
Note that even if you have a function of only one variable, and say take $x_n=\frac{(-1)^n}n$, and if we knew that $\lim_{x\to0^+}f(x)=\lim_{x\to0^-}f(x)=0$ then we could conclude that $\lim_{n\to\infty}f(x_n)=\lim_{n\to\infty}f(\frac{(-1)^n}n)=0$ even if the sequence $x_n$ keeps "switching directions."
You may argue that $x_n=\frac{(-1)^n}n$ does "zigzag," yet this does not present any problem.
Perhaps you didn't mean all of the above, but it is possible to formalize (and now you may start thinking that intuitively that is exactly what you meant :)
At any rate, it might be an interesting exercise to try to think of the details and whether the above makes sense, whether or not you will end up discussing it with your corrector. You could just be prepared, and try to figure it for the sake of knowing that it could be made to make sense, if you wish.
(And well, the answer by José Carlos Santos shows what happens if you use complex variables, but in my answer both $x$ and $y$ are assumed real.)


How to calculate probabilities for football match?

Question: I am looking for the acceptible methods to calculate probability chances "1 x 2" on football matches. I read a lot of articles, but there are no useful information that can help me. I started to investigate probability theory myself and I freezed after some calculations.
Let imagine we have match between Chelsea and Liverpool. I understand how calculate probabilitly for each team. I took last ten Chelsea's home matches and last ten Liverpool's away matches. After simple calculations(win/10; draw/10; lose/10) I received:
<code>P(Chelsea win at home) = 0,5;
P(Chelsea draw at home)=0,3;
P(Chelsea lose at home) = 0,2;

P(Liverpool win away) = 0,2;
P(Liverpool draw away)=0,6;
P(Liverpool lose away) = 0,2;
</code>
But I could now understand how to use this calculated data to predict match Chelsea - Liverpool. I tries to apply sum and multiplication theorems, but there could be incredible result, for exmaple over 1. I definetly understand that this calculation would be very approximatly and that there are a lot of parameters that affect on football result, but I think that it could be useful to predict match. Thank you for any help!
Answer: What you have to do is to normalize the data. A simple way for it:

Add the probabilities which show the same result, to each other. In you example, you have to add Chelsea wins to Liverpool losses, Chelsea draws to Liverpool draws and Chelsea losses to Liverpool wins.

What you'll have is:
Chelsea Win: $0.55+0.25=0.80$
Draw: $0.35+0.55=0.90$
Liverpool Win: $0.10+0.20=0.30$

Then, divide those possibilities to two, to normalize the probabilities. Why two? Because you have two teams.

Chelsea Win: $0.40$
Draw: $0.45$
Liverpool Win: $0.15$
Of course, in real world it's not that simple as you have to calculate last 5 games form, injured and banned players and the statistics when they're not playing, last game score and date, games between those two teams in last 10 years etc.
For instance, in Turkey, Galatasaray hasn't won against Fenerbahçe away in last 15 years. Even Galatasaray was way ahead champion, they just couldn't win against Fenerbahçe. So, when calculating the probable result of Fenerbahçe - Galatasaray game, you have to consider that curse. So, in any game, you can't only look at their whole season form, or only last 5 games, or only "something". You have to consider each effect, and this is what makes the calculation complex.


Calcular valor input duplicado

Question: Tenho uma div com 3 inputs (valor, aliquota, valortotal) elas estão dentro de uma div clone em jquery... Consigo fazer o calculo através do id como no código abaixo, mas como ela é clonada em jquery só funciona na div principal pois não pode ter id duplicado..
Pensei em pegar o input pelo name, mas não consegui ainda...
Note,que ao clicar em "CLONAR" a div ele só funciona na div original, na clonada não..

//Função que calcula os Inputs pelo ID
function Calc(){

ValorUm = parseFloat(document.getElementById('valor').value);
ValorDois = parseFloat(document.getElementById('aliquota').value);

document.getElementById('valortotal').value = (ValorUm*ValorDois/100).toFixed(2);
}
//Função clone
  $(document).ready(function() {
    var linha = $(".engloba:first").clone();
    $("#mais").click(function() {
        $("#conteudo_engloba").append(linha.clone());
    });
 });

<form>
    <input type="button" name="" value="CLONAR" id="mais">
</form>

Conteudo

  Valor <input type="text" id="valor">
  Aliquota <input type="text" id="aliquota" onblur="Calc()">
  Valor Total <input type="text" id="valortotal">

Comment: Car anão entendi sua explicação... Por que você clona?
Comment: KhaosDoctor, amigo, veja que tem o botão "CLONAR" que faz uma cópia da div atual e cria outra div...
Answer: Segue abaixo a solução do seu problema com as minhas considerações:

$(document).ready(function() {
  clonar();
  $("#mais").on("click", clonar);
});

function calcularValorTotal() {
  var $aliquota = $(this);
  var $valor = $($aliquota.prev());

  var valor = parseFloat($valor.val());
  var aliquota = parseFloat($aliquota.val());

  var valorTotal = (valor*aliquota/100).toFixed(2);

  var $valorTotal = $($aliquota.next());
  $valorTotal.val(valorTotal);
};

function clonar() {
  var linha = $("#engloba-template > .engloba").clone();

  $(linha).find(".aliquota").on("blur", calcularValorTotal);

  $("#conteudo_engloba").append(linha);
};
#engloba-template {
  display: none;
}
<form>
  <input type="button" name="" value="CLONAR" id="mais">
</form>

Conteudo

    Valor <input type="text" class="valor">
    Aliquota <input type="text" class="aliquota">
    Valor Total <input type="text" class="valortotal">

Para trabalhar com clonagem você precisará deixar de usar id's e passar a usar classes.
É melhor você criar templates e deixa-los escondidos, do que você usar o HTML em uso na tela para fazer as suas clonagens. Além de ser uma boa prática, é mais claro de visualizar a responsabilidade de cada elemento.

No HTML passei o modelo da div .engloba para um template escondido display: none; e alterei os id dos input para class.
No JS passei a usar somente jQuery, além de separar os métodos em funções e aprimorar as suas nomenclaturas.
Comment: Valeu @Lucas de Freitas Kauer...funcinou aqui... valeuu!!
Answer: Com javascript é possível obter o elemento anterior e o próximo elemento de um determinado nó usando previousSibling e nextElementSibling:

function Calc(elemento) {
  var anterior = elemento.previousSibling;
  var ValorUm = parseFloat(anterior.previousSibling.value);
  var ValorDois = parseFloat(elemento.value);
  elemento.nextElementSibling.value = (ValorUm * ValorDois / 100).toFixed(2);
}
//Função clone
$(document).ready(function() {
  var linha = $(".engloba:first").clone();
  $("#mais").click(function() {
    $("#conteudo_engloba").append(linha.clone());
  });
});

<form>
  <input type="button" name="" value="CLONAR" id="mais">
</form>

Conteudo

    Valor
    <input type="text">Aliquota
    <input type="text" onblur="Calc(this)">Valor Total
    <input type="text">

Comment: valeu @Lucas Costa, funcinou aqui tbm! Valeu!

Calcular valor input duplicado


Is it possible to ensure uniqueness on a sharded hashed key in MongoDB?

Question: We need to shard our production DB in a very short timetable, now we have decided to shard on hashed(_id) - however, we have seen it is not possible to create a unique constraint on such an index.
Is it possible in any other way to ensure 100% of the time that we will never insert a duplicate document with the same _id?
We have thought about adding 2 index, 1 for the shard key (hashed(_id)) and a second as the default unique _id index - but we weren't sure if this was possible / would solve our problem.
Thanks in advance!
Comment: Please read http://docs.mongodb.org/manual/tutorial/enforce-unique-keys-for-sharded-collections/ _thoroughly_.
Comment: tl;dr: ObjectIds are _guaranteed_ to be unique, and a hash collision is less likely than winning the lottery a _lot_ of consecutive times in a row. If you hashed about 6 billion document per second, you would have a 50% chance to create a collision after 100 years. For almost all practical purposes, this should be sufficient.
Comment: @MarkusWMahlberg - I am aware of that, and I asked if there was a way around it.
Comment: Around what exactly? And what it your current `_id` made up of?
Comment: We currently shard on hashed _id, which is in fact BsonID - and we are aware it's considered as good as any GUID.

However, we have a identification collection that points to the sharded collection, where several various IDs can point to a single _id - that's why we must ensure that the sharded _id will always be unique - as we sometimes will have to manually insert our own BsonIds and there is a possible for duplicate insertion
Comment: Which should not make any difference: such things as host and timestamp are encoded in that value. Using upsert, you'd eliminate any chance of having a duplicate entry with the same id.
Comment: Upsert isn't an option for us on the product end. Let's assume for the sake of the question that the only real solution is making sure 100% that my hashed shard key will always be 100% unique.
Comment: You can't. MD5 is used for hashing. So there is a chance of 1 in 2^128 hashes that they collide.
Comment: The possible options for unique indexes in a sharded cluster are covered [in the manual](http://docs.mongodb.org/manual/tutorial/enforce-unique-keys-for-sharded-collections/). Will #2 work for you?
Comment: @MarkusWMahlberg The link mentioned in first comment is dead. Can you please update it?
Answer: OK so our solution was sharding on the _id (which has a forced unique index per Mongod/shard instance) and adding a hashed(_id) index which we sharded on. This ensures that all items are unique.


What is the main idea behind the power spectrum?

Question: Assume that we have a time series and we have calculate the corresponding auto-covariance function. Having the auto-covariance function we can calculate the corresponding power spectrum and having the power spectrum we can "restore" the auto-covariance function.
As far as I understood, to obtain the power spectrum we use Fourier transformation and to calculate the auto-covariance function from the power spectrum we use a back Fourier transformation. So, one can say that auto-covariance function and power spectrum are just time and frequency representation of the same function.
The first part of my question is about the interpretation of the power spectrum. For example, for the white-noise the power spectrum is a constant. Does it mean that the white noise can be understood as a sum of sinusoid functions with different frequencies and the same amplitude (the density distribution function of the frequency is uniform)?
I think that the answer is "No". I think that the auto-covariance function should be understood as an infinite sum of sinusoids.
The second part of the question is about use of the power-spectrum. Assume that we have it. Can we use it to predict time series? Or how do we use it?
Answer: The power spectrum is the frequency-domain counterpart of the time-domain autocovariance function.
According to the frequency-domain view, a white noise process can be viewed as the sum of an infinite number of cycles with different frequencies where each cycle has the same weight.
The power spectrum is not used to predict a time series. It is used to examine the main characteristics of the series and propose a time series model accordingly. For example, it can be used to detect if seasonality is present in the data, if so, the spectrum will show peaks at the seasonal frequencies.
In principle, the same information can be obtained from both the spectrum and the autocovariance function, but in some contexts it is more convenient to work
with the frequency-domain representation. For example, if you are interested in looking at the seasonal frequencies that determine the seasonal pattern observed in the series, the spectrum will show you the cycles that lead that component. If you want to analyze the frequency of some phenomenon such as the business cycle, the spectrum is a straightforward way to get a
graphical view to it.
Answer: Spectral density function is an Fourier transform of autocovariance function and there exists a Rietz - Fisher Representation theorem which states that time domain and frequency domain representations for the time series are almost equal.
There are actually methods for estimation on frequency domain which might take into account various frequency bands.
http://www.jstor.org/discover/10.2307/2526316?uid=3737976&uid=2&uid=4&sid=21105062541343
Comment: (+1) Nice reference.


Size of db2 database

Question: How can I get the size of my UDB DB2 version 9.1 database? I tried firing getdbconfig from the command prompt. It gives all the configuration but not the size.
Thanks :)
Answer: There is a TechNote on IBM's support site:
How to calculate the size of a DB2 database

If you want to calculate the size and
  maximum capacity of your database, you
  can use the procedure
  GET_DBSIZE_INFO. This procedure
  first appeared in DB2 Universal
  Database™ (DB2 UDB) Version 8.2.

To execute this procedure you should follow these three steps:

Connect to the database for which you want to know the size and maximum capacity.
Execute the procedure GET_DBSIZE_INFO.
Close the connection.

Here is the syntax of the procedure:
 db2 call GET_DBSIZE_INFO (?,?,?,refresh-window)

The first three  parameters are output parameters, and the refresh-window is an input parameter of type INTEGER that specifies the number of minutes until the cached values for database size and capacity are to be refreshed.
Refer to this documentation link for examples of the output from this procedure in DB2 UDB Version 9.1.
Answer: There's a script here which has been tested in 9.1 and, according to the author:

will calculate the size of a DB2 LUW
  database on a UNIX server using UNIX
  commands that will give you a more
  accurate measure of the space used by
  the database. This script also stores
  this information in an operational
  table that you may use as part of your
  DBA Monitoring Dash Board to help you
  monitor and manage space in relation
  to growth trends.
Answer: The GET_DBSIZE_INFO procedure calculates the database size and maximum capacity.
The calculated values are returned as procedure output parameters and are cached in the SYSTOOLS.STMG_DBSIZE_INFO table.
The procedure caches these values because the calculations are costly.
The SYSTOOLS.STMG_DBSIZE_INFO table is created automatically the first time the procedure executes.
If there are values cached in the SYSTOOLS.STMG_DBSIZE_INFO table and they are current enough, as determined by the snapshot-timestamp and refresh-window values, these cached values are returned.
If the cached values are not current enough, new cached values are calculated, inserted into the SYSTOOLS.STMG_DBSIZE_INFO table and returned, and the snapshot-timestamp value is updated.
The below returns the database size and capacity using a refresh window of 0 minutes. The database size and capacity will be recalculated immediately.
CALL GET_DBSIZE_INFO(?, ?, ?, 0)
Value of output parameters
--------------------------
Parameter Name  : SNAPSHOTTIMESTAMP
Parameter Value : 2004-02-29-18.104.22.1681000

Parameter Name  : DATABASESIZE
Parameter Value : 22302720

Parameter Name  : DATABASECAPACITY
Parameter Value : 4684859392

Return Status = 0

You may query the systools.stmg_dbsize_info directly to get the results as well.

db2 "select db_size, db_capacity from systools.stmg_dbsize_info"
db2 "select db_size/1073741824 as SIZE_GB, db_capacity/1073741824 as
  CAPACITY_GB from systools.stmg_dbsize_info"

db2 "select db_size, db_capacity from systools.stmg_dbsize_info"

DB_SIZE              DB_CAPACITY
-------------------- --------------------
       1089248165888        1342416097280

  1 record(s) selected.

db2 "select db_size/1073741824 as SIZE_GB, db_capacity/1073741824 as CAPACITY_GB from systools.stmg_dbsize_info"

SIZE_GB              CAPACITY_GB
-------------------- --------------------
                1014                 1250

  1 record(s) selected.

Size of db2 database


Linear model fitting iteratively and calculate the Variable Importance with varImp() for all predictors over the iterations

Question: I would like to iteratively fit a linear model (= LM) and calculate the variable importance of the individual variables/predictors after each iteration with the caret::varImp() function. My data table and the number of days look like this (the number of columns of dt.train can always differ and the days variable also):
d <- 50
## Create random data table: ##
dt.train <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 366),
                       "DE" = rnorm(366, 35, 1), "Wind" = rnorm(366, 5000, 2), "Solar" = rnorm(366, 3, 2),
                       "Nuclear" = rnorm(366, 100, 5), "ResLoad" = rnorm(366, 200, 3),  check.names = FALSE)

I also already have a function that calculates this for me every d days (here d<-50):
varImportance <- function(data){
  ## Model fitting: ##
  lmModel <- stats::lm(DE ~ .-1-date, data = data)

  terms <- attr(lmModel$terms , "term.labels")
  varimp <- caret::varImp(lmModel)
  importance <- data[, .(date, imp = t(varimp))]
}
## Get variable importance: ##
dt.importance <- dt.train[, varImportance(.SD), by = seq_len(nrow(dt.train)) %/% d]

Now I would like to have a loop that builds up the iteration for me as follows:
1. Run: Model fitting with the data from "2020-01-01" to "2020-02-20" (which are here exactly the 50 days)
2. Run: Model fitting with the data from "2020-01-02" to "2020-02-21"
3. Run: Model fitting with the data from "2020-01-03" to "2020-02-22"
... and so on
Last run: Model fitting with the data from "2020-11-11" to "2020-12-31"

The variable importance should then always be saved in a new table to match the model fitting, i.e.:
variable Importance of 1. Run: should be declared for "2020-01-01",
variable Importance of 2. Run: should be declared for "2020-01-02",
... and so on
variable Importance of Last Run: should be declared for "2020-11-11".
How could this work?
Answer: You could use rollapply from the zoo package.
Important arguments are :

width to set the window
by.column = FALSE to pass all the columns together to the model
aligned = 'left' so that the roll window starts from the first data point on

As rollapply works on matrices, it converts dates mixed with numeric to character, see, so that the date field had to be handled separately.
library(data.table)
library(caret)
library(zoo)

d <- 50
## Create random data table: ##
dt.train <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 366),
                       "DE" = rnorm(366, 35, 1), "Wind" = rnorm(366, 5000, 2), "Solar" = rnorm(366, 3, 2),
                       "Nuclear" = rnorm(366, 100, 5), "ResLoad" = rnorm(366, 200, 3),  check.names = FALSE)

varImportance <- function(data){
  ## Model fitting: ##
  lmModel <- stats::lm(DE ~ .-1, data = data.table(data))
  terms <- attr(lmModel$terms , "term.labels")
  varimp <- caret::varImp(lmModel)
  importance <- t(varimp)
}

# Removing date because rollapply needs a unique type
Importance <- as.data.frame(zoo::rollapply(dt.train[,!"date"],
                                           FUN = varImportance,
                                           width = d,
                                           by.column=FALSE,
                                           align='left')
                            )

# Adding back date
Importance <- cbind(dt.train[1:nrow(Importance),.(date)],Importance)

Importance
#>            date     Wind     Solar   Nuclear    ResLoad
#>   1: 2020-01-01 2.523219 1.0253985 0.1676970 0.80379590
#>   2: 2020-01-02 2.535376 1.3231915 0.3292608 0.78803748
#>   3: 2020-01-03 2.636790 1.5249620 0.4857825 0.85169700
#>   4: 2020-01-04 3.158113 1.1318521 0.1869724 0.24190772
#>   5: 2020-01-05 3.326954 1.0991870 0.2341736 0.09327451
#>  ---
#> 313: 2020-11-08 4.552528 0.8662639 0.8824743 0.22454327
#> 314: 2020-11-09 4.464356 0.8773634 0.8845554 0.19480862
#> 315: 2020-11-10 4.532254 0.8230178 0.7147899 0.38073588
#> 316: 2020-11-11 4.415192 0.7462676 0.8225977 0.32353235
#> 317: 2020-11-12 3.666675 0.3957351 0.6607121 0.19661800

This solution takes more time than the function you already use because it has 50 times more calculations than the chunck version. It also wasn't possible to use data.table::frollapply which AFAIK can only output a 1 dimensional vector.
Comment: Hi! Unfortunately, when I apply this to the GAM it doesn't work as hoped, the same for MARS model.
Comment: As in our previous discussions, each model comes with its constraints, and making sure that data fits within these constraints can be tedious. However, I see no fundamental reason for the above method not to work with other model types.


Books about Turing machines and undecidability

Question: I need help with finding literature about Turing machine and undecidability. First book I was suggested is Introduction to Automata Theory, Languages, and Computation by Hopcroft, Motwani and Ullman. I also found some notes (from different courses) about this topic online, but not books that have something specific about this.
Any suggestions?
Answer: Hopcroft is pretty much a standard book for Automata Theory and Formal Languages. It's pretty good.
Michael Sipser's Theory of Computation will be good for Automata Theory as well. It's a little easier than Hopcroft.
If you're dealing with Turing Machines, Undecidability, and NP generally, you  will find Computers and Intractability by Garey and Johnson useful as well.
Comment: Do any of these books has exercises possibly with answers?
Comment: Hopcroft and Sipser have exercises. Some solutions are available online. I think the same is true for Garey, but I'm not sure.
Answer: A short wonderful (cheap) exposition can be found in the Dover book "Computability and Unsolvability" by Martin Davis. http://www.amazon.com/Computability-Unsolvability-Prof-Martin-Davis/dp/0486614719
The previous book is a famous and classic one. Let me add one other tittle which I really like (it is a complementary one, it should not be used as a main book to understand these topics) and it is not so well-known: "Cornerstones of undecidability" by G. Rozenberg and A. Salomaa. http://www.amazon.com/Cornerstones-Undecidability-Prentice-International-Computer/dp/0132974258
Comment: Thank you so much. Great books as I can see and very specific about my topic =)


DropTarget ActionScript

Question: i have 8 movie Clips that i stored in an array. i put the movie clips on the stage and i can move them around so everything work fine until now. I made a grid where the mc's can be droped.I saved the grid parts in an array,too.
after that gave names to the mc's and to the grid parts like that:
mc.name= number.toString();
gridpart.name= number.toString();
the movie clips and the grid parts have the same name like: mc1.name=1 and gridpart1.name=1 and so on.
Now I made an if statement to check if the right mc was droped on the right grid part, like that:
if(mc.name==gridpart.name)
{
trace("correct position")
}

But nothing happens. I used "dropTarget", too like that:
 if(dropTarget.name==a.target.name)
{
 //code
}

I don't know what to try now. I thought to put this code in the callback function of the mouse.CLICK event handler because i want that the mc should not be moved anymore if it is on hir correct position.
I would be happy if you have a better solution for this problem.
I tried to describe my problem so that you can imagine what I am trying to say.
Sorry about my English, I am not a  native English speaker.
Thank you for your time
Comment: Can you add some more code to that. There can be a lot of things going wrong and can you trace mc.name to and grid.name so we know what part is going wrong?. Finally also try using e.currentTarget.name see if that works for you.
Answer: I think you wrong using dropTarget.name. Try dropTarget.parent.name. This why dropTarget is referred to content of the DisplayObject onto which you release your dragged MovieClip.
I hope this will be usefull to you!
Comment: i just used evt.target and it worked.
and i thing your solution is right

DropTarget ActionScript


IPv6 multicast with Node.js

Question: I am experimenting with IPv6 UDP multicast over a VPN.  I have tried the following code:
const dgram = require('dgram');

let sock = dgram.createSocket('udp6', {
  reuseAddr: true
});

sock.on('message', (data, source) => {
  console.log('on message', arguments);
});

sock.bind('36912', '2620:9b::1944:e598', () => {
  sock.addMembership('ff02::1:3', '2620:9b::1944:e598');
});

setInterval(() => {
  let buf = Buffer.from((new Date()).toString());
  sock.send(buf, 0, buf.length, 36912, 'ff02::1:3');
}, 500);

The script runs, and I see packets being sent/received with Wireshark, but neither end shows them in the console.

What am I doing wrong?  What's a way to send and receive basic multicast with IPv6?
Comment: There are flags and scopes for IPv6 multicast. The multicast group `FF02::1` is the Link-Local All Nodes Address. You could start with that. Beyond that, you should research the various scopes and flags. For instance the scopes are: 0 Reserved, 1 Interface-Local scope, 2 Link-Local scope, 3 Realm-Local scope, 4 Admin-Local scope, 5 Site-Local scope, 6  Unassigned, 7 Unassigned, 8 Organization-Local scope, 9  Unassigned, A  Unassigned, B  Unassigned, C  Unassigned, D Unassigned, E Global scope, F Reserved.
Comment: What exactly are you doing? The multicast group to which you are sending is a reserved multicast group for Link-Local Multicast Name Resolution ([RFC 4795](https://tools.ietf.org/html/rfc4795)). That multicast group will never be sent off the link on which it is originated.
Comment: @RonMaupin I only need to send multicast packets across the broadcast domain.  The VPN takes care of putting everything on the same broadcast domain, and this is indeed working.  I can see the multicast packets between machines over the VPN.  I tried switching to `ff02::2`, and that still didn't work.  What multicast address should I be using?
Comment: @RonMaupin Sorry, that was a typo.  I used `ff02::1`, and that did not work for me.  And, thanks for clarifying the scope.  I've been getting started by looking at this:  http://www.txv6tf.org/wp-content/uploads/2013/07/Martin-IPv6-Multicast-TM-v3.pdf  I suppose if `ff02::1` is a valid multicast address, then I have a code problem of some sort.
Comment: @RonMaupin Another note... if I use `ff02::1`, I do not receive packets from my remote host over the VPN.  If I use `ff02::1:3`, I do.  Could this be due to a quirk/bug of the VPN implementation?
Comment: I think it may be swallowed by the device on which the VPN is configured. You could try and address in any of the link-local variable scope allocation ranges: [IANA Multicast Address Space Registry](https://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xhtml).
Comment: @RonMaupin Thanks Ron.  I tried `ff12::1` and that doesn't work either.  Neither do any of the other scopes, `ff13::1`, `ff14::1`, etc.  I suppose the VPN software (Hamachi) is making an exception for `ff02:1:3`, but not allowing any other multicast?
Comment: You are changing the flags, and that is not a good idea, unless you really know what you are doing. Try something like `ff02::db8:0:1`.
Comment: Right, I was setting the temporary address flag, thinking that might have something to do with it, and then I tried the various scopes just to see if one would overcome the issue.  `ff02::db8:0:1` does not work.  A quick look in dmesg reveals a clue:  `[639610.928709] [UFW BLOCK] IN=eth0 OUT= MAC= SRC=2620:009b:0000:0000:0000:0000:1908:468c DST=ff02:0000:0000:0000:0000:0db8:0000:0001 LEN=87 TC=0 HOPLIMIT=1 FLOWLBL=0 PROTO=UDP SPT=36912 DPT=36912 LEN=47`  Firewall rules permit anything on the `ham0` interface (the VPN), but somehow this packet is getting stopped...
Comment: ... it looks like it's not bound to the correct interface.  It's using `eth0` for some reason.
Comment: for the add_membership, the 2nd address should be a link-local (fe80..) address on the desired interface for it to get the right interface#, but I don't see where you are trying to recv?
Comment: @lossleader Are you saying I should swap the parameter order I have for addMembership?  And, what is the proper code for receiving?  I had the bind in there, which I thought was enough.
Comment: @Brad, I am saying the 2nd address looks like the wrong type(global?) so the OS might not find the interface number from it and you should have (or create) a link local one to pass as addMembership's 2nd arg, but addMembership is just receive side. On the send side, there is no node wrapper around uv_udp_set_multicast_interface() so I think you have to fix that in an OS specific way.
Comment: @lossleader The second address, `2620:9b::1944:e598`, is the address of the interface on the VPN.  I'm using Hamachi.  Historically their address have been `22.214.171.124/8` and then they moved to `22.214.171.124/8`.  It has some link-local addresses as well.  You're saying I should use these for adding membership?  How about the bind?  On sending, it was my understanding that the previous `bind` and/or `addMembership` is what took care of setting the interface.  Is this not the case?
Comment: @Brad, w/v6 the 2nd position is an interface id, but node's wrapper/uv are hiding this difference by looking it up from an ip's sin6_scope_id which I think will be 0 and therefore your default interface (eth0) on any non-link-local ip.. so using any of its link local addresses will add receiving on that interface. The bind overrides source address selection (SAS) but interface selection is a higher level task that usually affects SAS, not the reverse. Multicast v6 interface selection is done explicitly with a different sock option node doesn't have a wrapper for, so your only option is via OS.
Comment: @lossleader Ok, ignoring my code above, is there any way at all to broadcast data across an IPv6 network and receive it with Node.js?  One machine sends to others, and the others receive it?  IPv4 had normal broadcast, and I'll go back to that if I have to.  But, I'd rather get IPv6 multicast working.  (Multicast is a better option overall, and IPv6 of course doesn't have broadcast support anyway.)  And, if this isn't possible with Node.js, could you post an answer citing code or some other reference?  I'll happily award you the bounty if you can prove what I need isn't possible.
Comment: @lossleader Even better if you could file a bug report for Node.js.  :-)  I think I'd throw another 250 on for that, or more if you wanted.
Comment: "_ignoring my code above, is there any way at all to broadcast data across an IPv6 network_" IPv6 doesn't even have a broadcast concept. You must use multicast. To eliminate the code problem, try it on a small test LAN with just two PCs and a switch using ethernet. If it works for that, then there is some sort of problem with the VPN or devices which are the VPN endpoints.
Comment: @RonMaupin Yes, I'm aware, hence my comment stating that IPv6 doesn't have broadcast which is why I need multicast to work.  I think I'll pick up an Raspberry Pi or something this weekend to experiment with.  Somehow over the years of migrating everything to cloud services, using VMs for development, and eliminating apartment clutter, I'm down to one actual PC.  :-)  It's a new era for my utility bill.
Comment: @Brad Hopefully using explicitly scoped addresses isn't a problem in your setup, since they seem to be how libuv has smoothed the differences in v4/v6.. I'm still looking into the situation of the missing wrapper, but ironically it impacts v4 since it has no scoped addresses for as a work around.
Answer: Scope id -> interface number
In IPv6, there is a concept of a scope_id of an address that is supposed to indicate a context for the IP address, and generally just means what interface it is reachable on. While scopes have OS specific names, each just translates to an interface number, with 0 usually meaning the system's default.
In IPv6 multicast, this scope_id is provided directly to IP_ADD_MEMBERSHIP and IP_MULTICAST_IF instead of providing an ip associated with the interface as IPv4 does.
wrapper smoothing of v6's differences
node (via libuv) hides this difference for you in addMembership by looking up the scope_id from the "interface address" you provide.
Unfortunately, starting from just an IP and getting a scope doesn't make a lot of sense (the whole point of the scope is that the IP could have different uses in different scopes.) So libuv is only able to fill in a scope if you explicitly provide it at the end of the address, using the %[scope] format.
Using Addresses with Explicit Scopes
The way around this seems to be:
 sock.bind('36912', '::', () => {
   sock.addMembership('ff02::1:3', '::%eth2');
 ...
 sock.send(buf, 0, buf.length, 36912, 'ff02::1:3%eth2');

Where:

using :: (or no address) in bind is necessary since you are combining receive which will filter the multicast address on this with send which needs a normal address.

using %[iface#] forces the scope of this interface #.

The second argument of addMembership could really start with any address since we are forcing the scope and the rest is discarded.

Usually the send socket is separated and given a different port or an anonymous port as you are either limited in what you can configure or in danger of getting EADDRINUSE errors for having sockets that are too similar.
Answer: I followed the steps in this answer but still couldn't get IPv6 multicast to work. It turned out I was setting socket.setMulticastLoopback(false) to filter out messages coming from the node itself, which worked well for IPv4, but was blocking all messages for IPv6. Removing this fixed the issue and messages started appearing correctly, with no need to filter.

IPv6 multicast with Node.js


Is it possible to synchronize the passwords of local intranet with cloud server?

Question: I would like to setup a Sharepoint 2010 solution on a cloud based Windows Server 2008 R2. Preferably I would like the ability to use a company's existing user accounts and passwords. Therefore my question is..
Is it possible to either:

Have the cloud solution join the domain controller of an existing network on a remote site with reasonable efficiency?
OR at a minimum I would like some way to synchronise user accounts and passwords - is there another solution to achieve this?
Answer: The currently recommended solutions, in the order I prefer:

Look into ADFS (Federation Services) to accomplish logons
Utilize a password sync tool to move passwords between sites.  Microsoft's ForeFront Identity Manager and it has this capability.  You can also utilize a Password Filter in Active Directory to capture password changes and then perform certain actions with them, such as pass them to a web service on your remote machine.
Setup a one-way read-only domain trust
Comment: Will solution number 1 still allow for a user to login to the sharepoint site using the AD credentials however still being external from the intranet?
Comment: Yep! It's a security token provider, commonly called STS. Essentially it helps with SSO based sign-on for any of your resources that you chose to implement it with.  The nice thing is that you never really sync the password to the remote server which improves security.  Instead when the user requests access to your cloud sharepoint site sharepoint will temporarily redirect them back to your servers to authentication and then will return a token that the sharepoint site knows to trust.  If you need a good example of how it all works check out Office 365, it heavily relies on ADFS for auth.


Save new revision of custom entity

Question: I created a custom entity in my module and I can edit and save it just like any other entity in core. I also want to save revisions for this entity but I couldn't find any help so far. I tried this (from node module) but it doesn't work:
$entity = $this->getEntity();
$entity->new_revision = true;
$entity->save();

I have the revisions tables declared in @ContentEntityType annotation, I have the revision_id field declared in baseFieldDefinitions() but I don't know how to actually save a new revision.
Answer: For Drupal 8 most intern values like the revision flag (newRevision) is protected, which means that you aren't allowed to set them directly. There is a good reason for this, as Drupal wants to do stuff in some cases when these values are set.
Instead you need to use the ::setNewRevision method on the entity. This will throw an exception if the entity doesn't support revisions. So if you don't know what entities you are dealing with, you could do something like this.
function save_new_revisions(EntityInterface $entities) {
  foreach ($entities as $entity) {
    if ($entity->getEntityType()->isRevisionable()) {
      $entity->setNewRevision();
    }
    $entity->save();
  }
}

Comment: I had to add `$entity->setNewRevision()` instead of `$entity->new_revision = true;`
Comment: Good answer. FYI, you might as well set a log message as well. For example: `$entity->setRevisionLogMessage('Transitioned by SendToPayroll service.');`
Comment: And maybe:    `$group->setRevisionTranslationAffected(TRUE); $group->setRevisionUser(User::load(\Drupal::currentUser()->id());` - note that i need the translation one or the revision didn't appear in the UI.

Save new revision of custom entity


How can I import non-unicode text file by Feeds module?

Question: My drupal version is : 7.5x
I want to import an csv or txt file that have non-unicode (iransystem) encoding.
After import this file to Drupal (persian character with iransystem encoding) my characters show correctly in my site. So these texts are imported successfully. But when I want to filter results of those fields by Views (exposed filter), I can not see any result by filtering views fields (search in fields by views exposed filter).
I want to import non-utf8 or unicode persian text files into Drupal and filter those fields by Views exposed filter (search on non-unicode characters).
For example I imported A Persian or arabian word into a field of Drupal. This passage shows correctly to me, but when I search type this passage in exposed A Persian or arabian word text in Drupal page and paste on search field of Drupal Views, I can see results correctly.
Comment: What is your actual **question**? Something that ends with a "?". Note that some moderators do not consider the question title as the actual question. Some maybe explicitely repeat the title in your question, eg at the bottom of it. Good luck!
Comment: i cant speak english correctly,so I am sory !  highlighted texts is as persian texts.i can not type persian characters in this website.
Comment: No need for sorry, don't worry. And your english is pretty well. Also know that my prior edit of your question (to remove some typos, etc) was just to help you improve your question. But **you** really need to add an actual question in the body of your question. If you don't, your question is at risk of being put on hold like "unclear what you're asking". By adding such question, you avoid that somebody answers to the wrong question. OK?
Answer: I can only provide high-level guidance here, but you need to use the Feeds Tamper module, which allows you to alter data between when it is read from the source, and then passed to Feeds.
However, I don't think there is an existing tamper plugin that can handle your situation; you will have to create your own.
There are two patches in the issue queue that may provide guidance:

https://www.drupal.org/node/1817516
https://www.drupal.org/node/2263119 (disclosure, I wrote this one)

You can take one of those two patches, and update them to use your character set instead of the ones in the patch.
For example, in this patch, you would need to update
+function feeds_tamper_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
+  $field = drupal_convert_to_utf8($field, 'ISO-8859-1');
+}

to use your encoding name instead of 'ISO-8859-1'.
Comment: thank you mpdonadio , My exported excel files have DOS Codepage (Iransystem Is a DOS codepage [link](https://en.wikipedia.org/wiki/Category:DOS_code_pages) For persian texts.My exported files show in my excel correctly , when I convert it to csv by notepad and import to drupal by feeds those text show correctly too BUT can not filter these character and search,when type persian characters can not see any results.DOS codepage is 8bit and Unicode codepage is 16bit.sorry I can not understand english very well.This patches can convert DOS Codepage to Unicode?!
Comment: This link [exported excel file](https://ufile.io/375261) is my file for import by feeds.this file show correctly in excel ,imported successfully to drupal by feeds_xls,show on my site correctly BUT I can not search on those characters (type and search by views exposed filter).please help me and import this file to your drupal site for test,create a views for those 2 fields and search by views on this.you must no have any results.please test this file.your test and check can help me and drupalers very much.thanks
Answer: My File is Unicode file.because it shows in microsoft excel and other programs correctly.But I think my file and my export is the Basic Problem.
So I delete those files and stop importing those to drupal.
thank you


Reconciling Wishart mean and Inverse-Wishart mean

Question: The Inverse-Wishart wikipedia article states that
$ X \sim \operatorname{Wish}^{-1}(\Psi,\nu)$ if $X^{-1} \sim \operatorname{Wish}(\Psi^{-1},\nu),$ where $\Psi$ and $X$ are $p\times p$.
The mean of the Inverse-Wishart is given as $\frac{\Psi}{\nu-p-1}$, but the mean of the Wishart is $\nu(\Psi^{-1})$ (See here).  Why don't these match up? Wouldn't the mean of the Inverse-Wishart be $\frac{\Psi}{\nu}$?
Is this just because of a difference in parameterizations?
Answer: Let's look at the simpler case of positive univariate random variables. I assume it's already clear that in general for a positive random variable whose variance is not $0$, that $\text{Cov}(X,1/X)< 0$. If you're happy to accept that as the case, then
$\text{Cov}(X,1/X) = E(X.1/X) - E(X)E(1/X) = 1-E(X)E(1/X) <0\,,$ so
$E(X) E(1/X) > 1\,,$ or
$E(1/X)>1/E(X)$
or you could just use Jensen's inequality to the same end.
(In fact we can show $1/E(X)<E(1/X)\leq 2/E(X)$, a rather neat little fact)
Generally we should not expect means to "match up" in the way you anticipated.


Simple Injector async life time scoping and security exception

Question: I have a AsyncCommandHandlerDecorator<TCommand> and LifetimeScopedCommandHandlerDecorator<TCommand> as shown below:
public class AsyncCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand> where TCommand : ICommand {

    private readonly Func<ICommandHandler<TCommand>> _factory;

    public AsyncCommandHandlerDecorator(Func<ICommandHandler<TCommand>> factory) {
        _factory = factory;
    }

    [SecurityCritical]
    // with or whitout SecurityCritical attribute, problem exists.
    public void Handle(TCommand command) {
        ThreadPool.QueueUserWorkItem(_ => {
            var handler = _factory();
            handler.Handle(command);
        });
    }
}

// AND

public class LifetimeScopedCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand> where TCommand : ICommand {

    private readonly Container _container;
    private readonly Func<ICommandHandler<TCommand>> _factory;

    public LifetimeScopedCommandHandlerDecorator(Container container,
        Func<ICommandHandler<TCommand>> factory) {
        _container = container;
        _factory = factory;
    }

    [SecurityCritical]
    // with or whitout SecurityCritical attribute, problem exists.
    public void Handle(TCommand command) {
        using (_container.BeginLifetimeScope()) {
            var handler = _factory();
            handler.Handle(command);
        }
    }
}

and I register decorators like this:
container.RegisterSingleDecorator(
    typeof(ICommandHandler<>),
    typeof(LifetimeScopedCommandHandlerDecorator<>),
    c => c.ImplementationType.Name.StartsWith("Async"));

container.RegisterSingleDecorator(
    typeof(ICommandHandler<>),
    typeof(AsyncCommandHandlerDecorator<>),
    c => c.ImplementationType.Name.StartsWith("Async"));

But, when the async process attempt to invoke, I get this error:

Attempt by security transparent method
  'LifetimeScopedCommandHandlerDecorator`1.Handle(!0)' to
  access security critical method
  'SimpleInjector.SimpleInjectorLifetimeScopeExtensions.BeginLifetimeScope(SimpleInjector.Container)'
  failed.

I tried to use SecurityCritical attribute on both LifetimeScopedCommandHandlerDecorator.Handle and AsyncCommandHandlerDecorator.Handle, but it didn't help. Have you any idea please?
UPDATE:
The exception is of type MethodAccessException and here is the complete stack trace:

at MYNAMESPACE.LifetimeScopedCommandHandlerDecorator`1.Handle(TCommand
  command)
at MYNAMESPACE.AsyncCommandHandlerDecorator`1.<>c_DisplayClass1.b_0(Object
  _)
   in C:\MYPROJECTPATH\AsyncCommandHandlerDecorator.cs:line 23

at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
  state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

UPDATE 2:
With or whitout SecurityCritical attribute, problem exists.
Comment: Can you supply the exception type and complete stack trace.
Comment: @Steven yes, I update the Q and put the exception type and complete stack trace. Thanks to your help.
Comment: Why do you need the `[SecurityCritical]` attributes? Doesn't the problem go away without them?
Comment: @Steven Nop. I put this attribute after I got the problem. I googled the error and found some articles that they told when a security transparent method is calling a security critical one, one of ways that can resolve the problem is making the security transparent method `SecurityCritical`. With or without them, no differences.
Comment: Here is one of articles I found: http://msdn.microsoft.com/en-us/library/bb264475.aspx
Comment: @Steven any result? any suggestion? I'm searching, but no result yet :( I saw the source at codeplex; But there is not `SecurityCritical` attribute on `BeginLifetimeScope`. So, why this error happens? Have you any idea?
Comment: Are you running in partial trust?
Comment: @Steven yes, I was running it in partial trust. But now, I run in full trust and problem resolved. I'm using MVC 4, .NET 4.5, Win 7, IIS Express 8, VS 2012. In full trust, there is no problem.
Answer: Finally, I found the answer (thanks to @Steven for his helps).
In my assembly, I have added [SecurityTransparent] for some reasons. In the other hand, Simple Injector uses the ThreadLocal<T> internally. And the ThreadLocal<T> is attributed by HostProtection(SecurityAction.LinkDemand) and in LinkDemand's comment, we can read:

The immediate caller is required to have been granted the specified permission. Do not use in the .NET framework 4. For full trust use System.Security.SecurityCriticalAttribute instead; for partial trust, use System.Security.Permissions.SecurityAction.Demand.

That means actually the ThreadLocal<T> class is a SecurityCritical object and we can not call a SecurityCritical method by a SecurityTransparent one.


Opa amigos, queria saber por que no código abaixo a resposta só sai certa se antes de escrever a palavra (santo) eu der um espaço. :/

Question: cidade = str(input('Digite o nome da sua cidade: ')).title()
p = cidade.find('Santo')
if p == True:
   print('A sua cidade começa com Santo.')
else:
   print('A sua cidade não começa com Santo.')

Answer: A necessidade do espaço adicionado ao inicio da entrada se dá por conta do mal uso do método str.find() e uma conversão de tipos desastrosa.
O método str.find() retorna um valor numérico inteiro(zero ou positivo) que é o índice da primeira aparição de substring, passado por parâmetro, dentro de uma string. Ou então retorna -1 caso a string não seja encontrada.
Portanto na linha:
p = cidade.find('Santo')

A variável p independente do substring 'Santo' estar ou não contido em cidade o resultado sempre será um objeto do tipo int.
A conversão equivocada acontece na linha:
if p == True:

Onde você compara p que é do tipo int com True que é uma das duas constantes lógicas.
Acontece que quando há uma comparação entre instancias de classes diferentes o interpretador primeiro tenta converter o segundo operando para o mesmo tipo do primeiro de forma que possa haver uma comparação. Mas ao converter True em int...
>>> print(int(True))
1

O resultado é 1 e que torna o seu código equivalente esse:
cidade = str(input('Digite o nome da sua cidade: ')).title()
p = cidade.find('Santo')
if p == 1: #substituindo a constante lógica True por sua conversão numérica.
   print('A sua cidade começa com Santo.')
else:
   print('A sua cidade não começa com Santo.')

Ou seja a comparação só será verdadeira se o substring 'Santo' aparecer no índice 1 da string. Lembrando que o índice do primeiro caractere de uma string é 0.
Para corrigir basta fazer com que o código compare corretamente a posição da substring 'Santo' e posição de interesse:
cidade = str(input('Digite o nome da sua cidade: ')).title()
p = cidade.find('Santo')
if p == 0: #Verifica se o substring 'Santo' aparece a partir da primeira letra.
   print('A sua cidade começa com Santo.')
else:
   print('A sua cidade não começa com Santo.')

Comment: obrigado pela explicação, esclareceu bastante minha dúvida!!!


Complex Analysis: Find all analytic functions such that $(f(\frac{1}{p}))^3=\frac{p+1}{p}$

Question: I've started the following problem but I'm stuck now.
Find all analytic functions $f:\mathbb{E}\to\mathbb{C}$ that satisfy
$(f(\frac{1}{p}))^3=\frac{p+1}{p}\qquad$ for all natural numbers $p$ and $\mathbb{E}$ being the unitdisk $\{z:|z|<1\}$.
My answer so far:
I've found the following functions that satisfy the condition:
$f_1(z)=(1+z)^\frac{1}{3},\quad f_2(z)=-(-1)^\frac{1}{3}(1+z)^\frac{1}{3},\quad f_3=(-1)^\frac{2}{3}(1+z)^\frac{1}{3}$.
But I fail to show how these functions are analytic on the unitdisk and how I would have to define them on the unitdisk. Also, do I have to prove there is no distinct $f_4$?
Comment: Are you sure that $f_2$ satisfies the conditions?
Comment: Oh I see I meant $z=1+z$ in both $f_2$ and $f_3.$ Thank you @Szeto !
Answer: $(f(\frac{1}{p}))^3=\frac{p+1}{p}$ is equivalent to  $f(\frac{1}{p})$ being either one of the three cube roots of $\frac{p+1}{p}$.
Note that there is an analytic cube root of $1+z$ when $z\in \Bbb E$ because there is an analytic logarithm defined on $1+\Bbb E$: indeed, $1+\Bbb E$ does not contain $0$ or a loop that goes around it. You can then freely define $$f_1(z)=e^{\frac13 \log(1+z)}$$
with $\log(1+z)=\sum_{n=1}^\infty \frac{(-1)^{n-1}}{n}z^n$ being analytic on $\Bbb E$.
Now as was said in the beginning and pointed out by Martin R, there are three cube roots of any non-zero complex number, which yields two other solutions $$f_2(z)=e^{\frac{2i\pi}{3}}f_1(z)\qquad\text{and}\qquad f_3(z)=e^{\frac{4i\pi}{3}}f_1(z).$$

Proof that these are the only three solutions.
We know that for each $z=\frac 1p$, $f(z)$ coincides with either $f_1(z)$, $f_2(z)$ or $f_3(z)$. Why couldn't it be a different $f_i$ for each $p$? Because by the pigeonhole principle, there is at least one $f_i$ that coincides with $f$ on infinitely many $\frac 1p$'s, therefore on a set with a limit point, and you are done by analytic continuation.

See On the Power Series for $\log(1+z)$, published in the Annals of Mathematics in 1916!
Comment: *"$f$ coincides with the map $f_1$"* – not necessarily. $f^3$  coincides with $f_1^3$, so $f$ can be $f_1$ or $f_2 = e^{2\pi i/3} f_1$ or $f_3 = e^{4\pi i/3} f_1$.
Comment: @MartinR Ah, true! Thanks.
Comment: @MartinR I edited, hope it's all complete now.
Comment: @ArnaudMortier Thanks for the help!
Comment: @Pipster You're welcome!


Correct Database settings for pushing a Drupal site live

Question: I have a Drupal 7 site.
I have it working fine on localhost and my own test domain, with individual settings folders setup such as:
sites/localhost
sites/test.mydomain.co.uk
I am now putting it up onto a site where there is no domain set, but I can access it by visiting:
sitename.org/folder1/folder2
i have duplicate settings files in;
sites/folder1.folder2
sites/www.upcomingfinaldomainname.com
Have I got these right?
I keep getting the message:
PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in db_table_exists()
I'm using the user and pass I have been provided, and the correct db names. I have also set host as localhost and removed the port number.
Any suggestions?
Comment: Does the MySQL server work well for other sites?
Comment: Yes, no problems.
Comment: I think you need to enable PDO Extension, ask the hosting provider to enable it
Answer: If your connection parameters were incorrect, you would get a different error from MySQL.
I have seen connection problems on Drupal systems for a few different reasons.

Overloaded server
Low timeout values on a busy server
Low value for max_allowed_packet (this normally is a 2006 or 2020, though, in my experience).

Assuming other sites work, then the first two likely aren't the problem.  I would check your max_allowed_packet and see if that helps matters.  I typically use 32M; large values can help with restoring backups.
Answer: Looks like a database hosts misconfiguration. Check out the  /etc/hosts.allow and set mysqld: ALL. Also, check if it's blacklisted in /etc/hosts.deny.
Also, check if the database server port and host are set correctly. If running on the same server, they should be 127.0.0.1 and port is 3306 (default).


Propriedade e Objeto JavaScript

Question: Porque ele não consegue ler a propriedade?

objetoSelecionado = document.selectForm.variosDias;
<form name="selectForm">
    <select name="variosDias" multiple>
        <option value="Domingo">Domingo</option>
        <option value="Segunda">Segunda-feira</option>
        <option value="Terça">Terça-feira</option>
        <option value="Quarta">Quarta-feira</option>
        <option value="Quinta">Quinta-feira</option>
        <option value="Sexta">Sexta-feira</option>
        <option value="Sábado">Sábado</option>
    </select>
    <input type="button" value="Enviar" onclick="">
</form>

Aparece o erro:

Uncaught TypeError: Cannot read property 'variosDias' of undefined
Comment: O que você quer ler exatamente? o valor selecionado ou o DOM?
Comment: o DOM, eu queria saber onde está o Erro
Comment: Que erro está aparecendo pra você? Aqui está funcionando normalmente...
Comment: Uncaught TypeError: Cannot read property 'variosDias' of undefined
Comment: Vou criar uma resposta com um exemplo pra você ver como tá funcionando.
Answer: Você está no caminho certo! Quando você seleciona dessa forma: document.selectForm.variosDia você está selecionando apenas o elemento HTML, se quer acessar o valor dele, deve colocar document.selectForm.variosDia.value. Lembrando que o algo deve estar selecionado para exibir, se não, retornará um valor vazio ;)
Este Codepen pode te ajudar a entender melhor!
Answer: O exemplo está funcionando:

objetoSelecionado = document.selectForm.variosDias;

console.log(objetoSelecionado)

objetoSelecionado.remove()
<form name="selectForm">
    <select name="variosDias" multiple>
        <option value="Domingo">Domingo</option>
        <option value="Segunda">Segunda-feira</option>
        <option value="Terça">Terça-feira</option>
        <option value="Quarta">Quarta-feira</option>
        <option value="Quinta">Quinta-feira</option>
        <option value="Sexta">Sexta-feira</option>
        <option value="Sábado">Sábado</option>
    </select>
    <input type="button" value="Enviar" onclick="">
</form>

Verifique se o seu código completo não possui elementos com o mesmo name, ou se os names estão escritos corretamente.
Answer: Resolvido! coloquei o código JavaScript, logo após o formulário, e não apareceu mais erro. Obrigado para todos!

<form name="selectForm">
    <select name="variosDias" multiple>
        <option value="Domingo">Domingo</option>
        <option value="Segunda">Segunda-feira</option>
        <option value="Terça">Terça-feira</option>
        <option value="Quarta">Quarta-feira</option>
        <option value="Quinta">Quinta-feira</option>
        <option value="Sexta">Sexta-feira</option>
        <option value="Sábado">Sábado</option>
     </select>
</form>

Propriedade e Objeto JavaScript


Custom conditional cart item prices in WooCommerce

Question: I am having a problem here, that I have been trying to solve for weeks now. Tried everything I could find on the internet.
To cut it short it is a system of ordering helpers(for cleaning), I use woocommerce + woocommerce bookings + woocommerce vendors.
Basically I need to add cleaning equipment to the cart manually and then I need cart items (helpers) price to be multiplied by service time (except cleaning equipment). But whenever there is cleaning equipment in the cart, the price of other items (helpers) is being multiplied 2x service time.
I don't understand what is wrong, when the cleaning equipment is not in the cart everything is fine. It doesn't matter how many other items(helpers) are in the cart it always multiplies service time by 2.
<code>    // Add equipment to the cart

add_action( 'woocommerce_before_calculate_totals', 'add_equipment_to_cart', 10 );

function add_equipment_to_cart() {
    $product_id = 650; // id=650 - cleaning equipment id

    // check whether radio 'Do you have equipment?' is checked to 'Yes' or 'No'
    if($_POST['equipment'] == 'No') {
        foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];

            // check whether equipment is already in the cart
            if( $values['data']->id == $product_id ) {
                $equipment = $product_id;
            }
        }
        // add it to cart only if it is not there
        if(empty($equipment)){
            WC()->cart->add_to_cart( $product_id );
        }
    } elseif($_POST['equipment'] == 'Yes'){
        foreach( WC()->cart->get_cart() as $cart_item_key2 => $values2 ) {
            $_product2 = $values2['data'];
                if($values2['data']->id == $product_id ){
                   WC()->cart->remove_cart_item($cart_item_key2);
                }
        }
    }
}

    // Change price of items in the cart

 add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 1 );

function add_custom_item_price( $cart_object ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item_id = $cart_item['data']->get_id();
        if($item_id != 650) { // 650 - cleaning equipment id

                // product original price
                $original_price = $cart_item['data']->get_price();

                // comes from an input
                $servicetime = $_POST['servicetime'];

                $new_price = $original_price * $servicetime;

                // set the new item price in cart
                $cart_item['data']->set_price($new_price);

        }

    }

}
</code>
Any kind of help would be appreciated!
Answer: For price changes in cart, you need to make your price calculation before (Once data has been submitted on add to cart event) and set that custom price calculation in cart item as custom data, to avoid problems and errors:
<code>// Save custom field value in cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_field_in_cart_object', 30, 3 );
function save_custom_field_in_cart_object( $cart_item_data, $product_id, $variation_id ) {
    // Get the correct Id to be used (compatible with product variations)
    $the_id = $variation_id > 0 ? $variation_id : $product_id;

    if( isset( $_POST['servicetime'] ) ){
        $product = wc_get_product( $the_id ); // Get the WC_Product object
        $product_price = (float) $product->get_price(); // Get the product price
        $service_time = (float) sanitize_text_field( $_POST['servicetime'] ); // Get service time
        // Set the price calculation as custom data in cart item
        $cart_item_data['custom_price'] = $product_price * $service_time;
    }
    return $cart_item_data;
}

// Change price of items in the cart
add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 1 );
function add_custom_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        // ID 650 is the cleaning equipment id
        if( $cart_item['data']->get_id() != 650 && isset( $cart_item['custom_price'] ) ) {
            // Get the calculated custom price
            $new_price = (float) $cart_item['custom_price'];
            // set the new item price in cart
            $cart_item['data']->set_price( $new_price );
        }
    }
}
</code>
Code goes in function.php file of your active child theme (or theme). It should work now…
Comment: Thank you very much for your answer, it works, but this solution is not suitable for me, because I have cart, checkout and product archive in one page and there should be the possibility to change service time after adding item (helper) to the cart and therefore the price has to be changed.
Comment: @James So in this case that is not going to work anyway as you can't do calculations on `woocommerce_before_calculate_totals` because you will always get wrong prices as a post need to be saved somewhere and additionally this hook is fired multiple times on one trigger. So you should better use jquery / ajax and rethink it all differently.
Comment: after adding your code, there is still one problem (had it before, but thought it will solve itself, when the multiplication is solved) after the purchase subtotal price is correct, but the total is 2x subtotal (for example: subtotal - 43, total - 86) maybe you have an idea why this is happening? thanks in advance!
Comment: @James I don't got this problem… it works perfectly for me


Tomcat Server wont load the Webpage

Question: Im trying to deploy my WebApplication on a TomCat 9.0.11.
Now everything went good so far, the artifact was deployed into the ROOT directory, but the page just wont load, and doesnt shows up my index.html? Does anybody see the error here? If i forgot something please tell me so i can add the missing stuff.
EDIT: I want to run the server on Windows first, later on Debian. The website should also be accesibile trough example.com not f.e. example.com/app (or for Windows localhost not localhost/app)
TomcatConfiguration1
TomcatConfiguration2
Artifacts
ServerLog
TomcatServer after deployment
Trying to open the page
Greets
Lukas
Comment: Possible duplicate of [Deploying just HTML, CSS webpage to Tomcat](https://stackoverflow.com/questions/3954621/deploying-just-html-css-webpage-to-tomcat)
Answer: i think project should be inside the webapp folder not inside root .Please attach log which can show us the context loading .
Or you can refer to this link:
Deploying just HTML, CSS webpage to Tomcat
Comment: Where can i find the log which shows the context loading?

Tomcat Server wont load the Webpage


Removing a float from a string by php and regex

Question: I have a code written in PAWN for SA-MP,
I sorted this code by several preg_replace calls with PHP and this is the semi-final code.
Final step is to remove the third parameter (They're Z-coordinates) with preg_replace which is float. like this:
SILLY4 = GangZoneCreate(-2178.69, -599.884, -0.00012207, -1794.92, -324.114);

to
SILLY4 = GangZoneCreate(-2178.69, -599.884, -1794.92, -324.114);

Comment: They're __all__ floats.
Comment: Why do you want to remove the third?
Comment: Convert your floats to strings and then use regex (string)$var, BUT What is the senese of it?
Comment: This is for SA-MP. This are the gang zones for my server. i replaced several times from the info.zon (orginal GTA: SA zone info) https://eval.in/137830 the semi-final code is here : https://eval.in/137827 and i want just x, y coords . third param is z and i not need it.
Answer: This regex should do what you want: it removes the third parameter in the code.
$result = preg_replace('/(?m)^([^=]+= GangZoneCreate\(([^,]+,){2})(?2)((?2)[^)]+\);)$/', '\1\3', $subject);

Comment: @iFarbod Thanks for sending your whole string. I changed the regex. It matches everything. Assign your whole big string to $subject, run the regex. Your cleaned up string will be in $result.
Comment: @iFarbod No problem, fixed now. The expression matching the string name was too complex. Fixed it. Please see https://eval.in/137834
Comment: with your last code , i got this : https://eval.in/137833 but some lines are some unreplaced texts : like line 121


Using pyVmomi with Django

Question: i'm trying to use pyVmomi with Django, is there any way (if there is, what is the most recommended way) to pass the serviceInstance between views?
Thanks.
Comment: tried using sessions, but the serviceInstance object is "not pickable". also tried to see if i can just save the session key and then create a new instance and import the key to it (instead of creating a new session) but that didnt work either.
Answer: According to Shawn Hartsock (the current VMWare employee maintaing pyVmomi) you cant connect with out a login but between that sample and this sample it should show how to use the same session which you said you were not able to do.

Using pyVmomi with Django


Execute search/replace in PhpStorm as action

Question: I'm looking for a solution to:

store favorite "Find Occurrences of ..." and
execute them without any more questions by the UI in one stroke

I know the option ALT + 3 -> STRG + E to open the last Find Usages, but that are only "Find" and not "Replace in Path" actions
Maybe I need to develop a plugin - that could look like this:
DO REPLACEMENTS:
----------------------------------
[X] foo -> bar
[ ] bar -> foo
[X] ): boolean -> ): bool
----------------------------------
[add] [execute] [execute & review]
----------------------------------

but any other ideas are welcome!
Important is to use PhpStorm`s file scopes! Because I would like to use my own custom scope.
Comment: There are no such functionality. You can try recording a macro though... (but it's unlikely to do what you want -- you cannot check what steps to run and when to stop). Otherwise -- code your own plugin -- the best and most flexible way from any POV.
Comment: Macros dont work (macros *never* works! if i try something with macros :-) )
Answer: You can use "Structural Search Inspection". It's base on the "Structural Search and Replace" engine which is pretty powerful. Once configured you can run the inspection using the "Run Inspection by Name..." action with a custom scope. It has a quick fix which can be used to replace occurrences.
Comment: That seems to be the Answer, but i dont get it work with what ive tried: class $class$ {
    public function $method$(): $returnType$ {
}
Comment: ...and can i get quick access to my saved searches by a toolwindow or keyboard shortcut or macro?
Comment: You can assign a shortcut on the "Search Structurally..." action, it doesn't have it by default. But I'd still recommend configuring "Structural Search Inspection" which runs a search automatically. Back to a search query you've mentioned. What are you trying to achieve? What would you like to find?
Comment: my goal is to define some preferences of search/replacement code templates to fix all my code style problems before the code sniffer tells me these errors ;-) ... as simple as possible. with a short-cut ..... I don't know how suitable code-templates are for this idea.
Comment: Nice Tip with "Structural Search Inspection" - Thanks - but i have trouble to learn how to use these templates...
Comment: See: https://stackoverflow.com/questions/46506157/intellij-structural-search-in-php-to-find-specific-return-types


Center larger div to smaller div?

Question: I would like to know how I can align two divs.
The first div is smaller than the second one and I want to center the second one to the first one (like if you would do in Photoshop where the focal point of an object gets aligned to the focal point of the other object so that they are on one level)
Just a quick sketch

I hope you understand what I mean :D
Thanks in advance
Comment: Can you show us what you have tried?
Comment: http://www.vanseodesign.com/css/vertical-centering/  That has a lot of methods.  Check them out.
Answer: If you're using display:inline-block (as opposed to float:left), then you can use vertical-align:middle to vertically align the two elements by their middle line.
Comment: @Derek朕會功夫 That is unsustainable, especially if the elements change size for any reason.
Comment: I am just mentioning in case `inline-block` isn't supported (which shouldn't happen).
Comment: I thought vertical-align only worked when the element is display:table-cell and the parent is display:table  (or they actually are, in fact, tables.)
Comment: `vertical-align` works on all elements, it just doesn't seem to have any effect most of the time. It has a noticeable effect on inline and inline-block elements that have a different height from the rest of the line.

Center larger div to smaller div?


How is it true that all linear combinations of 2 distinct eigenvectors of a Hermetian operator share the same eigenvalue?

Question: Given a Hermitian operator $L$ and 2 distinct eigenvectors $\lambda_1$ and $\lambda_2$ with the same eigenvalue $\lambda$ (confusing to use $\lambda$ for both but that's what the book does), why is the following statement obvious, or even true?

It should be clear that any linear combination of the two eigenvectors is also an eigenvector with the same eigenvalue.

It's clear to me that the linear combination $\lambda_1+\lambda_2$ would have the same eigenvalue of $\lambda$ because they must be orthogonal. But for example wouldn't the linear combination $2\lambda_1+3\lambda_2$ have a different eigenvalue?
I'm kind of learning linear algebra on the fly so I may be misreading the statement altogether. I'm trying to break things down into components but still not seeing how the above statement is true.
Comment: They're fixing an eigenvalue and saying that all eigenvectors corresponding to that fixed eigenvalue forms a subspace.
Comment: I realized later that I was imagining the vectors (geometrically) incorrectly. I was thinking, how can the coefficients not add to the relative length of the vector and thus need a different eigenvalue. But the eigenvalue is relative to the larger vector to begin with. Novice mistake.
Comment: I'm not sure how the length of a vector comes in? Eigenvector corresponding to two different eigenvalues don't add to give you a third eigenvector corresponding to another eigenvalue. Keep in mind the identity map, where the whole space corresponds to the eigenvalue 1.
Answer: Let $A$ be an linear mapping and $x_1,x_2,\cdots, x_n$ be its eigenvectors with the same eigenvalue $\lambda$. Let $c_1,c_2,\cdots,c_n$ be scalars and put $x=\Sigma c_ix_i$. Then $Ax=\Sigma Ac_ix_i=\Sigma c_iAx_i=\Sigma c_i\lambda x_i=\lambda\Sigma c_ix_i=\lambda x$.


Select records from a table only where a field value is repeated less than x times

Question: I am very new to SQL and I would appreciate it if you could help me. I have a table that has a field with many IDs and that field is in number format. The same ID may repeat different number of times, e.g. 5 times, 6 times. I want to display records of all fields only when the same ID is repeated less than x times in this field. Which sql statement will get this done?
Thanks in advance.
Answer: Try this:
SELECT T1.* FROM TableName T1
INNER JOIN
(SELECT ID,COUNT(ID) as Count
FROM TableName
GROUP BY ID
HAVING COUNT(ID) < 5) T2 ON T1.ID=T2.ID

EDIT:
Try your query using alias names:
SELECT APropertyID,BPropertyID,Ayy,Byy from
(SELECT a.PropertyID as APropertyID, b.PropertyID as BPropertyID, a.yy as Ayy,b.yy  as Byy
FROM tableA a full outer join
     tableB b on a.PropertyID=b.PropertyID ) a1
inner join
(SELECT PropertyID,COUNT(PropertyID) as Count
FROM tableA
GROUP BY PropertyID
HAVING COUNT(PropertyID) < 5) c
on a1.APropertyID=c.PropertyID

Comment: @BoratSagdiyev: I agree with that, my friend. That was my first answer though. Your query will get only the `id`s. But OP is asking for **all fields** in the table. That is why I used a join.
Comment: Yakshemash ! I am not sure why you used a `JOIN`. This works for me `select id, COUNT(id) as cnt
from TableName
group by id
having COUNT(id) < 3` Am I missing something ? Chenqui.
Comment: Thanks Raging Bull,
my case is a bit more complicate where i already have a joint table like below so when i combine it like you suggested i cannot seem to get it right. may i have your help on what went wrong here?

SELECT * from (SELECT a.PropertyID, b.PropertyID, a.yy,b.yy
FROM tableA a
full outer join tableB b on a.PropertyID=b.PropertyID
 )  a1

inner join (SELECT PropertyID,COUNT(PropertyID) as Count
FROM tableA
GROUP BY PropertyID
HAVING COUNT(PropertyID) < 5) c
on a1.PropertyID=c.PropertyID
Answer: SQL Server allows for an OVER Clause in aggregates (which is a useful but "nonstandard" SQL feature) that is handy in cases like this.

Determines the partitioning and ordering of a rowset before the associated window function is applied. That is, the OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.

Example:
SELECT cts.*
FROM (
    -- Build intermediate result where each record also has
    -- a count of how many times that value appears.
    SELECT
        t.*,
        COUNT (1) OVER (PARTITION BY value) as valueCount
    FROM t
) as cts
-- Filter intermediate result based on collected count.
WHERE cts.valueCount < 5

(I've used value instead of ID above - the same approach holds.)
Answer: SELECT *
FROM MyTable
WHERE ID IN
  (SELECT ID
  FROM MyTable
  GROUP BY ID
  HAVING COUNT(1) < 5)

Comment: Yakshemash ! I am not sure why you used a `JOIN`. This works for me `select id, COUNT(id) as cnt
from TableName
group by id
having COUNT(id) < 3` Am I missing something ? Chenqui.
Comment: I didn't use a join?  This is the simplest way to do what was wanted: "the purpose is to display records of all fields "
Comment: oops...just copy pasted my above comment without editing. my mistake.


Quadratic with missing Linear Coefficient

Question:
Let $x^2-mx+24$ be a quadratic with roots $x_1$ and $x_2$. If $x_1$ and $x_2$ are integers, how many different values of $m$ are possible?

I'm assuming we can use Vieta's Formula.
We can say $x_1+x_2=m,$ and $x_1\cdot x_2=24.$
$16$ values satisfy both of these conditions, so I think our solution would be $\boxed{16}.$ Did I go wrong somewhere in my process, or am I correct? Thank you in advance.
Answer: You are on the right track, but consider that the pairs $(3/8)$ and $(8/3)$ , for example, give the same sum. Now, you should be able to solve the problem.
Comment: In that case, we halve the solutions.
Comment: Exactly, you got it. It is also not difficult to write all pairs out and approve this result.
Comment: Thanks for the help. I understand now! :)
Answer: $$24=2^33$$
So, the number of positive factors are $$(1+1)(3+1)$$ which will just be doubled if we permit negative factors
See also : https://en.m.wikipedia.org/wiki/Divisor_function
Comment: Does that double-count $(3,8)$ and $(8,3)$
Comment: @OscarLanzi,  $$(1,24);(2,12);(3:8):(4,6)$$  So, the maximum number of possible combinations could be $$\dfrac82$$


Expand $\cos^a x$ in terms of $\cos kx$, $\sin mx$

Question:
If $a\geq 0$, expand $\cos^a x$  in terms of $\cos kx$, $\sin mx$

$$\cos^a x=\left(\frac{e^{ix}+e^{-ix}}2\right)^a$$
Since $a$ is a non negative real number, so by General Binomial theorem
$$\cos^a x=\frac1{2^a}\sum_{k=0}^\infty\binom ake^{ikx}e^{-i(a-k)x}$$
where $\binom ak=a(a-1)(a-2)...(a-k+1)$
$$\cos^a x=\frac1{2^a}\sum_{k=0}^\infty\binom ake^{i(2k-a)x}$$
Any help would be appreciated.
Comment: @KevinDietrich $a\geq 0$ and $a\in \mathbb{R}$
Comment: It seems that once you substitute $e^{i(2k-a)x} = \cos(2k-a)x + i\sin(2k-a)x$ into the final expression then you are done. Is this form not sufficient for you?
Comment: @duelspace Thanks. Please explain a bit and write as an answer.
Comment: @duelspace: [It's $e^{i(2k-a)x} = \cos((2k-a)x) + i\sin((2k-a)x)$ and not $e^{i(2k-a)x} = \cos(2k-a)x + i\sin(2k-a)x$](https://www.wolframalpha.com/input?i=exp%28%282+*+k+-+a%29+*+x+*+i%29) 'cause euler's formula...
Comment: What is $a$? $a \in \mathbb{N}$ or $a \in \mathbb{Z}$ or $a \in \mathbb{R}$ or $a \in \mathbb{C}$ or ...
Answer: The question seemingly asks for the Fourier expansion of $\cos^a x$ for $|x|\leqslant\pi/2$ (that is, of $|\cos x|^a$ for $x\in\mathbb{R}$): $$|\cos x|^a=\sum_{n=0}^\infty c_n\cos 2nx,$$ the coefficients of which can be computed using the formula $$\int_{-\pi/2}^{\pi/2}\cos^a x\cos bx\,dx=\frac\pi{2^a}\frac{\Gamma(a+1)}{\Gamma\left(\frac{a+b}2+1\right)\Gamma\left(\frac{a-b}2+1\right)}$$ seen here and in the linked questions. The result is $$c_0=\frac1{\sqrt\pi}\frac{\Gamma\left(\frac{a+1}2\right)}{\Gamma\left(\frac{a}2+1\right)},\quad c_n=2c_0\frac{\prod_{k=0}^{n-1}(a-2k)}{\prod_{k=1}^n(a+2k)}.\quad(n>0)$$
Obviously, if $a$ is an even integer, the series is finite.
Comment: Is your $a$ any non negative real?
Comment: @Max: yes (in fact we can even allow $a\in\mathbb{C}$ with $\Re a>-1$).
Comment: Thank you so much. I accept your answer.
Comment: I have removed .


How do I get each column of the same row in one line?

Question: I have this columns in excel:
A       B   C   D   E   F
Nima1   1   2   3   4   5
Nima2   6   7   8   9   10
Nima3   11  12  13  14  15
Nima4   16  17  18  19  20

and I want to show them like this:
Nima1   1
Nima1   2
Nima1   3
Nima1   4
Nima1   5
Nima2   6
…
Nima4   20

and so far I come up with nothing, every formula that I write doesn't work.
please if anyone knows how to do it, guide me through it.
Comment: In general, showing what you have tried (working or not) helps understand parts of the problem that you failed to include in your narrative.
Answer: In any unused cell to the right put in this formula,
'for system that use a comma as a list separator
=INDEX(A:E,(ROW(1:1)-1)/5+1,IF(COLUMN(A:A)=1,1,MOD(ROW(1:1)-1,5)+1))
'for system that use a semi-colon as a list separator
=INDEX(A:E;(ROW(1:1)-1)/5+1;IF(COLUMN(A:A)=1;1;MOD(ROW(1:1)-1;5)+1))

Fill right one column then fill both down until you get zeroes.
Comment: I put your formula in the same cell but it keep showing me this error:the formula that you type contains an error.
Comment: I've added the same formula for systems that use a semi-colon as a list separator.


Vector operations.

Question: At 12:00 pm, a spaceship is at position [3,2,4]km away from the origin with respect to some 3 dimensional co ordinate system. The ship is travelling with velocity [-1,2,-3]km/h What is the location of the spaceship after 2 hours have passed?
Comment: Hi and welcome to math.SE. You're more likely to be well received if you show us your efforts and attempts, instead of merely stating your question.
Comment: Next time, I'll do that. Thanks for the suggestion.
Answer: Initial position: $$[3,2,4]$$
Velocity: $$[-1,2,-3]$$
So, in $2$ hours, it travels $-2,4$ and $-6$ kms resp. in $3-D$ co-ordinate system.
It's final position becomes: $$[3-2,2+4,4-6]=[1,6,-2]$$
Comment: Thank you so much for your answer. i was thinking too much and using vector projections to do it. You've been helpful. Thanks, again.
Answer: Hint: Use the definition of velocity in a constant velocity movement$$\vec v={\vec x_2-\vec x_1\over t_2-t_1}$$

Vector operations.


export 'default' (imported as 'Vue') was not found in 'vue' in Vue 3 and Laravel

Question: I am going to create a Laravel 8 + Vue JS 3 hybrid project.I have already setup everything, but when I npm run watch, there is an error like the one below. I have tried various ways to look at some forums but still error. Can anyone help me?

WARNING in ./resources/js/components/index.js 6:2-15
export 'default' (imported as 'Vue') was not found in 'vue' (possible exports: BaseTransition, Comment, Fragment, KeepAlive, Static, Suspense, Teleport, Text, Transition, TransitionGroup, callWithAsyncErrorHandling, callWithErrorHandling, camelize,....

./js/components/ExampleComponent.vue
<template>

Test

</template>

./js/components/index.js
import Vue from 'vue';
import Card from './Card';
import Button from './Button';

// Components global.
[
  Card,
  Button,
].forEach(Component => {
  Vue.component(Component.name, Component)
})

./js/app.js
require('./bootstrap');

window.Vue = require('vue');
import './components';

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

const app = new Vue({
    el: '#app'
});

webpack.mix.js
const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js').vue()
   .sass('resources/sass/app.scss', 'public/css');

   if(!mix.inProduction()) {
      mix.sourceMaps();
      mix.webpackConfig({ devtool: 'source-map'})
      .options({
         processCssUrls: false
      });
   }

Comment: Does this answer your question? ["export 'default' (imported as 'Vue') was not found in 'vue'](https://stackoverflow.com/questions/63768491/export-default-imported-as-vue-was-not-found-in-vue)
Comment: Check this tutorial for Vue v3 setup without vue-cli: https://frontendguruji.com/blog/how-to-setup-a-vue-js-project-from-scratch-without-vue-cli/
Answer: Your code should be like :
./js/app.js
require('./bootstrap');
import { createApp } from 'vue';

import components from  './components';
import ExampleComponent from './components/ExampleComponent.vue'

let app=createApp(ExampleComponent)
app.use(components)

app.mount("#app")

./js/components/index.js
this is a plugin that register the components globally

import Card from './Card';
import Button from './Button';

// Components global.

export default {
  install: (app, options) => {
    [
  Card,
  Button,
].forEach(Component => {
  app.component(Component.name, Component)
})
  }
}