Converting a content type into a Profile2 profile

Question: I'm working on a site that's a user-contributed directory of local businesses. Each business that registers gets a user account.
I've thus far built the entire site using "Place" as a content type. However, in order to get users to contribute their listing as soon as they register (And to let the user easily edit that node), using Profile2 might make sense.
So, either one of two questions:
a. Is there any way of easily exporting a Drupal content type into something importable into Profile2?
b. Is there a way to get users to create a node just after or as they're signing up?
Thanks!
Answer: To your first question, create a view of the required information and using the Views Data Export module you can export it to a csv file.
Then you can import the information to users and profiles using the User Import module.
To your second question, Rules will do it for them. Create a new rule executed on the event 'After Saving New Account' with the action of 'Create an Entity' and define the node you want created, using the new user as author.
Answer: An easy way to have users create a node on signup is to use Logintoboggan:
Create a new user Role called pre-auth and give it limited permissions. For example allow that role to create a particular content type. (To avoid spambots I would leave that content type set as unpublished.)
Then simply set Logintoboggan to allow login on registration, and redirect the user to node/add/your-content-type.
There is some self-explanatory configuration of the Non-authenticated role, the Welcome and Account activation email templates which are required; as Logintoboggan overrides the default account activation workflow.


relationship between normal and log-normal distribution

Question: In wikipedia it is stated that:

If $X \sim \operatorname{Log-\mathcal{N}}(\mu, \sigma^2)$ is distributed  log-normally, then $\ln(X) \sim \mathcal{N}(\mu, \sigma^2)$ is a normal random variable.

Is the converse true?
Answer: Yep, if $X$ is normal, then $\exp(X)$ is log-normal.
Answer: More on X being normal while Y=exp(X) being log-normal:
Comment: I would clean up all references to $Ln$  to $\ln$.


How do I import CSS just for some classes or ids?

Question: Say, I have this HTML structure:

Header

Body

Footer

And an external CSS file (/styles.css), which contains
#header{
    color:red;
}
#footer{
    color:red;
}

Now with the help of javascript I can easily load the whole CSS, so as the text color of #header and #footer becomes red.
Using javascript, is it possible to load only styles which refer to #header and filter out any other styles in my stylesheet (styles for #footer in my case)?
Comment: Do you mean remove them for the sake of browser performance or server optimization? Either way there's going to be processing, difference is one can't be done.
Comment: @Bryan No, I just don't want this stylesheet to apply to anything except #header.
Answer: This can be done by directly modifying the CSS rules being applied to the current document.

JSFiddle demo (tested on Chrome): https://jsfiddle.net/ud5svdky/1/
Comment: Ohwait... I have no idea what's doing yet, but it appears to work :D
Comment: @nicael Glad to hear that. CSS rule modifications are a bit complicated in general.
Comment: I gonna test in real life :)
Comment: Nice! Is there any risk of FOUC issues, though? Can I be sure that the browser won't apply the original stylesheet first, then only re-display the page after I modify it?
Comment: @Kos It depends on where it's placed. When at the beginning of the body element or end of the head element, there shouldn't be issues with synchronously loaded CSS documents (because the DOM has yet to be rendered). I would see issues with async loading however.


I cant look for a value in a object array, it returns me error

Question: Hello everyone I'm doing this music player and this is the song loader but the problem is that when I try to assing the value to song constant with lookSongbyId function it returns me an error idk why
let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{

    function lookSongbyId(id)
    {
        queue.forEach(currentSong => {
            if(currentSong.id == id )
            {
                return currentSong
            }
        })
    }

    const song = lookSongbyId(id)

    console.log(`la canción ${song.name} ha sido cargada`)
}
loadSong(1)

song constant is undefined, and I dont know why aghhh
If u could help me with this code I've been so thankful with u :DDD
Comment: Syntax: `functionlookSongbyId(id)`. Also, you should load the whole array of `queue` and then run each object of array through `.forEach()`.
Comment: thanks i didnt realize of this typo but it was only when i wrote the question, in my original code it isnt but it doesnt work :c
Comment: Returning from a forEach handler goes to the next iteration, it does not return a value for its outer function. Use a for of loop instead, or one of the suggested answers
Answer: you can use directly filter if you want to return more than item or find if you want only want (if the id is unique)
const queue = [
      {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
      },
      {
        id: 2,
        name: 'Another Song2',
        artist: 'Favio Figueroa',
      }
    ];
    const useFilter = queue.filter((row) => row.id === 1 );
    console.log('useFilter', useFilter) // [ { id: 1, name: 'Crush', artist: 'Glades' } ]
    const useFind = queue.find((row) => row.id === 2 );
    console.log('useFind', useFind) // { id: 2, name: 'Another Song2', artist: 'Favio Figueroa' }

you can add in your function that logic.
Answer: You can simplify your function to just use find which will return the matched song.
let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{
    const song = queue.find(x => x.id === id)
    console.log(`la canción ${song.name} ha sido cargada`)
    return song
}
loadSong(1)

Comment: Woow thaanks it really helps me a lot
Answer: Assuming the functionlookSongbyId is just misspelled (you must write function lookSongbyId), the forEach function cannot be used to return a value, as indirectly said here.
Use a for ... of or .find() to retrieve the element
Answer: Don't create a function for the song search, you can use find and get the right song seamlessly:
const loadSong = (id) => {
    const song = queue.find( sng => sng.id === id);
    console.log(`la canción ${song.name} ha sido cargada`)
}

Comment: Interesting method! thanks for your help


Automorphism group of compositum of fields

Question: $\newcommand{\Gal}{\operatorname{Gal}}
\newcommand{\Aut}{\operatorname{Aut}}$
Suppose we have field extensions $F < K_1, K_2 < K$. It is known that if $K_1/F$ and $K_2/F$ are both Galois and $K_1 \cap K_2 = F$, then the Galois group of the compositum is given by:
$$
\Gal(K_1K_2/F) \cong \Gal(K_1/F) \times \Gal(K_2/F)
$$
If we don't assume $K_1 \cap K_2 = F$, we can still characterize $\Gal(K_1K_2/F)$ as a subgroup of this product. See Dummit and Foote, chapter 14, proposition 21.
My question is: what if we don't assume that $K_1/F$ and $K_2/F$ are Galois? Do we still have that:
$$
\Aut(K_1K_2/F) \cong \Aut(K_1/F) \times \Aut(K_2/F)?
$$
If not, what would be an easy counter-example?
Comment: Where you write "subfield", I think you mean "subgroup". If you do not assume Galois, what does $\mathrm{Gal}(K_i/F)$ mean? Just the automorphisms of $K_i$ that fix $F$?
Comment: @ArturoMagidin Yes, these are typos. You interpreted correctly. I'll edit my question for clarity.
Answer: I'm going to interpret your question as asking whether $\mathrm{Aut}(K_1K_2/F) = \mathrm{Aut}(K_1/F)\times\mathrm{Aut}(K_2/F)$ if $K_1$ and $K_2$ are extensions of $F$ such that $K_1\cap K_2=F$, where for fields $L\subseteq M$,
$$\mathrm{Aut}(M/L) = \{\sigma\in\mathrm{Aut}(M)\mid \sigma|_L=\mathrm{id}_L\},$$
and hence equals the Galois group in the special case where $M$ is Galois over $L$.
Consider $F=\mathbb{Q}$, $K_1=\mathbb{Q}(\sqrt[3]{2})$, and $K_2=\mathbb{Q}(\omega)$, where $\omega$ is a complex cubic root of unity; that is, a root of $x^2+x+1$.
Then $K_2$ is Galois over $\mathbb{Q}$ and $\mathrm{Gal}(K_2/F)$ is cyclic of order $2$. On the other hand, $\mathrm{Aut}(K_1/F)$ is trivial, because $\sqrt[3]{2}$ is the only real cubic root of $2$, $K_1$ is contained in $\mathbb{R}$, and an automorphism of $K_1$ must send $\sqrt[3]{2}$ to a cubic root of $2$. Thus,
$$\mathrm{Aut}(K_1/F)\times\mathrm{Aut}(K_2/F)\cong\{e\}\times C_2 \cong C_2$$
is cyclic of order $2$.
However, $K_1K_2$ is the splitting field of $x^3-2$, which has degree $6$ over $F$. In particular, $\mathrm{Gal}(K_1K_2/F)$ has order $6$ (and is isomorphic to $S_3$) so we get neither an isomorphism with, nor a realization as a subgroup of the direct product.
Comment: The natural assumption is that $K_1K_2=K_1\otimes_F K_2$ which doesn't change your answer.
Comment: @reuns: they are still assumed to be contained in a single extension $K$, so $K_1K_2$ is usually understood to mean the compositum, smallest subfield of $K$ containing both.


How can I adress problems of heteroscedasticity in mixed model analysis?

Question: I am analizing pupil size data using mixed model analysis in R. I use lme() from package nlme. However, I am encountering serious problems of heteroscedasticity and violation of normality assumption.

Do you have any suggestions on how to solve this problem?
I would like to test whether active neurostimulation (vs. control; Stimulation) increases pupil size over time (before stimulation vs. end stimulation; Time). We employed a between subject design.
I adopted the following strategies that did not solve the problem: 1. transformed the outcome - log(). 2. modelled the covariance-variance matrix following the instructions in this page https://rpsychologist.com/r-guide-longitudinal-lme-lmer#heteroscedasticity-at-level-1 .
Here the models:
Here the models:
Time (0 vs . 1)
Stimulation (0 vs 1)
Tonic_PS = pupil size
ID = participant ID
model.1 <- lme(Tonic_PS ~ Time * Stimulation,,
random = ~ Time|ID,
weights = varIdent(form= ~ 1 | Stimulation),
data =Tonic_pupilsize_T2,
method = "ML")

model.2 <- lme(Tonic_PS ~ Time * Stimulation,
random = ~ Time|ID,
weights = varIdent(form= ~ 1 | Stimulation * Time),
data =Tonic_pupilsize_T2,
method = "ML")

model.3 <- lme(Tonic_PS ~ Time * Stimulation,
random = ~ Time|ID,
correlation = corAR1(),
data =Tonic_pupilsize_T2,
method = "ML")

model.4 <- lme(Tonic_PS ~ Time * Stimulation, random = ~ Time|ID,
weights= varIdent(form= ~ 1 | Time),
correlation = corAR1(),
data =Tonic_pupilsize_T2,
method = "ML")

Any suggestion will be very appreciated!
Comment: Add: If the basis for your judgment is the second plot: Modeling heteroscedasticity does not vanish if you model it. You just tell the model that level-1-residual variance varies as a function of Stimulation and Time - nothing more and nothing less. If this is the correct model for the variance part than you simply get consistent standard errors, nothing else should change.
Comment: Could you please be more specific regarding why you think that your second approach did not solve the problem? Because it actually should - except if group is not the cause of the heteroscedasticity.
Comment: You actually can't really - just like you don't know if you have all relevant predictors for the mean you don't know that for the variance either. For your case, estimating separate variances for each cell seems fine to me - but you could of course check for a robust method as suggested in the other answer.
Comment: Does this answer your question? [Accounting for heteroskedasticity in lme linear mixed model?](https://stats.stackexchange.com/questions/118391/accounting-for-heteroskedasticity-in-lme-linear-mixed-model)
Comment: Thanks a lot for your response. I indeed judged based on the graph. I compared the above described models with the simpler model that includes only Random slope and Intercept.
model <- lme(Tonic_PS ~ Time * Stimulation, random = ~ Time|ID, data =Tonic_pupilsize_T2, method = "ML")
The model fit of the above described models is better looking at BIC AIC. Is this sufficient? Could you be more specific about  how I can establish looking at the standard errors if I modelled correctly the variance part?
Comment: ok thanks a lot!
Comment: How do you express pupil size? Area? Diameter? Reciprocal diameter? Something else?  Your models look strange, because they seem to use "participant ID" as the response variable.
Answer: Rather than transforming data to fit a model, I suggest using a model that fits the data.
Quantile regression does not assume homoscedasticity and  quantile regression for multilevel (or mixed) models now exists.  There is an R package lqmm available from CRAN that should work.
Comment: Thanks a lot for the suggestion!


HowTo Disable WebBrowser 'Click Sound' in your app only

Question: The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.
Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.
using System;
using Microsoft.Win32;

namespace HowTo
{
    class WebClickSound
    {
        ///
        /// Enables or disables the web browser navigating click sound.
        ///
        public static bool Enabled
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
                string keyValue = (string)key.GetValue(null);
                return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
            }
            set
            {
                string keyValue;

                if (value)
                {
                    keyValue = "%SystemRoot%\\Media\\";
                    if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
                    {
                        // XP
                        keyValue += "Windows XP Start.wav";
                    }
                    else if (Environment.OSVersion.Version.Major == 6)
                    {
                        // Vista
                        keyValue += "Windows Navigation Start.wav";
                    }
                    else
                    {
                        // Don't know the file name so I won't be able to re-enable it
                        return;
                    }
                }
                else
                {
                    keyValue = "\"\"";
                }

                // Open and set the key that points to the file
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
                key.SetValue(null, keyValue,  RegistryValueKind.ExpandString);
                isEnabled = value;
            }
        }
    }
}

Then in the main form we use the above code in these 3 events:

Activated
Deactivated
FormClosing
private void Form1_Activated(object sender, EventArgs e)
{
    // Disable the sound when the program has focus
    WebClickSound.Enabled = false;
}

private void Form1_Deactivate(object sender, EventArgs e)
{
    // Enable the sound when the program is out of focus
    WebClickSound.Enabled = true;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Enable the sound on app exit
    WebClickSound.Enabled = true;
}

The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.
What do you guys think? Is this a good solution? What improvements can be made?
Comment: I had a problem with this line:  isEnabled = value;
I've just commented it, but i want to know what it was intended to be
Answer: const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
const int SET_FEATURE_ON_PROCESS = 0x00000002;

[DllImport("urlmon.dll")]
[PreserveSig]
[return: MarshalAs(UnmanagedType.Error)]
static extern int CoInternetSetFeatureEnabled(int FeatureEntry,
                                              [MarshalAs(UnmanagedType.U4)] int dwFlags,
                                              bool fEnable);

static void DisableClickSounds()
{
    CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,
                                SET_FEATURE_ON_PROCESS,
                                true);
}

Comment: Awesome, works like a charm and only disables it for just your app and doesn't rely on form focus.
Answer: I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.
So instead of this:
webBrowser1.DocumentText = "
Hello, world!
";

try this:
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("
Hello, world!
");

Comment: your suggested solution prevents the control from making that click noise but on the other side this approach causes the control to have serious focus issues. In my case, the webbrowser control steals back the focus at the end of the event loop. As far as I can tell there's no workaround for that.
In my case I needed to get back to the DocumentText solution - but still I'm looking for disabling that annoying sound. Any other ideas?
Comment: Just found out, that James on this thread: http://stackoverflow.com/questions/393166/how-to-disable-click-sound-in-webbrowser-control has a great solution - at least for IE7 and IE8. I can use the DocumentText property, have no focus issues and best of all, I have no click sound.
Answer: You disable it by changing Internet Explorer registry value of navigating sound to "NULL":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","NULL");

And enable it by changing Internet Explorer registry value of navigating sound to "C:\Windows\Media\Cityscape\Windows Navigation Start.wav":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","C:\Windows\Media\Cityscape\Windows Navigation Start.wav");

Answer: Definitely feels like a hack, but having done some research on this a long time ago and not finding any other solutions, probably your best bet.
Better yet would be designing your application so it doesn't require many annoying page reloads.. for example, if you're refreshing an iframe to check for updates on the server, use XMLHttpRequest instead.  (Can you tell that I was dealing with this problem back in the days before the term "AJAX" was coined?)
Answer: If you want to use replacing Windows Registry, use this:
// backup value
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string BACKUP_keyValue = (string)key.GetValue(null);

// write nothing
key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, "",  RegistryValueKind.ExpandString);

// do navigation ...

// write backup key
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, BACKUP_keyValue,  RegistryValueKind.ExpandString);


Check for my code coverage ratio from my build process

Question: I am using Visual Studio 2008 Code Coverage and I have many classes that are 100% covered by my unit tests. How could I check during my build process that these classes remain 100% covered by my unit tests (also executed during my build process after compilation) ?
Comment: This will depend on what you are using for continuous integration build.
Comment: Could you paste your msbuild script please?
Answer: For code coverage ratio check you can use NDepend.
You can declare an attribute, like YourNamespace.FullCoveredAttribute
and tag your classes 100% covered by tests.
using YourNamespace;
...
[FullCoveredAttribute]
class MyClassFullCovered { ... }

Then the single following CQL query will check for all classes 100% covered and warn if it finds any flaw:
WARN IF Count > 0 IN SELECT TYPES WHERE
HasAttribute "YourNamespace.FullCoveredAttribute" AND
PercentageCoverage < 100

The magic comes from the fact that NDepend can gather code coverage metric from both NCover and VSTS Coverage.


Is it possible to restrict SQL server access to a Hamachi VPN?

Question: We already use Hamachi to link our isolated servers together, but it is possible to restrict access to certain applications so that they can only be seen on the server or via Hamachi's VPN.
From our logs we can see "far eastern" probing of our SQL Server installations, and ideally we would like to restrict access to SQL Server boxes. We have a unsophisticated network topology of leased servers.
Answer: If this is running on a recent Windows Server version (preferably 2008 R2), then just use the windows firewall to deny access to your SQL ports except from the hamachi VPN IP addresses you need.
Answer: This is why SQL Server's should never be exposed to the public Internet.  Instead the SQL Server should be configured with private IPs which are not NAT'ed to a public IP.
Configure your routers or firewall and configure them to now allow any access from the outside world.
Comment: Thanks - It is an inherited system - which we are trying to modernise
Comment: Sounds like there is probably a decent amount of stuff to fix.


Ordenar GridView ASC

Question: Tenho esse grid, e gostaria de ordenar as colunas por ordem crescente (ASC)
como fazer?
<asp:GridView ID="gridView1" runat="server" AllowPaging="False" AllowSorting="True" DataSourceID="sqlTeste"
            AutoGenerateColumns="False" EmptyDataText="<%$ Resources:Mensagens, BuscaSemRegistros %>">
            <Columns>
                <asp:BoundField DataField="FUNDO" HeaderText="Fundo" SortExpression="NOME_FUNDO" />
                <asp:BoundField DataField="NUM_MES" HeaderText="Mês de Referência" SortExpression="NUM_MES_ORDENACAO" />
                <asp:BoundField DataField="COD_USUARIO" HeaderText="Usuário Responsável" SortExpression="COD_USUARIO" />
                <asp:BoundField DataField="DTA_INCLUSAO" HtmlEncode="False" DataFormatString="{0:g}"
                    HeaderText="Data/Hora Inclusão" SortExpression="DTA_INCLUSAO">
                </asp:BoundField>
            </Columns>
        </asp:GridView>

Comment: Você vai ordenar todos os campos?
Answer: A ordenação da GridView tem bastante problemas, uma solução que pode funcionar é essa aqui:
Adicionar o evento de ordenação na GridView
<asp:GridView ... OnSorting="gridView1_Sorting" AllowSorting="true">

E no seu CodeBehind
private string ConverterSortDirection(SortDirection sortDirection)
{
    string novaDirecao = String.Empty;

    switch (sortDirection)
    {
        case SortDirection.Ascending:
            novaDirecao = "ASC";
            break;
        case SortDirection.Descending:
            novaDirecao = "DESC";
            break;
    }
    return novaDirecao;
}

protected void gridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable dataTable = gridView1.DataSource as DataTable;

    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " " + ConverterSortDirection(e.SortDirection);

        gridView1.DataSource = dataView;
        gridView1.DataBind();
    }
}

Ordenar GridView ASC


How to prove the following inequality using Lagrangian multipliers?

Question: Find the maximum and minimum values of the function $f(x,y,z)=(xyz)^2$ where $(x,y,z)$ is on the sphere $x^2+y^2+z^2=r^2$.
Then show using above that $(abc)^{1/3} \leq (a+b+c)/3$. For non-negative $a,b,c$
For the first part I have set up the Lagrangian and calculated the partial derivatives.
That is we have $$2xy^2z^2+2\lambda x =0\\2x^2yz^2+2\lambda y =0\\2x^2y^2z+2\lambda z =0\\x^2+y^2+z^2-r^2=0$$
Now since the point lie on the sphere we have $x,y,z \neq0$ hence $\lambda=-y^2z^2=-x^2z^2=-x^2y^2 \implies x^2=y^2=z^2$ (I think).
So we get $3x^2=r^2 \implies x^2=r^2/3$ and then the maximum and minimum are the same and we have $f(x,y,z)=(xyz)^2=r^6/27$.
Okay so firstly I want to ask am I correct up until here?
And secondly how do I prove the last inequality?
Comment: If the maximum and the minimum are the same, then the function is constant on the sphere. So there must be something wrong.
Comment: Can you see where?
Comment: I'll post an answer
Comment: There are points in the sphere where $x=0$ or $y=0$ or $z=0$. Of course not the three equalities at the same time.
Comment: From the equations, either you get $x=0$ or $y=0$ or $z=0$, in which case $f=0$ (that is the minimum value). If $x,y,z\neq 0$, then you get $x^2=y^2=z^2$ and $f(x,y,z)=r^6/27$, which is the maximum value. No idea how to prove the inequality from that.
Comment: Yeah that is what I got pretty much. (I forgot to include the case $x,y,z=0$ and hence the minimum could be $0$).
Answer: We have that $f(x,y,z) \ge 0$ for all $(x,y,z)$. Now $f(0,r/{\sqrt 2}, r/{\sqrt 2}) = 0$, hence the minimum of $f$ is $0$.
I am not sure what you mean by $x,y,z \neq 0$, but if it is "$ x \neq 0$ and $y \neq 0$ and $z \neq 0$", then it is incorrect. What we know is that at least one of them should be $\neq 0$, but this is not important.
From the system you have, multiply the first equation by $x$, the second by $y$ and the third by $z$ and subtract the equations from each other to get $x^2 = y^2 = z^2$ (realizing that $\lambda = 0$ corresponds to $f(x,y,z) = 0$, and then that we may suppose $\lambda \neq 0$). Then, $x^2 = y^2 = z^2 = r^2/3$. Hence, $f$ achieves its maximum $6$ times (at the points $(\pm r/{\sqrt 3}, \pm r/{\sqrt 3},\pm r/{\sqrt 3})$), and this maximum is $f(r/{\sqrt 3},r/{\sqrt 3},r/{\sqrt 3}) = r^6/27$.
See Wore's comment for how to get the inequality.
Comment: @Wore you are right. I'll fix that.
Comment: You can fix it like this: since $a,b,c\geq 0$, there are $x,y,z$ such that $a=x^2,b=y^2,c=z^2$. Choose now $r$ such that $r^2=a+b+c=x^2+y^2+z^2$. Using what we know we obtain $f(x,y,z)=abc\leq r^6/27=(a+b+c)^3/27$. Finally, take cubic root in both sides.
Comment: I don't think I solved the problem with my edit, but I'll think about how to do it properly
Comment: You can use the information in my previous comment if you want.
Comment: @Wore I like what you did, but I'll stick with my solution because I am too lazy to write that out again, but I'll edit to refer the OP to your comment.
Comment: Fair enough, but it seems that you are morally obligated to find a flawless correction of your original answer since it has been already accepted. :)
Comment: Thank you both for your help it is a shame I can only award best answer and that is it. Wore you were a help also :)
Comment: You're welcome. @Wore I am interested in being correct, not in having my answer accepted. After some thought, I realized that the inequality I used is not true. In fact, it is the opposite inequality that holds (also, in general, $\left( \frac{a+b+c}3 \right)^p \le \frac{a^p + b^p + c^p}3$ for all $p\ge 1$).
Comment: @Ahmed it was a joke! I believe that as far as the question is answered (either in some answer, or in the comments, or a combination of both) and the OP understands the solution is ok, right?


We refer to X for standard notations and definitions from Y

Question: I'm having problems with my mathematical English, so I'd like to ask for your help! Is it correct to write something like "Unless stated otherwise, we refer to [1] and [2], respectively, for standard notations and definitions from set theory and ring theory."? Are there some better ways to phrase the same concept? I don't know if this is the appropriate place to ask for certain questions, but I tried in an English chat, and they recommended to ask mathematicians.
Thanks in advance.
Comment: This seems like a perfectly good English sentence to me (I'm not sure why someone in an English chat would recommend you post the question to mathematicians - (English) mathematical writing is still English prose).
Comment: They say that mathematicians prefer certain expressions to others, no matter if they are written in a correct English.
Answer: If you are writing a paper, then you could say something like:
"The nomenclature used in our paper for set theory and ring theory are borrowed from [1] and [2] respectively, unless stated otherwise."
Just my two cents
Comment: You mean nomenclature :)


Customising Search Box in Search Results Adding OnBlur and OnFocus Attributes

Question: I am trying to add custom #attributes to the search_form in the search results page. I get the $form_id from devel which is $form_id = "search_form".
Here is my hook_form_alter() implementation:
function nm_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'search_form' ){
    $form['search-form']['#attributes']['onblur'] = "if (this.value == '') {this.value = '".$form['search-form']['#value']."';}";
    $form['search-form']['#attributes']['onfocus'] = "if (this.value == '".$form['search-form']['#value']."') {this.value = '';}";
  }
}

I checked if the condition is right inside the if statement with the following code, but nothing happened.
dpm($form['search-form'])

So, I am suspecting that the if condition is right.
Answer: If you want to add attributes to the form itself you need to do it on the $form array:
$form['#attributes']['onblur'] = "if (this.value == '') {this.value = '".$form['search-form']['#value']."';}";

I'm just guessing but I think you're expecting there to be a search-form element because that's the CSS ID of the form? That's not quite how it works with the FAPI, the elements are in a hierarchy that will eventually be rendered down to HTML. Until that rendering happens the elements have no concept of an ID/class etc., so you won't find them in the array under the ID/class.
Comment: Thanks, What I want to do was different that you answer, But thanks for guiding me. I finally did it. Will post the right way to the question.
Answer: The search form contains the following form elements.
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $module,
  );
  $form['basic'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array(
    '#type' => 'value',
    '#value' => '',
  );
  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

There isn't any $form['search-form'].
If you want to add attributes to the form you need to add them to $form['#attributes'], as with the following code.
$form['#attributes']['class'][] = 'search-form';

If you want to add attributes to the textfield, then you should use $form['basic']['keys']['#attributes'].
Keep in mind that the attributes you add there are added to the search form, not to the page showing the search results. The page showing the search results is output from search_view().
Comment: Thanks for your answer, I want to add the onblur and onfocus to the input field not the form itself, anyway I did it after deeply looking for the array of the form. Will post the right way in the question. Thank u :)
Answer: Solution:
What I was trying to do was adding the onblur and onfocus attributes and here how I did it: You can insert the following to your template.php
function {ThemeName}_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'search_form' ){
    $form['basic']['keys']['#attributes']['onblur'] = "if (this.value == '') {this.value = '".$form['basic']['keys']['#default_value']."';}";
    $form['basic']['keys']['#attributes']['onfocus'] = "if (this.value == '".$form['basic']['keys']['#default_value']."') {this.value = '';}";
  }
}

Thanks for all who helped.


Chat PHP Como Usar?

Question: Quero ter um chat para suporte no site que estou desenvolvendo, estou querendo utilizar o tawk.to, tenho algumas dúvidas de como instalar ele, estou desenvolvendo o site em CSS e HTML.
A dúvida é se o site precisa estar online para poder aparecer o chat? Eu apenas colei o código que eles disponibilizam do chat, entretanto não aparece nada, quem poder me ajudar agradeço, Muito obrigado pela atenção !!!!
Vou inserir o código que o tawk.to disponibiliza no site deles e o meu como esta ficando :

@charset "utf-8";
/* CSS Document */

#topo {
 background:url(../imagens/topo2etrelas.png);
 border-left:1px solid #000;
 border-right:1px solid #000;
 position:inherit;
 width:1024px;
 height:190px;
 margin:auto;

}

#fundoinicial {
 background-image: url(../imagens/fundoof.png);
 width: 1024px;
 height: 1000px;
 margin: auto;
 border-right: 1px solid #000;
 border-left: 1px solid #000;

}

#menufundo {
 background:#60365e;
 border:1px solid #000;
 position:relative;
 width:1024px;
 height:28px;
 margin:auto;

}

#ul li a{
 font-family:"Comic Sans MS", cursive;
 font-style:normal;
 list-style-type:none;
 display: inline;
 font-size:19px;
 line-height:0px;
 padding:10px;
    margin:4px 0 0 52px;
 color:#FFF;
 text-decoration:none;
 float:left;

}

#ul li a:hover{
 text-shadow:0px 0px 0px black,
    0px 0px 0px black,
    0px 0px 0px black,
    0px 0px 0px black;
 font-size:19px;
    color:black;
}

.rodape {
 background: url(../imagens/rodape.png);
 margin: auto;
 position: absolute;
 width: 1056px;
 height: 99px;
 left: 132px;
 top: 1198px;

}

.trs {-webkit-transition:all ease-out 0.5s;
    -moz-transition:all ease-out 0.5s;
    -o-transition:all ease-out 0.5s;
    -ms-transition:all ease-out 0.5s;
    transition:all ease-out 0.5s;}
#slider {
 position: absolute;
 width: 970px;
 height: 339px;
 margin: auto;
 left: -25px;
 top: 122px;
 border: 1px solid #666;
 border-radius: 10px 10px 10px 10px;
}
#slider a {
 position: absolute;
 width: 850px;
 height: 290px;
 margin: auto;
 left: 57px;
 top: 4px;
 opacity: 0;
 filter: alpha(opacity=0);
}
.ativo {opacity: 1!important; filter:alpha(opacity=100)!important;}

/*controladores*/
span {
 background: none;
 cursor: pointer;
 opacity: 0;
 filter: alpha(opacity=0);
 position: absolute;
 bottom: 12px;
 width: 44px;
 height: 43px;
 z-index: 5;
}
.next {
 right: 8px;
}
.next:before,.next:after {left: 21px;}
.next:before {
    -webkit-transform: rotate(-42deg);
    top: 5px;
}
.next:after {
    -webkit-transform: rotate(-132deg);
    top: 19px;
}
.next:before,.next:after,.prev:before,.prev:after {content: "";
    height: 20px;
    background:#000;
    width: 1px;
    position: absolute;
}
.prev {
 left: -16px;
}
.prev:before,.prev:after {left: 18px;}
.prev:before {
    -webkit-transform: rotate(42deg);
    top: 5px;
}
.prev:after {
    -webkit-transform: rotate(132deg);
    top: 19px;
}

figure:hover span {opacity: 0.76;filter:alpha(opacity=76);}
    figure {
    max-width: 950px;
    height: 310px;
    position: relative;
 top:60px;
 left:0px;
    margin:0px 0 0 50px;

}

figcaption {
 border-top: 0.2px solid #000;
 border-radius: 0px 0px 10px 10px;
 color: #FFF;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 22px;
 text-align: center;
 background: #60365e;
 width: 970px;
 position: absolute;
 margin: auto;
 bottom: -156px;
 left: -24px;
 line-height: 35px;
 height: 35px;

}

h1 a{
 font-family: Arial, Helvetica, sans-serif;
 font-size: 19px;
 color: #FFF;
 text-decoration: none;
 text-shadow: 1px 1px black;
 position: absolute;
 left: 172px;
 top: 1209px;

}

p a{
 font-family: Arial, Helvetica, sans-serif;
 font-size: 15px;
 color: #FFF;
 text-decoration: none;
 text-shadow: 1px 1px black;
 position: absolute;
 left: 172px;
 top: 1237px;
}

.facebook{
 width: 32px;
 right: 32px;
 position: absolute;
 top: 25px;
 left: 515px;
 opacity: 0.5;
 filter: alpha(opacity=50);

}

.facebook:hover {
    opacity: 1.0;
    filter: alpha(opacity=100); /* For IE8 and earlier */
}

.trabalhe {
 font-family: Arial, Helvetica, sans-serif;
 font-size: 19px;
 color: #FFF;
 text-decoration: none;
 text-shadow: 1px 1px black;
 position: absolute;
 left: 986px;
 top: 1231px;
 width: 159px;

}

.email {
 font-family: Arial, Helvetica, sans-serif;
 font-size: 15px;
 color: #FFF;
 text-decoration: none;
 text-shadow: 1px 1px black;
 position: absolute;
 margin-top: 20px;
 left: 992px;
 top: 1235px;
}

.purificador img {
 position: absolute;
 width : 130px;
 height: 130px;
 top: 950px;
 right:1020px;

}
.fogao img {
 position: absolute;
 width: 130px;
 height: 130px;
 top: 950px;
 right: 820px;
}
.geladeira img {
 position:absolute;
 width:150px;
 height:200px;
 top:880px;
 right:610px;
}
.maquina img {
 position: absolute;
 width: 115px;
 height: 165px;
 top: 915px;
 right: 450px;

}
.ar img {
 position: absolute;
 width: 200px;
 height: 130px;
 top: 960px;
 right: 200px;
 font-size: 36px;
}

.posicionado1 a{
 font-family: "Comic Sans MS", cursive;
 color:#000;
 text-decoration:none;
 position: absolute;
 right: 219px;
 top: 1115px;
 font-size: 18px;
}

.posicionado1 a:hover{
 text-decoration:underline;
 color:#ff8533;
}

.posicionado2 a{
 font-family: "Comic Sans MS", cursive;
 color: #000;
 text-decoration: none;
 position: absolute;
 right: 462px;
 top: 1115px;
 font-size: 18px;
}
.posicionado2 a:hover{
 text-decoration:underline;
 color:#ff8533;
}

.posicionado3 a{
 font-family: "Comic Sans MS", cursive;
 color: #000;
 text-decoration: none;
 position: absolute;
 right: 629px;
 top: 1115px;
 font-size: 18px;
 height: 0px;

}
.posicionado3 a:hover{
 text-decoration:underline;
 color:#ff8533;
}

.posicionado4 a{
 font-family: "Comic Sans MS", cursive;
 color: #000;
 text-decoration: none;
 position: absolute;
 right: 857px;
 top: 1115px;
 font-size: 18px;
 height: 0px;

}
.posicionado4 a:hover{
 text-decoration:underline;
 color:#ff8533;
}

.posicionado5 a{
 font-family: "Comic Sans MS", cursive;
 color: #000;
 text-decoration: none;
 position: absolute;
 right: 1036px;
 top: 1115px;
 font-size: 18px;
 height: 0px;

}
.posicionado5 a:hover{
 text-decoration:underline;
 color:#ff8533;
}

.mibew-agent-button{
 position: absolute;
 top:330px;
 left:300px;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Alfatec</title>
<link rel="shortcut icon" href="imagens/ico.png" type="imagem/x-png" />
<link href="css/reset.css" rel="stylesheet" type="text/css" />
<link href="css/estilo.css" rel="stylesheet" type="text/css" />

Página Inicial

Quem Somos

Áreas de Cobertura

Serviços

Fale Conosco

Trabalhe Conosco

firstname.lastname@example.com

-->

  Ar Condicionados

 Lavanderia

 Refrigeração

 Cozinha

 Purificadores

Comment: Não tem documentação essa ferramenta?
Comment: não tudo online , apenas disponibilizam o codigo para inserir no html
Answer: Dentro do painel do Tawk.to tem a opção de, exibir somente no domínio (você deve informar no painel) ou, deixar aberto. Acesse o Dashboard como administrador, vá na guia Administrador -> Restrição de domínio. Se você tiver informado algum domínio, remova, assim será exibido em qualquer página/site que criar. Recomendo que, quando for publicar o site, adicione o domínio para o chat ficar restrito ao seu site.

Chat PHP Como Usar?


Trying to read confusion matrices

Question:
I am given these 2 confusion matrix for a homework assignment but I am unsure how to interpret the data. I am asked to make a decision with these two matrices. For the first matrix am I interpreting this right:
-We predict that 4 are yes but really there are 5
-We predict 1 No but there are 90??
I am just very confused with this confusion matrix (ha)
Answer: For the first table $$\begin{array}{|c|cc|} \hline & p & n \\\hline y & 4 & 5 \\ n & 1 & 90\\ \hline\end{array} $$
We predicted $9$ of them to be yes (look at the sum over first row) but really there are only $4$ (top left entry).
We predicted $91$ of them to be no (look at the sum over second row) but really there are $90$ (bottom right entry). Most entries that we predict to be negative are indeed negative.

Trying to read confusion matrices


.htaccess redirect css file to php

Question: I took my file.css file and rename it to file.php and add this code at the first line on the new php file :
<?php
    session_start();
    header("Content-type: text/css");
?>
/* css content goes here ... */

Now I am trying to redirect all request from http://puaction.com/css/file.css to http://puaction.com/css/file.php via htaccess BUT it's not working... :/
what's wrong with my htaccess file?
That's my .htaccess file :
RewriteEngine on
RewriteRule file.css file.php

Comment: Where is `.htaccess`?
Comment: I don't see an .htaccess file?
Comment: I have just add my htaccess file... take a look. Thanks !
Comment: Does your Apache configuration allow you to change these settings in a `.htaccess` file? If yes, then perhaps refer to Apache's documentation on the topic of `mod_rewrite`: http://httpd.apache.org/docs/current/rewrite/remapping.html
Answer: In the htaccess file in your document root, add:
Redirect 301 /css/file.css /css/file.php

.htaccess redirect css file to php


What is the best way to calculate current capacity for place?

Question: I have database like this and I want to calculate current capacity for places.
Ex: A Place max_capaity 64, current_capacity 5.
Someone go to A Place. current_capacity should be 6.
I can create "current_capacity" column and can update it.
But is that a right way? Or should I query all person who in the A place and count current_capacity from there? (using COUNT)
Which one is right way for big or active databases?
(Imagine 2000 places and billions people)
Answer: You should start with a basic join and aggregation.  Something like this:
select p.*, p.max_capacity - u.cnt
from places p left join
     (select place_id, count(*) as cnt
      from user_places
      group by place_id
     ) u
     on p.place_id = u.place_id;

I wouldn't recommend adding a column unless you really have to.  In order to maintain the column, you then have to implement triggers, to update the value whenever a user is assigned or removed from a place.


How can I tell which version of CIFs is in the kernel if CIFs module isn't loaded?

Question: I need to determine the CIFs version that exists in my kernel, but the CIFs module isn't loaded.
my-user@ip-XX-XX-XX-XX:~$ modinfo kernel/fs/cifs.ko
modinfo: ERROR: Module kernel/fs/cifs.ko not found.

When I run find /lib/modules/$(uname -r) -type f -name '*.ko*' in the list of results I see /lib/modules/4.15.0-1058-aws/kernel/fs/cifs/cifs.ko
How can I find out what version of cifs.ko exists, awaiting potential use, in my kernel?  I'm using Ubuntu 18.04.
Answer: Try modinfo (if you are not root you might need the full path) with the name of the module:
$ /sbin/modinfo cifs

Comment: That did it--I was just using the wrong path and I didn't realize it would work without the full path.  Thanks!


Can Ckeditor use relative paths for images?

Question: I am building a drupal 7 site on my localhost with ckeditor (7.x-1.13), HTML Purifier (7.x-1.0).
I realized that when my ip changes on the network, the links to the images I upload from ckeditor are broken. As I checked the html source, I saw that they are absolute urls and are using the previous ip as a part of them. Now that the ip is different, they are broken.
I need to develop the site and enter most of the content on localhost and if I cannot solve this problem, things will get complicated when I move the site to the server.
After reading a related question (D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path) I tried installing pathologic (7.x-2.11) module, checking the settings for text formats, clearing the cache with no result.
Is there a way to make ckeditor to use relative paths for images? Would it have any disadvantages?
Answer: You should always use relative paths in your content to avoid the problem you now have.
If it was me I would fix the links in the database so they are all relative. You can do so with sql queries like this:
UPDATE field_body_data
SET body_value = REPLACE(body_value, 'http://example.com/', '/')
WHERE body_value LIKE '%http://example.com/%';

Followed by:
UPDATE field_body_data
SET body_value = REPLACE(body_value, 'http://example.com', '/')
WHERE body_value LIKE '%http://example.com%';

There are two to catch the case you might have a path to the home page without a trailing slash.
You would have to do this for any text area field that might contain a hyperlink.
The Pathologic module will also help you around this issue.
You add the pathologic input filter for your relevant formats, then configure it with your old domain name.
Also add the domain name /
This will make it change relative paths to use their alias, like /node/10 to be /node-path-alias
That last feature with the aliases is very useful.
See https://drupal.org/node/257026 for more info on configuring pathologic.
Comment: To be clear, if you use Pathologic as suggested in the latter half of this answer, it can be configured so that doing the replacement with SQL queries, as in the first half, is not necessary.


Checkstyle for PHP as Eclipse Plugin

Question: Is there such a plugin available ?
Answer: Yes there's one: PHP Tool Integration. The equivalent to Checkstyle is PHP_CodeSniffer (a pear package). You'll find further information here PHP_CodeSniffer.

Checkstyle for PHP as Eclipse Plugin


How to interpret a positive beta coefficient in linear regression?

Question: Could someone provide a sample interpretation for the following:
<code>                                dependent variable
Categorial variable
 category 1                    Beta estimate of 1.78 (-3.39,6.69).
 cat 2                         2.45 (-287, 9.34)
 cat 3                         4.49 (-3.65, 7.08)
</code>
Answer: It depends on whether you are using dummy coding or effect coding or some other coding. In dummy coding, a positive $\beta$ for a categorical variable means that the predicted value of the dependent variable is higher by $\beta$ when the independent variable takes that category than when it takes the reference category
Answer: Note that if the numbers in parens are the confidence intervals on the betas then for all of your coefficients the intervals include both positive, negative, and 0 values meaning that it is possible that there is no effect what soever or that it could even be negative and that the reason your are seeing positive betas could be explained by pure chance.
Before worrying too much about the size and direction of effects you should make sure that what you are seeing cannot be easily due to random chance (the sample you happened to get).
If you get meaningful estimates that are not due to chance, then see @PeterFlom's answer.
Comment: Yes, and @confusedstat you probably want also want a test for the overall usefulness of the categorical variable so you can test all categories simultaneously rather than just one at a time (which is all your current readout allows).  This can be done via an F test comparing the model with the variable in to one without the variable - often a standard output from an ANOVA table based on the model.


Dailymotion "broke" HTTPS with video thumbnail (Chrome warning)

Question: I have an embed dailymotion video inside a web page. I use the code below to display it. This code call the preview picture of the video through HTTP instead of HTTPS whereas web page domain is on HTTPS.
API call is well sent with HTTPS protocol :
document.location.protocol

Due to this, all ressources into the web page are not sent through HTTPS and Chrome display a warning on the SSL certificate.


Can we build a Naive Bayes model in the presence of multicollinearity?

Question: There exists multi-collinearity in the model. As a result(may be) the accuracy of Naive Bayes model is less than logistic regression model(model is built with the help of PCA). So, is there any method to build Naive Bayes model in the presence of multi-collinearity?
Answer: One of the assumptions of Naive Bayes is class-conditional independence. If your data lacks this property (by way of multi-collinearity), then perhaps Naive Bayes will not be the right choice. It's worth noting, though, that your data does not need to exhibit independence, in general. Instead it is independence conditioned on the class. These are two different things.
Regardless though, you will be able to fit a Naive Bayes model. Plus, the broken assumptions may not be the end of the world. This paper (published at AAAI 2004) goes into more detail as to why Naive Bayes sometimes performs well in spite of broken assumptions.
Comment: Naive Bayes could still be a good model, the posterior probabilities will likely be inaccurate .


How not to "write" some value of a list?

Question: Hi I have created a big script with a lot of help from this forum.
But it is very slow. The main problem is coming from the fact that I wrote everything on my spreadsheet, and then retrieve some value and clean all the boxes with a .setValue("") or a .clearContent().
I guess that there is an easy way not to write the values, instead of write then clean...
here is my code :
function PLANNING() {
  var PLsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PLANNING_DATA");
  var PROsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("0_LISTE PROJETS");
  var COsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("1_REALISATION PROJETS");

////////////////////// PLANNING 2D

//entêtes des plannings
  PLsheet.getRange('M1:T1').setValues([['2D TASK','2D PROJECT', '2D RESPONSIBLE', "START DATE", 'END DATE', 'PROGRESS', 'FINISH?', 'PHASE']]);
  var values = COsheet.getRange('A2:AA' + COsheet.getLastRow()).getValues();
  var res = values.flatMap(valueRange =>
  {

  var DUR = valueRange[7] instanceof Date ? new Date(valueRange[7].getTime() - (100 * 86400000)) : valueRange[7];
  var BAT = valueRange[7] instanceof Date ? new Date(valueRange[7].getTime() - (15 * 86400000)) : valueRange[7];

  return [
    [valueRange[5], valueRange[1], valueRange[6], DUR, valueRange[7], valueRange[8], valueRange[2], 'durée projet'],
    [valueRange[5], valueRange[1], valueRange[6], BAT, BAT, 'BK', valueRange[2], 'date BAT'],
    [valueRange[5], valueRange[1], valueRange[6], valueRange[7], valueRange[7], 'BK', valueRange[2], 'date BAP'],
    ];
  });
  //Logger.log(res)
  PLsheet.getRange(2, 13, res.length, res[0].length).setValues(res);

  //remplir les cases projets vides :
  var project2D = PLsheet.getRange(2,14,PLsheet.getLastRow()-1,1).getValues();
  // skip the first row of values assuming it alread has a value

  for( let i=1; i<project2D.length; i++ ) {
  if( project2D[i][0] === "" ) project2D[i][0] = project2D[i-1][0];
  }
  PLsheet.getRange(2,14, project2D.length, 1 ).setValues(project2D);

  //remplir les cases FINISH vides :
  var finish2D = PLsheet.getRange(2,19,PLsheet.getLastRow()-1,1).getValues();
  // skip the first row of values assuming it alread has a value

  for( let i=1; i<finish2D.length; i++ ) {
  if( finish2D[i][0] === "" ) finish2D[i][0] = finish2D[i-1][0];
  }
  PLsheet.getRange(2,19, finish2D.length, 1 ).setValues(finish2D);//(range auquel on bake les valeurs)

//////////////////////cleaning

  //clean empty task
  var d2cleanervalues = PLsheet.getRange(2, 15, PLsheet.getLastRow() - 1, 1).getValues();
  for (let i = 0; i < d2cleanervalues.length; i++) {
    if (d2cleanervalues[i][0] === "") {
      PLsheet.getRange(2 + i, 16, 1, 1).setValue("");
      PLsheet.getRange(2 + i, 17, 1, 1).setValue("");

    }
  }
  //clean finish "TRUE" (Vrai)
  var d2cleanervalues = PLsheet.getRange(2, 17, PLsheet.getLastRow() - 1, 1).getValues();
  for (let i = 0; i < d2cleanervalues.length; i++) {
    if (d2cleanervalues[i][0] === true) {
      PLsheet.getRange(2 + i, 16, 1, 1).setValue("");
      PLsheet.getRange(2 + i, 17, 1, 1).setValue("");

    }
  }

}

Comment: Please modify your [mcve] to focus in directly on your question and nothing else
Comment: `//clean empty task` and `//clean finish "TRUE"` - for every row of data you have four  (4) `setValue` - that slows things down. 1) These two sections look as they could be combined into a single routine combining a single `getValues()` (covering columns O,P and Q), a single `for` statement, and a single `IF/else IF` (evaluating Column O and Column Q) and assigning the relevant row values to a "temporaryArray", and lastly a single `setValues()` using the value of the "temporaryArray". I'd be surprised if that didn't have a substantial effect on the overall run time.
Comment: Hi, I have try to use your suggestion to create an answer to my proble ! @Tedinoz and @ Cooper, if you have one minute to check the answer to my own question, I will be able to correct it to give an answer to my question ! thanks !
Comment: Please supply a complete sample of data for the various sheets as well as an example of the outcome that you are trying to achieve.
Comment: @Tedinoz, I made a big edit and add as much info as I can, thank you very much for your time !
Comment: Your `d2cleanervalues` references Column 15 ("O") and Column 17 ("P") in sheet "PLANNING_DATA". However your spreadsheet doesn't contain any data in Columns "O" or "Q" on "PLANNING_DATA". Please ensure that your spreadsheet data that aligns with the code in your question.
Comment: I think I should create a new question, because I have been working on 2 different planning created from the same "base" code, and in the question the code refer to the second planning (wrote on planning data from column 'M to T'). But in my own answer, the code refer to the first planning, (wrote on planning data from column 'A to I'). Can you focus on my "answer" rather then my "question", or do you think it's better if I create a new "topic" ? Thank you very much for your time !
Answer: The following answer appears to solve the OP's question.
Notes:

The column value that equates to TYPE isn't know, so not value was selected.
I used the nested array res developed by the OP.

There are 6 arrays for each project row.
so the increment in the counter variable must be i += 6 instead of the usual i++
rowCounter = rowCounter+1 was also necessary in order to keep track of the target row on PLSheet.

The value of installation oui/non is taken from Column F on PROSheet

however res does not include a value for this column
so it is necessary to return this value from values. This requires know the relevant row number on PROSheet which is calculated as i/6 or values[rowIdx][5]

function ejbPLANNING_ques() {
  var PLsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PLANNING_DATA");
  var PROsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("0_LISTE PROJETS");

  //Clean sheet
  PLsheet.getRange('A2:I').clearContent()

  // planning
  // Logger.log("DEBUG: PRO sheet range = "+PROsheet.getRange('A5:AI' + PROsheet.getLastRow()).getA1Notation())
  var values = PROsheet.getRange('A5:AI' + PROsheet.getLastRow()).getValues();
  var res = values.flatMap(valueRange =>
  {
    var temp = valueRange[19] instanceof Date ? new Date(valueRange[19].getTime() + (7 * 86400000)) : valueRange[19];
  return [
    [valueRange[2], valueRange[1], valueRange[4], valueRange[6], valueRange[18], valueRange[22], 'durée projet', valueRange[9], valueRange[11]],//project lenght
    [valueRange[2], valueRange[1], valueRange[4], valueRange[6], valueRange[18], valueRange[19], 'conception', valueRange[9], valueRange[11]],//research lenght
    [valueRange[2], valueRange[1], valueRange[4], valueRange[6], valueRange[19], temp, 'retour BAT', valueRange[9], valueRange[11]],//waiting for client
    [valueRange[2], valueRange[1], valueRange[4], valueRange[6], temp, valueRange[20], 'mise en fabrication', valueRange[9], valueRange[11]],//mise en production 3D time
    [valueRange[2], valueRange[1], valueRange[4], valueRange[6], valueRange[20], valueRange[21], 'fabrication', valueRange[9], valueRange[11]],//production time
    [valueRange[2], valueRange[1], valueRange[4], valueRange[6], valueRange[21], valueRange[22], 'installation', valueRange[9], valueRange[11]]//installation on site
   ];
  });

  // clean res false true;
  // rowCounter keeps count of the row number in PLSheet
  var rowCounter = 0
  // create a temporary array to hold values
  var tempArray = new Array
  // loop through res arrays-6 arrays per row
  for (let i = 0; i < res.length; i += 6) {
      if (res[i][0] === true) {
        // get the row number on PROSheet
        if (i==0){var rowIdx = 0}else{var rowIdx = i/6}
        Logger.log("DEBUG: TRUE: i="+i+", valueid="+rowIdx+", target range = "+PLsheet.getRange(2+rowCounter, 1,1,9).getA1Notation()+" value = "+res[i][0]+", row = "+res[i]+" , FINISH:"+res[i][0]+", PROJECT:"+res[i][1]+", DESCRIPTION:"+res[i][2]+", RESPONSIBLE:"+res[i][3]+", START DATE:"+res[i][4]+", END DATE:"+res[i][5]+" , TYPE:"+", not known"+", 3D oui/non:"+res[i][7]+", installation oui/non:"+values[rowIdx][5])
      tempArray.push([res[i][0],res[i][1],res[i][2],res[i][3],res[i][4],res[i][5],"not known",res[i][7],values[rowIdx][5]])
      rowCounter = rowCounter+1
    }
    else {
      Logger.log("DEBUG: FALSE: i="+i+" value = "+res[i][0]+", row = "+res[i]);
    }

  }
  var rows = tempArray.length
  var plLR = PLsheet.getLastRow()
  PLsheet.getRange(plLR+1, 1, rows , 9).setValues(tempArray)
}

RESULTS


Get x and y coordinates into variables in macro ImageJ

Question: I want to be able to place a point in an image using the point selection tool, then read the x and y coordinates to variable in a macro.
I've tried getSelectionCoordinates but that isn't working. I don't want to display the coordinates in a log or results window.
Any help would be much appreciated.
Answer: getSelectionCoordinates works fine for me, e.g.:
s = selectionType();

if( s == -1 ) {
    exit("There was no selection.");
} else if( s != 10 ) {
    exit("The selection wasn't a point selection.");
} else {
    getSelectionCoordinates(xPoints,yPoints);
    x = xPoints[0];
    y = yPoints[0];
    showMessage("Got coordinates ("+x+","+y+")");
}

(A common misunderstanding is that getSelectionCoordinates doesn't return a value conventionally - you have to give it the names of variables that it'll set.)


General probability

Question: What's the correct way to solve following question:
Dima has to pick 4 digit password (1-9 inclusive). Every digit is picked randomly.
What's the probability of picking at least 1 even digit?
Thank you
Comment: How many possible 4 digits passwords are there? How many of these have only odd digits?
Answer: You can do this with complementary counting. The probability of picking at least 1 even digit complements the probability of picking all odd digits, which is $\left (\frac{5}{9}\right)^4 = \frac{625}{6561}$, so the answer is $$1 - \frac{625}{6561} = \boxed{\frac{5936}{6561}}$$
Comment: Thank you very much!

General probability


Smallest positive integer that starts with 2016 and is divisible by 2017

Question: I have the following quiz but I don't really know how to solve it.
Find the smallest positive integer that starts (in decimals) with 2016 and is divisible by 2017.
Why to they specify the decimals in brackets?
First thought was to divide 2016 by 2017. 2016/2017 = 0.999504.
Should the integer start with 2016? I find it confusing. Can someone help?
Comment: Just for an experiment. Multiply $2017$ by $9$ or $99$ or $999$ or $9999$. The last works.
Answer: Your first thought is actually quite spot-on.
Since $2016/2017 \approx 0.999504$, we have $$0.9995 \times 2017 < 2016 < 1\times 2017$$
Multiplying this by various powers of $10$ yields
$$9\times 2017 < 10 \times 2016 < 10 \times 2017$$
$$99\times 2017 < 100 \times 2016 < 100 \times 2017$$
$$999\times 2017 < 1000 \times 2016 < 1000 \times 2017$$
The above shows that there are no $5,6,7$-digit multiple of $2017$ starting with $2016$. Finally:
$$9995\times 2017 < 10000 \times 2016< 9996 \times 2017 = 20161932$$
Comment: Thanks a lot for your answer. Could you please explain why you started multiplying by various powers of 10? I don't get the underlying logic of the solution. I would never thought to solve it like that...
Comment: This amounts to the observation that $2016\times 10^k$ is the smallest $(k+4)$-digit number starting with $2016$. Any number smaller than it cannot start with "$2016$".
Answer: Another solution:
20160   mod 2017 = 2007   No solution with 1 digit because     2017 - 2007 = 10
201600  mod 2017 = 1917   No solution with 2 digits because    2017 - 1917 = 100
2016000 mod 2017 = 1017   No solution with 3 digits because    2017 - 1017 = 1000
20160000 mod 2017 = 85
This leads to the last 4 digits solution 2017 - 85 = 1932


Is it possible to import header from file - nginx?

Question: Just started using my very first nginx server and I have added few header, but I was wondering, is it possible somehow to import those headers from different file?
Let,s say, I have a _headers file with such content:
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "SAME-ORIGIN";
add_header Feature-Policy "geolocation 'none'; microphone 'none';";

And can I somehow import it into my /etc/nginx/sites-available/example.com?
Answer: Well, this looks like this is a possible thing! I used "include" directive for that and it worked pretty good!
Found it here


Problemas com tipo de array?

Question: Estou tendo problemas na formulação de um gráfico.
Tenho basicamente 2 campos: categorias e dados. Dentro de categorias, as informações devem estar dispostas assim: ['categoria 1', 'categoria 2', 'etc'] entre aspas e separadas por vírgula. Já dentro de dados, as informações precisam vir assim: [dado 1, dado 2, dado 3] sem aspas.
Preciso pegar ambas informações (categorias e dados) de um select num banco de dados PostgreSQL, porém só obtenho sucesso no campo dados, visto que ele não vem nunca separado com aspas. Como posso formatar para incluir as aspas?
Esse é um exemplo de código para os dados:
$query="SELECT colunaa from minha tabela";
$output=pg_query($conn,$query);
    ?>
    [<?php while ($result = pg_fetch_array($output)) {?>
                      <?php echo $result["colunaa"]?>,

                    <?php } ?>]

Comment: Já tentou fazer `'',`
Answer: Você pode concatenar as aspas:
SELECT CONCAT('''', colunaa, '''') from minhatabela

Espero ter ajudado.
Comment: Obrigada! Funcionou. O problema agora é que no resultado ou o php põe uma vírgula a mais no final, ou não põe vírgula nenhuma.
Comment: Faça `$pulaVirgula = TRUE; echo '['; while ($result ... ) { if ($pulaVirgula) { $pulaVirgula = FALSE; } else { echo ',' } echo "'". $result['colunaa'] . "'"; } echo ']'`
Comment: Se você concatenar no banco de dados, vai criar uma carga desnecessária, num recurso que é não-escalável horizontalmente.
Comment: O código com $pulaVirgula retornou erro
Answer: Em PostgreSQL você pode fazer algo como:
CREATE TABLE tb_cores
(
    id INTEGER NOT NULL PRIMARY KEY,
    nome TEXT NOT NULL
);

INSERT INTO tb_cores ( id, nome ) VALUES ( 1, 'PRETO' );
INSERT INTO tb_cores ( id, nome ) VALUES ( 2, 'BRANCO' );
INSERT INTO tb_cores ( id, nome ) VALUES ( 3, 'VERMELHO' );
INSERT INTO tb_cores ( id, nome ) VALUES ( 4, 'VERDE' );
INSERT INTO tb_cores ( id, nome ) VALUES ( 5, 'AZUL' );

1) COM Agregação (separado por vírgulas):
SELECT string_agg( nome, ',' ) FROM tb_cores;

Saída:
|                       string_agg |
|----------------------------------|
| PRETO,BRANCO,VERMELHO,VERDE,AZUL |

2) COM Agregação (com aspas e separado por vírgulas):
SELECT CONCAT( $$'$$, string_agg( nome, $$','$$ ), $$'$$ ) FROM tb_cores;

Saída:
|                                     concat |
|--------------------------------------------|
| 'PRETO','BRANCO','VERMELHO','VERDE','AZUL' |

3) SEM agregação, somente aspas:
SELECT CONCAT( $$'$$, nome, $$'$$ ) FROM tb_cores;

Saída:
|     concat |
|------------|
|    'PRETO' |
|   'BRANCO' |
| 'VERMELHO' |
|    'VERDE' |
|     'AZUL' |

SQLFiddle

Problemas com tipo de array?


DBD::SQLite::db commit failed: disk I/O error

Question: I have a system writing data to an sqlite file. I had everything operational under CentOS 8. After upgrading the system to Rocky Linux 9 I see this error when running a commit command: DBD::SQLite::db commit failed: disk I/O error
I have checked file permissions, disk space, SMART readings, everything disk related that I can think of but without success.
Has anyone encountered this error before? What could I try to fix it?
Comment: Have you updated your Perl libraries, too?
Comment: Can you write to the sqlite file directly?
Comment: I have updated Perl with the system updated and I installed all the modules I am using. I can write to the sqlite file directly...
Answer: The problem turned out to be a missing Perl module (LWP::https) that was causing DBD::SQLite not to get the data it wanted. Apparently, DBD::SQLite says Disk I/O error for that case.


Application of the implicit function to the unit matrix

Question: The task is to show that there's such environment $U \subset \mathbb{R}^{n,n}$ in the surroundings of unit matrix $I_n$ that for any $X\in U$ there can be found a matrix $Y\in \mathbb{R}^{n,n}$ that satisfies $X^{p}=Y^{q}$ ($q,p\in \mathbb{N}$ here)
Now we have to prove this one by using the implicit function theorem and I have no clue how to identify some "matrix building function" with a map $ \mathbb{R}^n×\mathbb{R}^m \mapsto \mathbb{R}^m$ which is required for the theorem to be applied. I tried but I cannot seem to get the dimensions to correspond with the theorem.
Id be grateful for any hint)
Answer: Hint: Let $f: \Bbb R^{n \times n} \times \Bbb R^{n \times n} \to \Bbb R^{n \times n}$ be the map defined by
$$
f(X,Y) = X^p - Y^q.
$$
We wish to prove that there is a function $g$ such that $Y = g(X)$ is a matrix for which $f(X,Y) = 0$ whenever $X$ in some neighborhood of $I$. Begin by noting that $F(I,I) = 0$.

Regarding the invertibility of the derivative requirement: recall that the derivative of $f$ with respect to $Y$ must be invertible. Computing and considering the derivative of a function with matrix inputs is tricky. One approach is as follows: expanding $f(I,I+H)$ yields
$$
f(X,Y+H) = I^p - (I + H)^q =\\
I - I-\binom q1 H^1 - \binom q2 H^2 - \cdots =
-qH + o(H).
$$
Thus, the derivative $D_Y f(X,Y)$ at the point $X = I, Y = I$ is the linear map
$$
D_Y f(X,Y)(H) = -qH.
$$
This linear map is inverible.
Comment: It is obviously not true that $f(X,Y) = 0$ for all choices of $X,Y$. Analogously, if we wanted to show the existence of the function $g(x) = \sqrt{x}$, we would consider the function $f(x,y) = x - y^2$, but it is obviously not true that $f(x,y) = 0$ for all choices of $x,y$.
Comment: Dont we have to prove first $f(X,Y)=0$ for whatever X,Y und that $Df(X,Y)$ is reversible? Im really confused here
Comment: @piercetodsteltzer Also, what do you mean by $Df(X,Y)$? Please be more precise.
Comment: Sorry, it was dumb phrased cuz I didn't really know what I was saying. Im just uncertain where to start. We want to show there's such $g $ that $g(X)=Y$ if X is in neighbourhood $U\subset \mathbb{R}^n$ of $I_n$. For that must be valid $f(X_0,Y_0)=0$ and $D_{Y}f(X_0,Y_0)$ should be invertible. Since $X\subset U$ we put $I_n$ in $f$. If $f(I_n,Y_0)=0$ is to be , then $Y_0=I_n$ is the only choice. Then $D_{Y}f(X_0,Y_0)=-q{I_n}^{q-1}$  is obviously invertible but now Y must also be in $I_n$ neighbourhood, whereas we have to prove the statement for $Y\subset \mathbb{R}^n$
Comment: $X_0,Y_0$ are matrices in neighbourhood of which we look for X,Y with $X^p=Y^q$(☆). So $X_0=I_n$ but Im not sure about $Y_0$ since $Y$ has to be just some random matrix from $\mathbb{R}^n$ that satisfies (☆). But according to the theorem there must be some neighbourhood of $Y_0$ ,so ...
Comment: It is incorrect to say that $D_Yf(X_0,Y_0) = -q I_n^{q-1}$. In particular, it doesn't make sense to say that $D_Yf(X_0,Y_0)$ is a matrix whose size is the same as that of $Y$.
Comment: Also, I'm not sure what you're trying to say about $Y$. I suggest that you review what exactly the implicit function theorem says.
Comment: @piercetodsteltzer Also, it would probably be easier to add any followup questions to your original post instead of trying to type everything out in the comments here


To many arguments for public fun Fragment.findNavController()

Question: import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.drawerlayout.widget.DrawerLayout
import com.example.tender.R
import com.example.tender.databinding.FragmentAvailableTenderBinding
import com.example.tender.databinding.FragmentLoginBinding
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.NavigationUI

/**
 * A simple [Fragment] subclass.
 */
class AvailableTenderFragment : Fragment() {

    private lateinit var drawerLayout: DrawerLayout

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val binding = FragmentAvailableTenderBinding.inflate(inflater)

        drawerLayout = binding.drawerLayout

        **val navController = this.findNavController(R.id.nav_host_fragment)**

        **NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)**

        NavigationUI.setupWithNavController(binding.navView, navController)

        binding.root

    }
}

"To many arguments for public fun Fragment.findNavController():NAvcontroller defined in androidx.navigation.fragment" is showing when i hover on findnavcontroller.I am unable to resolve the error on the above bold lines.In this case what should I do?
Comment: `findNavController(R.id.nav_host_fragment)` and `setupActionBarWithNavController` are methods you'd call in your Activity, not in a Fragment. Can you explain the setup of your app?
Comment: Thank You for answering! Ohh! yes I wrote It on wrong place, it is helpful for me .
Answer: As per the Navigate to a destination documentation, the androidx.navigation.fragment.findNavController you've imported takes no parameters (it finds the parent NavHostFragment of the current Fragment and doesn't need the ID of the NavHostFragment).
The lines you've written, namely findNavController(R.id.nav_host_fragment) and setupActionBarWithNavController() are methods you'd call in an Activity, not in a Fragment.
Comment: If this helped answer your question, make sure to accept the answer to remove this question from the queue of unanswered questions. Best of luck going forward!
Comment: This is quite confusing, why :
`val navController = findNavController()`
`bottomNavigation.setupWithNavController(navController)`

Does not work inside the `onActivityCreated()` of a fragment that has a navHost?


github error: insufficient permission for adding an object to repository database

Question: When I run these commands from my App folder:
git add .
git commit -m "commit details"
git push

I get the error:
mycompaq@ubuntu:~/myapp$ git add .
error: insufficient permission for adding an object to repository database .git/objects

error: app/views/reviews/update.js.erb: failed to insert into database
error: unable to index file app/views/reviews/update.js.erb
fatal: updating files failed
mycompaq@ubuntu:~/myapp$

I tried this command:
chown -R user:user /project/directory

But seeing as I got in a whole load of trouble in the first place by running commands I wasn't sure about, I want to know if this is the correct solution.
What should the exact syntax be, if the user is 'Christophe', and the folder where my Rails app is stored is called 'myapp'. I mean should it be
chown -R user:christophe /myapp/app/views/reviews/update.js.erb

Answer: You accidentally committed a file or folder to git using elevated permissions and now git can't modify those objects.   It is safe to recursively force ownership of all files under .git/objects/ to your current user to clear the problem.

Make sure you're inside the repository where you're getting the error.

Get your username by typing
whoami

Enter this command
sudo chown -R your_user_name .git/*

Finally
git add .
Answer: chown [ -f ] [ -h ] [ -R ] Owner [ :Group ] { File ... | Directory ... }

From the man page

The chown command changes the owner of the file specified by the File
  parameter to the user specified by the Owner parameter. The value
  of the Owner parameter can be a user ID or a login name found in the
  /etc/passwd file. Optionally, a group can also be specified. The value
  of the Group parameter can be a group ID or a group name found in
  the /etc/group file.

About the -R option

-R
  Descends directories recursively, changing the ownership for each
  file. When a symbolic link is encountered and the link points to a
  directory, the ownership of that directory is changed but the directory
  is not further transversed.

So
chown -R user:christophe /myapp/app/views/reviews/update.js.erb

Would change the owner of the update.js.erb file to the user user in the group christophe, which is probably not what you want.
In your case changing the owner of the repo to yourself, i.e.
sudo chown -R christophe /path/to/your/local/repo

should suffice.
If you don't know your user name, you can find it out with the whoami command.
Comment: I tried 'chown -R christophe /myapp', and also 'Christophe1' (my github user name) but I keep getting 'chown: invalid user: `Christophe1' Probably a dumb question, but how can I find out what 'user' should be ? It is my machine, afterall, and my name is Christophe!
Comment: Cool, nice one. I'll take a note of that. But when I run 'chown -R christophecompaq myapp' I get a load of 'Operation not permitted' messages. And then git add . gives me the original error.Thanks for ur description of chown and 'R though.
Comment: `sudo chown -R christophecompaq myapp`
Comment: Hey, nice! I edited your answer to include some of these comments, if you don;t mind - to make it easier for others.
Comment: I integrated your suggestion, glad you have solved in any case.
Answer: You can give access to all the files in .git/ folder. Just run the following command:
sudo chmod a+xrw .git/*


Plotting data on a map in matlab

Question: I am using MATLAB R2015a. I have defined a grid which is basically a matrix that stores the latitudes of the grid points in the first column and the longitudes of the grid points in the second column I have some data for energy of an earthquake for a region stored in a column vector where each element corresponds to the energy at the corresponding grid point. I have done a surface plot using this code (here e_lat and e_long are the first and second columns of the grid matrix respectively):-
function [b] = cumulative_plot( beam, e_lat,e_long, t_start, t_end)
%CUMULATIVE_PLOT Plots the cumulative energy of the earthquake
%% Input Arguments
% *beam* - Energy for each time increment (columns) for each grid point (rows)
%
% *e_lat* - Vector containing Latitudes of the grid points
%
% *e_long* - Vector containing Longitudes of the grid points
%
% *t_start* - starting time
%
% *t_end* - ending time
%
% *t_start* and *t_end* define the time window within which the energy is
% to be considered

%% Code

b = [];
b = sum(beam(:,t_start:t_end)')'; % Adding the energy within the time window
b = b./max(b); % Normalising

fn = 'cumulative_energy.txt';
f = fopen(fn,'w');

for i=1:length(e_lat)
    fprintf(f,'%f %f %f \n',e_long(i),e_lat(i),b(i));
end

fclose(f);

energy_surf = fit([e_long,e_lat],b, 'loess');
plot(energy_surf,'style','contour');
hold on;
plot3(73.6400 ,34.5239 ,20,'s','MarkerSize',20,'MarkerEdgeColor','k','MarkerFaceColor','k')
hold on;
plot3(94.709,23.03,20,'s','MarkerSize',20,'MarkerEdgeColor','b','MarkerFaceColor','b')
shading interp
alpha(1)
view(0,90)
box off
colorbar
title(['Cumu Energy(0.05 - 0.2 Hz) at seconds = ' num2str(t_start )],'FontWeight','bold','FontSize',15,'FontName','Times');
xlabel('Long/degree','FontWeight','bold','FontSize',13,'FontName','Times');
ylabel('Lat/degree','FontWeight','bold','FontSize',13,'FontName','Times');

end

This is an example (the actual data that I am processing):-
cumulative_plot(b_corr,e_lat,e_long,1,20);

I want to make a contour plot of this energy data on a geographic map of the region specified. Is this possible?
To give a better idea, this is what I have right now :-

And this is kind of what I want to achieve (without the purple circular markers and other things. Just the base energy) :-
Comment: I was thinking on your problem and it might be possible make such a plot without the mapping toolbox if you provide with the topological data to plot. Or know a service that can provide this information easily in a Matlab readable format.
Comment: Oh I see, I deleted my answer because I see how it didn't answer your question. For what you want I think you could check the mapping toolbox https://www.mathworks.com/help/map/index.html , but I don't have it, so I can't help you further, sorry.
Comment: Sure, thanks. This plot has been done in GMT after processing the data in matlab. I wanted to do the whole work in matlab. Sadly my supervisor won't give me extra time to learn the toolbox.
Comment: Yes that is a good idea
Answer: If you have the bmp image of the mountain details, save the data in RGB format, and mix it with the data of the cumulative energy scale by its intensity. Intensity provide the alpha blending value.
Comment: Actually I wanted this to be as generic as possible. To get a BMP of the regions topography, I would still have to use other mapping tools. I was hoping to do all the work in MATLAB using the provided toolboxes.
Comment: You want basically to do an image overlay, the background is the geographic map, which should be an image, for example from google or other source. The overlay is your data contour plot, which you will use alpha bending to show it in transpency ...

Plotting data on a map in matlab


Weird file reading behavior

Question: apparently I have a file .txt extension which only has some links like:

a .txt file saved with this line yield:
(function (exports, require, module, __filename, __dirname) {
 <a href="ht
                                                              ^
SyntaxError: Unexpected token <

how does one read a file with such characters?
the code is:
const
    fs = require("fs"),
    txtFile = require("./txt.txt"),
    readStream = fs.createReadStream(txtFile);

readStream.on('readable', function () {
    console.log(readStream.read());
});

Comment: please show your node code. did you try to read it with `require`?
Comment: @DanielA.White added
Answer: Don't pass the file name to require. That's for code modules, not reading any other files.
Just pass the file name to createReadStream.
readStream = require("stream").createReadStream("./txt.txt");

Weird file reading behavior


Python find root for non-zero level

Question: Say I have the following code
def myfunc(x):
    return monsterMathExpressionOf(x)

and I would like to find numerically the solution of myfunc(x) == y for diverse values of y. If y == 0 then there are a lot of root finding procedures available, e.g. from scipy. However, if I'd like to find the solution for e.g. y==1 it seems I have to define a new function
def myfunc1(x):
    return myfunc(x) - 1

and then find it's root using available procedures. This way does not work for me as I will need to find a lot of solution by running a loop, and I don't want to redefine the function in each step of the loop. Is there  a neater solution?
Answer: You don't have to redefine a function for every value of y: just define a single function of y that returns a function of x, and use that function inside your loop:
def wrapper(y):
    def myfunc(x):
        return monsterMathExpressionOf(x) - y
    return myfunc

for y in y_values:
    f = wrapper(y)
    find_root(f, starting_point, ...)

You can also use functools.partial, which may be more to your liking:
def f(x, y):
    return monsterMathExpressionOf(x) - y

for y in y_values:
    g = partial(f, y=y)
    find_root(g, starting_point, ...)

Read the documentation to see how partial is roughly implemented behind the scenes; you'll see it may not be too different compared to the first wrapper implementation.
Comment: Thanks, but does not this essentially defines a new function `f` at each iteration of `for`? That is, each function for which I'd like to find a root I'll need to define using this wrapper?
Comment: Yes, because you're root finding function probably wants a function that only depends on `x`.
Comment: Is there  a way to define a function `f(x,y)` and then define `g` such that `g(x) = f(x,1)`?
Comment: That's pretty much what I have written above; it's just that your way of writing it down is mathematically better. But in code, you can't (some things/languages excepted) write `g(x) = f(x, 1)`; it just doesn't make sense. Instead, you write `g = f(1)` and the variable `x` is implicit.
Comment: Thanks, this indeed looks nicer
Answer: @Evert's answer shows how you can do this by using either a closure or by using functools.partial, which are both fine solutions.
Another alternative is provided by many numerical solvers.  Consider, for example, scipy.optimize.fsolve.  That function provides the args argument, which allows you to pass additional fixed arguments to the function to be solved.
For example, suppose myfunc is x**3 + x
def myfunc(x):
    return x**3 + x

Define one additional function that includes the parameter y as an argument:
def myfunc2(x, y):
    return myfunc(x) - y

To solve, say, myfunc(x) = 3, you can do this:
from scipy.optimize import fsolve

x0 = 1.0  # Initial guess

sol = fsolve(myfunc2, x0, args=(3,))

Instead of defining myfunc2, you could use an anonymous function as the first argument of fsolve:
sol = fsolve(lambda x, y: myfunc(x) - y, x0, args=(3,))

But then you could accomplish the same thing using
sol = fsolve(lambda x: myfunc(x) - 3, x0)

Python find root for non-zero level


Square-Connect Webhook PHP post no data

Question: I have Square-Connect Webhooks endabled.  I am receiving POST's to my server script.  Yet the $_POST array seems to be empty.
Here is my code:

<?php
  $sRM = $_SERVER['REQUEST_METHOD'] ;
  $sH = null ;

  if ( 'PUT' == $sRM )
  {
    $sH = file_get_contents( 'php://input' ) ;
  }
  else if ( 'POST' == $sRM )
  {
    $sS = '' ;

    foreach( $_POST as $sK => $sV )
    {
      $sH .= $sK.'=>'.$sV ;
      $sS = ', ' ;
    }
  }

  if ( ConnectDB() )
  {
    $_SESSION[ 'DB' ]->real_escape_string( trim( $sH ) ) ;  //  Prevent SQL Injection
    $rR = $_SESSION[ 'DB' ]->query( 'INSERT INTO `Hooks` ( `Method`,`Message` ) VALUES ( "'.$sRM.'", "'.$sH.'" ) ;' ) ;
  }
?>

Thanks,
Rob
Answer: The square docs state that the POST body will be in JSON format, so PHP will not parse it like a form and populate the $_POST array. You need to do something like this:
$json = file_get_contents('php://input');
$obj = json_decode($json);

as described in the answers to Reading JSON POST using PHP.
Comment: I had seen that piece about file_get_contents( `php://input' );
Comment: I had seen the reference... but it stated that the call would be of type "PUT".  When I saw that it was of type "POST"... I then processed it expecting name value pairs.

The file_get_contents('php://input'); worked.

Thank you!

Square-Connect Webhook PHP post no data


"Expected a list of items but got type \"dict\"."

Question: I am trying to build a api for updating first and last name for my user. I am getting the following error in HTTP Response
{
    "non_field_errors": [
        "Expected a list of items but got type \"dict\"."
    ]
}

I have written the following API and trying to pass the patch request to it.
class UserSelfUpdateView(UpdateAPIView):
    serializer_class = UserUpdateSerializer
    permission_classes = [UserPermissions, ]

    def update(self, request: Request, *args, **kwargs):
        instance = User.objects.filter(id=self.request.user.id)
        serializer = UserUpdateSerializer(instance, data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({'success': True}, status=status.HTTP_200_OK)

The serializer for the above request is:
class UserUpdateSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields: ('id', 'first_name', 'last_name')

The format in which I am trying to pass my request body is:
{
    "first_name": "A",
    "last_name": "B"
}

The reason for using

instance = User.objects.filter(id=self.request.user.id)

is because I want the functionality in a way that only logged in user is able to modify his details only.
Answer: The error is here
serializer = UserUpdateSerializer(instance, data=request.data, many=True)

change to
serializer = UserUpdateSerializer(instance, data=request.data)

if passing many=True you need to pass a queryset not an instance


$TS=0$ if and only if $T(v)=0$

Question: Please help me write down a step by step solution to this question:
Let $T$ be a linear transformation from $V$ to $V$. Prove that there exists a non-zero linear transformation from $S$ from $V$ to $V$ such that $TS=0$ if and only if there exists a non-zero vector $v\in V$ such that $T(v)=0$.
Assume $V$ is finite dimensional . If the infinite dimensional case can be proved well and good.
Comment: @Qwerty : as a convention, in maths the general case is *by default*, so you may want to edit your question to add this assumption for future readers : on this site you may ask questions for yourself first, but but it's good to think to future people with the same question as you. This way you'll get more upvotes :)
Comment: @JendrikStelzner  :I am getting an intuition that too vague. So Ii thought rather not to mention here. I need complete help. I am new to this topic.
Comment: Is $V$ finite dimensional? (Have you begun working in infinite-dimensional vector spaces or hilbert spaces?)  If so, then consider the matrix representations of $T$ and $v$ and construct the matrix $S$ to have every column equal to $v$.  What happens then to $TS$?
Comment: I guess there is some mistake in the statement since $T\equiv 0$ satisfies $TS=0$.
Comment: @Leandro no, $T=0$ is perfectly fine.  The only problem that could come from it is if $V=\{0\}$.
Comment: @JendrikStelzner : I have not started infinite dimensional spaces
Answer: Assuming $V$ is finite-dimensional
$\Rightarrow)$  Via contrapositive:
Suppose that there does not exist a nonzero vector $v$ such that $T(v)=0$.
This directly implies that $T$ is invertible.
Suppose also that $TS=0$.  Since $T$ is invertible we can left-multiply by $T^{-1}$ yielding $T^{-1}TS=S=T^{-1}0=0$ and that $S=0$.
This proves that in the case that $T(v)\neq 0$ for all $v\neq 0$ that there could not have been a nonzero $S$ such that $TS=0$.
By contraposition, that implies that if $TS=0$ for some nonzero $S$ that there exists a vector $v$ such that $T(v)=0$

$\Leftarrow)$ Directly:
Suppose $T(v)=0$ and $v\neq 0$.
Construct the transformation $S$ to be the transformation corresponding to the matrix with every column equal to the matrix representation of $v$.  (I.e. it is a projection onto the subspace spanned by $v$).
You have then $S\neq 0$ and $TS=0$.
Comment: @Tryss it is safe to assume based on the OP's comments that $V$ is finite-dimensional.  In many scenarios that one would be asked such a question it would be strictly before infinite dimensional spaces are introduced and there would be a footnote somewhere stating that every vector space is finite-dimensional unless specified otherwise, saving the need to specify it every time.
Comment: That's why I say "notice", and not "you're wrong". It was more a comment aimed to future readers that could have the same question but with infinite dimensional vector spaces (as nothing is explicitly said, ones could mistake it for a question about general case). But your small edit is all that was needed ;)
Answer: As the assumtion $V$ is finite dimensional was initially not specified in the question, here is idea of a possible proof in the infinite dimensional case :

Suppose there exists a non-zero vector $v \in V$ such that $T(v) = 0$.

Take $\{v\}$, and complete it to a basis $B$ of $V$.
For each $x$, it can be writen uniquely as
$$x = \lambda_v.v + \sum_{u \in J, J\subset B\backslash\{v\}, J \text{ finite}} \lambda_u . u$$
Now define $S$ as $S(x) = \lambda_v.v$.
It satisfy the hypothesis (it is in fact a projector).

Now, if there exists a non-zero $S$ such that $TS = 0$, just take a $v\in \text{Im}(S) \backslash \{0\}$ : you'll have $T(v)=0$

Notice that you need the axiom of choice for the first implication (not sure if it's possible without it, but I doubt it)
Comment: Nice one but I cant accept more than one answer. Sorry:-( @Tryss
Comment: @Qwerty : don't worry about it, you accepted a good answer and it's more than what does the average user here ;)
Comment: This is an off topic comment but I am tempted to ask : Are there users here those who accept bad answers leaving the good ones? @Tryss ?
Comment: @Qwerty : No, in general they don't accept anything even when there's perfectly fine answers that helped them. It's not uncommon to be the single answerer, and have no upvote, no downvote, no comment...
Comment: Such questions should be downvoted upon.. It demoralizes a novice answerer. Something about this should be done on meta.. @Tryss
Comment: @Qwerty Whether or not an answer is accepted has nothing to do if it is good.  That is why we have upvotes and downvotes.  You shouldn't downvote the question to punish the one who accepted the answer, as they chose based on personal choices.  Instead, downvote the answer so there are no bad answers in the first place

$TS=0$ if and only if $T(v)=0$