Keeping JS changes on DOM after refresh

Question: So, I have this weird thing going on in my test site, where I have every "link" (be it menu,button, or anything) to show/hide divs instead of loading pages. Pretty basic right? Except whenever I refresh the page, it all reverts back to the Homepage, which is expected. Based on my search for answers, I think I have to use the local/session storage option. Session sounds better.
So here's the deal. I looked up the w3schools page on sessionStorage and I get how it works, but I don't undestand how I could apply this to my page. Basically every link on my page runs a function that hides the previous div and shows a new one with the content. So I was thinking if every time a function triggered, it would store a value on a var that would appoint the function as the last used. Then somehow use sessionStorage and make it work, but I can't built it. Any help?
Here's a short example of my current code.
EDITED
var state = null;
function show1() {
    state = "home";
    "use strict";
    document.getElementById('snow').style.display = "block";
    document.getElementById('btn').style.display = "none";
}

function ramble() {
    state = "ramble";
    "use strict";
    document.getElementById('ramble').style.display = "block";
    document.getElementById('snow').style.display = "none";
    document.getElementById('tex').style.display = "none";
}

That's basically it.Onclick show/hide.
Comment: try saving it on localstorage
Comment: Can you show your HTML? Perhaps this is a more simple issue with something in there?
Comment: Based on what I've read, localstorage keeps changes after browser close and that's not something I want.
Comment: @AlexD I would but I'm currently on mobile and seems too much of a hustle to type the html, that's why I only gave some JS. I'll post some when I'm home if still needed.
Answer: You can use the following syntax:
Save data:
sessionStorage.setItem('key', 'value');

Retrieve data:
var data = sessionStorage.getItem('key');

More info and examples: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
The same goes with localStorage, but with the persistance differences you already found
Comment: Woops sorry I forgot to respond. Yeah I did manage to make it work but it got too complicated and I instead changed teh whole architecture to something more manageable. Thanks for the help though!
Comment: That link looks really helpful, practically answers  all of my questions. I'll give it a shot and report.
Comment: So I've add a state variable that changes everytime a function is triggered. I want to build an If that depending on the state value, changes whatever needs to be changed.  Now how do I build the sessionStorage statement? Do I need to build a function and then call it? Could you perhaps give me an example, just the base of it, using the edited code I've provided, without the actions that need to be done, I'll do that myself. If that's not too much to ask.
Comment: Wait I think I got this. -- Scratch that
Comment: @Blacksteel I'll wait haha
Answer: I hope my solution will help you: If you want to keep your JS changes, you need to save them to database using AJAX and also change page architecture and logic to use data from database. After that, even if you reload page you will keep all your changes.

Keeping JS changes on DOM after refresh


Modelling longitudinal data with crossed random effects

Question: Let's say I have 40 participants. They are each measured three times (session). On each visit they see ten stimuli (item), which can be one of two types (type). They then get some score for each stimuli. How could I model the effect of stimulus type, session number, and their interaction, with lme4?
I've included some example data, and my best guess at the model with the full random effects structure below.
library("lme4")

participant <- rep(1:40, each = 30)
session <- rep(rep(1:3, each = 10), times = 40)
item <- rep(1:10, times = 120)
type <- rep(1:2, times = 600)
score <- rnorm(1200)

data <- cbind(participant, session, item, type, score)
data <- as.data.frame(data)

data$participant <- factor(data$participant)
data$session <- factor(data$session)
data$item <- factor(data$item)
data$type <- factor(data$type)

m <- lmer(score ~ type * session + (1 + type | participant / session) +
                  (1 | item / session), data = data)

Comment: Why is `item` included as a random effect? Why is `session` included as both fixed and random?
Answer: First, note that the simulated data above results in a singular model fit because there is no variation in the response among any of the random factors.  This can be overcome with a simple modification:
library(lme4)

set.seed(15)
participant <- rep(1:40, each = 30)
session <- rep(rep(1:3, each = 10), times = 40)
item <- rep(1:10, times = 120)
type <- rep(1:2, times = 600)
# score <- rnorm(1200)                        ##### This line removed
score <- participant + item + rnorm(1200)     ##### This line added

data <- cbind(participant, session, item, type, score)
data <- as.data.frame(data)

data$participant <- factor(data$participant)
data$session <- factor(data$session)
data$item <- factor(data$item)
data$type <- factor(data$type)

m <- lmer(score ~ type * session + (1 + type | participant / session) +
              (1 | item / session), data = data)

Second, now note that the model m above does not converge. This is because the fixed effect session is also included as a random grouping factor, which does not make any sense. A more sensible alternative is:
m0 <- lmer(score ~ type * session + (1 | participant) + (1 | item), data = data)

where I have also removed the random slope/coefficient for type by participant which also does not make sense given that the data are simple random draws - that is, there is no systematic association of score and type for each participant.
> summary(m0)
Linear mixed model fit by REML ['lmerMod']
Formula: score ~ type * session + (1 | participant) + (1 | item)
   Data: data

REML criterion at convergence: 3828.3

Scaled residuals:
    Min      1Q  Median      3Q     Max
-4.2095 -0.6430  0.0437  0.6908  3.1569

Random effects:
 Groups      Name        Variance Std.Dev.
 participant (Intercept) 136.623  11.689
 item        (Intercept)   9.856   3.139
 Residual                  1.024   1.012
Number of obs: 1200, groups:  participant, 40; item, 10

Fixed effects:
                Estimate Std. Error t value
(Intercept)    25.557744   2.322048  11.007
type2           0.988240   1.988126   0.497
session2       -0.025759   0.101185  -0.255
session3       -0.042207   0.101185  -0.417
type2:session2 -0.028411   0.143098  -0.199
type2:session3 -0.002558   0.143098  -0.018

Correlation of Fixed Effects:
            (Intr) type2  sessn2 sessn3 typ2:2
type2       -0.428
session2    -0.022  0.025
session3    -0.022  0.025  0.500
type2:sssn2  0.015 -0.036 -0.707 -0.354
type2:sssn3  0.015 -0.036 -0.354 -0.707  0.500

This model estimates the fixed effect of stimulus type, session number, and their interaction, while controlling for crossed random effects for participant and item, as requested.
Random slopes for type, session and their interaction could potentially be included, provided that the data supports such a structure (the simulated data do not) and provided these are indicated by the underlying theory of the data generation process. It is not generally a good idea to begin with a maximal random effects structure.
Comment: @Dave, that's right, it is simply that in this (simulated) case it does not make sense to fit random slopes fro `Type`. With real data it very well might. As for nesting in `Participant`, I assume you are referring to `session`, which is a fixed effect, not random.
Comment: Hi Robert, thanks for the answer! Can you explain why having a subject slope for Type does not make sense? Doesn't it make sense to allow for the fact that the effect of Type might be different for each participant? Perhaps this was an issue with the simulated data, but imagine a study in which participants respond to either red or blue circles (making Type a colour factor), woudl it not make sense to allow for the effect of colour to vary by person?

Could you also elaborate on why nesting session in participant doesn't make sense?


Computing the integral using cauchy's theorem

Question: I need to integrate
$$\oint _{|z|=1} \frac {\sin z}{z}\, dz$$
I write $\sin z=z-\frac{z^3}{3!}+\frac{z^5}{5!}-...$, then I get by dividing by $x$, the series $1-\frac{z^2}{3!}+\frac{z^4}{5!}-...$. I am confused as to how to use this to integrate. What happens to $\frac{z^2}{3!}+\frac{z^4}{5!}-...$ now?
Thanks in advance!
Comment: By Cauchy's integral theorem wouldn't the integral be zero because the function is analytic in the region which the coutour belongs to?
Comment: If the integration contour is $|z|=1$, then the value is zero since $\frac{\sin z}{z}$ is analytic (with the removable discontinuity at $z=0$).
Comment: @Omnomnomnom I mean that the function $f(z) = \sin(z)/z$ is analytic everywhere inside and on the unit disk which is enclosed by the integration contour $|z| = 1$. So by the integral theorem the integral of $f(z)$ around $|z|=1$ has to be zero.
Comment: If this is on the real line then you are just integrating at -1 and 1, so the integral is zero. I assume this is a complex integral? If so, it's more customary to use $z$ than $x$.
Comment: yes I know I changed it to $x$ because that feels better. But you are right
Comment: @okrzysik it depends what you mean.  For example, $1/z$ is analytic in an open neighborhood of the contour.
Answer: We manage write the function $\frac{\sin z}{z}$ as a power series
$$
F(z) = 1-\frac{z^2}{3!}+\frac{z^4}{5!}-...,
$$
which converges in $\mathbb C$. That means $F(z)$ is analytic and by Cauchy's theorem
$$
\oint_{|z|=1}F(z)\, dz = 0.
$$

To be more formal note that $\frac{\sin z}{z} = F(z)$ when $z\in\mathbb C\setminus 0$, and, in particular when $|z|=1$. So
$$
\oint_{|z|=1}\frac{\sin z}{z}\, dz = \oint_{|z|=1}F(z)\, dz = 0.
$$
Answer: The function $f(z)=sin(z)$ is entire. In particular, it is analytic on the unit disk. By Cauchy's Formula, we have
$$
f(z_0)=\frac{1}{2\pi i}\int_{\|z\|=1}\frac{f(z)}{(z-z_0)}dz
$$
for any $z_0$ in the interior of the unit disk. Now apply this for a suitable choice of $z_0$.
Answer: Note that $\lim_{z \to 0} \frac{\sin z}{z} = 1$, and that the function
$$
f(z) = \begin{cases}
\sin z & z \neq 0 \\
1 & z = 0
\end{cases}
$$
is entire (that is, $\sin z/z$ has a removable discontinuity at $z = 0$).  Because $f$ is entire, we have
$$
\oint \frac{\sin z}{z}\,dz = \oint f(z)\,dz = 0
$$


How does the Cooley-Tukey-Algorithm work?

Question: I have tried to understand the Cooley Tukey Algorithm for some time. I read many articles and watched some videos like these:
https://www.youtube.com/watch?v=iTMn0Kt18tg
https://www.youtube.com/watch?v=h7apO7q16V0
https://www.youtube.com/watch?v=E8HeD-MUrjY
https://www.youtube.com/watch?v=mPVtovydY1k
(Source: YouTube)
First my background:
I know how the normal Fourier Transform, the DFT, Laplace and so on work.
I would be able to explain them to other people and have no problems with complex numbers.
I programmed the DFT many times and was able to program a Spectrum-Analyzer where you put in an audio file and it outputs a spectrogram. (Just by using DFT but very limited Frequency range) I use Python. Here is an example DFT in Python:
<code>import numpy
import matplotlib.pyplot

frequency = 4
samples_power = 6
f_min = 0
f_max = 10

samples = 2**samples_power
signal = numpy.sin(frequency*2*numpy.pi*numpy.linspace(0,1,samples))

f, t = numpy.meshgrid(numpy.linspace(f_min,f_max,samples) ,numpy.linspace(0,1,samples))
n = f*t

dft_matrix = 1/numpy.sqrt(numpy.shape(n)[0])*numpy.power(numpy.e,-2*numpy.pi*1j*n)

dft = numpy.sum(signal*dft_matrix,axis=1)
amplitude = numpy.abs(dft)
phase = numpy.arctan(dft.imag/dft.real)

matplotlib.pyplot.plot(numpy.linspace(f_min,f_max,samples),amplitude)
matplotlib.pyplot.xlabel("Frequency (Hz)")
matplotlib.pyplot.ylabel("Energy / Amplitude")
matplotlib.pyplot.show()
</code>
But this gets very slow very soon. I want to learn how the FFT works, so that I can use it.
What I know about it, that is has something to do with the "nth root of unity". And even and odd indexes are separated into two separate matrices. There are some redundancies in the DFT, if you analyze just integer frequencies. They are all at 0 in the middle. Even and odd frequencies also cross zero on different fractions. And the Cooley-Tukey-Algorithm/FFT makes use of it.
What I dont understand:
-the connection between all these things (zero points on different fractions, even and odd, nth root of unity ...)
-what seperating even and odd indexes does
-what axis is split into even and odd and what happens with the other because everyone seems only to be talking about one axis.
-what points are not used in the smaller matrices
-if the even and odd matrices are multiplied with the even and odd indexes of the signal
-what operations have to be done with the two resulting vectors to get the output
-what frequencies are used/allowed and if they have to be in a specific order
How does the Cooley Tukey Algorithm Work?
I need it explained in right order with logical connections and as much detail as possible (especially in Math).
I would appreciate it, if someone could do that. Thanks for the answers in advance!
Comment: Welcome to MSE! You seem to be asking a few questions, and it's preferable to ask one question at a time. By providing clarity, you help the potential responders to your question give you the best help you need. Please use the [meta read](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question) and enhance your question.
Comment: I will try it.  But it will take some time.
Comment: Is it better now? I changed the "many questions" into short explanation what I dont understand.
Answer: I think the FFT trick becomes obvious once you notice that the DFT of $x(n)1_{2|n}$ (setting to $0$ the odd samples, assuming the signal has even length $N$) is $\frac{X(k)+X(k+N/2)}2$, the DFT of $x(n)1_{2\ \nmid\ n}$ is $\frac{X(k)-X(k+N/2)}2$.
So we can compute the (length $N/2$) DFT of $x(2n)$ and $x(2n+1)$ separately and mix them at the end.
In practice it is a bit more complicated (when $N$ isn't a power of $2$, and there are also some optimizations to compute the $N$th roots of unity) but the idea is there.
Comment: can you help me understand this part? : x(k)+x(k+n/2)/2 or odd part. @reuns
Answer: I found a great Video on Youtube from a German University:
https://www.youtube.com/watch?v=HFlIIIi5cEM
(don't really need audio because the drawings are self-explaining, but you can use subtitles if you want)
And this lecture from Rensselaer Polytechnic Institute:
https://www.youtube.com/watch?v=1mVbZLHLaf0
(Source Youtube)
Now I know what the missing puzzle piece was. It is the "Twiddle Factors" or how you want to call them.
I didn't know three things:

Why you need them at all
Why they are power of $k$
What happens with the other side of the Matrix

The German guy explains it very good by drawing the DFT-Matrix.
Why do you need them?
-> Because you can just calculate the DFT of the even rows and by multiplying it with $W_N^k$ you get the odd rows for "free"
Why are they a Power of $k$?
-> The further right you look at the DFT-Matrix, the bigger the $W_N^{kn}$ gets, and the twiddle factors have to get bigger too
What about the other side?
-> In even row's the other side is the same, and in odd row's it's the opposite.
If you would calculate an $N=8$ Matrix this would mean that for as an example the first row (even, in the 8x8) you add samples 0 to 3 and 4 to 7 and then multiply the length-4 vector by the first row of the 4x4 Matrix and you have just calculated the first frequency. For the odd rows (in the 8x8), you would subtract samples 0 to 3 - 4 to 7 and multiply the resulting length-4 vector by the twiddle factors. Then multiply the vector by the first row of the 4x4 and suprise, you just got the the second frequency.
It is so easy, you just need the right teacher. And in the Internet it is really hard to find someone who's explaining something the way you understand it. Thankfully I did.


Javascript confusing order of execution

Question: I was playing around with reverse() to see how it works and came across this interaction that I can't understand at all. Here is the initial code:
let muhArray = [1,2,3,4,5];

let reversedArray = muhArray.reverse();

console.log(`muhArray: ${muhArray}`);

console.log(`reversedArray: ${reversedArray}`);

This returns:
muhArray: 5,4,3,2,1 (Original array changed as well)
reversedArray: 5,4,3,2,1
I figured that since reverse() reverses arrays in-place, even if it is an initilization, it changes the original muhArray anyways. So I created a copy(muhArrayCopy) to preserve the original array.
let muhArray = [1,2,3,4,5];

let muhArrayCopy = muhArray;

console.log(`muhArrayCopy: ${muhArrayCopy}`);

let reversedArray = muhArray.reverse();

console.log(`reversedArray: ${reversedArray}`);

This returns:
muhArrayCopy: 1,2,3,4,5
reversedArray: 5,4,3,2,1
Up until this point everything seems fine, but changing the order made me realise muhArray.reverse() affects already declared and initialized muhArrayCopy as well.
let muhArray = [1,2,3,4,5];

let muhArrayCopy = muhArray;

let reversedArray = muhArray.reverse();

console.log(`muhArrayCopy: ${muhArrayCopy}`);

console.log(`reversedArray: ${reversedArray}`);

Such order returns:
muhArrayCopy: 5,4,3,2,1
reversedArray: 5,4,3,2,1
Is this maybe a code execution order thing? I have read about hoisting but that does not seem to explain it, as far as I can understand. I am all new to programming so I have little to no knowledge about it.
Thanks in advance.
Comment: You could try and use the rest parameter by cloning the array instead of referring to it: `const muhArrayCopy = [...muhArray]`. Not 100% sure if that will work accordingly, but it's worth a try
Comment: It is because Javascript is [Object-oriented](https://en.wikipedia.org/wiki/Object-oriented_programming) so the copy of a variable will point to the
Comment: `let muhArrayCopy = muhArray;` does not create an actual copy of the array, it simply gives it "a second name", as non primitives are copied by reference. If you want to create a real copy that "lives" independently from the original array, you can use the spread operator (`let muhArrayCopy = [...muhArray];`) or any other suitable method that creates a new array (e.g. `let muhArrayCopy = muhArray.map(item => item;);` or `let muhArrayCopy = muhArray.slice();`, etc.)
Answer: There is nothing unexpected happening here.  In the first code snippet, you print the array copy before reversing the original array.  Keep in mind that the "copy" still points to the original array.  In the second snippet, you print the copy after reversing the original source.
Answer: js is call by reference, so
let muhArrayCopy = muhArray;

does not create a copy, it puts the reference of variable in the other one, so both are affected when something happens to the  other.

let muhArray = [1,2,3,4,5];

let muhArrayCopy = [...muhArray];

let reversedArray = muhArray.reverse();

console.log(`muhArrayCopy: ${muhArrayCopy}`);

console.log(`reversedArray: ${reversedArray}`);

this should solve it. here [...muhArray] we are creating a copy of the array.
Answer: [Array.prototype.reverse()][1] from definition The reverse() method reverses an array in place and returns the reference to the same array
So when you apply reverse to an array, it changes the parent array as well.
If you want to make your original array unchanged, you have to copy the original array to an another memory location and reverse it.
Assigning a variable to another will copy the memory location of the same variable. So what ever changes made to the existing variable will be reflected to the assigned variable as well
You should not copy the variable, instead you have to clone it and assign it to another variable. This can be done using Deep Copy and Shallow Copy
Read more about Deep Copy v/s Shallow Copy here
Since the variable here is an array, just clone it with Spread operator and reverse it.
Working Example

let muhArray = [1,2,3,4,5];

let muhArrayCopy = muhArray;

let reversedArray = [ ...muhArray ].reverse();

console.log(`muhArrayCopy: ${muhArrayCopy}`);

console.log(`reversedArray: ${reversedArray}`);

Javascript confusing order of execution


Using CultureAndRegionInfoBuilder to update built-in .Net culture

Question: I'm attempting to change the built in .Net culture fr-CA, using the following method:
    CultureAndRegionInfoBuilder cib = new CultureAndRegionInfoBuilder("fr-CA", CultureAndRegionModifiers.Replacement);

    try
    {
        Console.WriteLine("Updating " + cib.CultureName);

        cib.NumberFormat.CurrencyGroupSeparator = ",";
        cib.NumberFormat.CurrencyDecimalSeparator = ".";
        cib.NumberFormat.NumberGroupSeparator = ",";
        cib.NumberFormat.NumberDecimalSeparator = ".";

        cib.Register();

        Console.WriteLine("Culture updated.");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        Console.ReadKey();
    }

However, the Register() call fails with "System.InvalidOperationException: The 'Register' method failed because the custom culture 'fr-CA' already exists."
Is it possible to update the built-in culture?  According to the docs (http://msdn.microsoft.com/en-us/library/system.globalization.cultureandregioninfobuilder.cultureandregioninfobuilder.aspx), it looks like I can just update it, though I might be reading that wrong.
Comment: You may try the same code on other OS or another computer, just to check.

It might not be a good idea to edit existing cultures.
Comment: Is your process launched as administrator ? Vista or XP ?
Comment: Yes, launched as administrator (I received an access denied error if I didn't) -- this is running on Server 2008 sp1.
Answer: I just had to add:
CultureAndRegionInfoBuilder.UnRegister("fr-CA");

before Register().
Answer: You may be better to create a copy of an existing culture and Register it with a new name such as "fr-CACustom".
[Note that a custom culture can be registered on a computer only by a user who has administrative rights on that computer.]
try
{
    CultureAndRegionInfoBuilder cib = new CultureAndRegionInfoBuilder("fr-CACustom", CultureAndRegionModifiers.None);
    cib.LoadDataFromCultureInfo(new CultureInfo("fr-CA"));
    Console.WriteLine("Creating" + cib.CultureName);

    cib.NumberFormat.CurrencyGroupSeparator = ",";
    cib.NumberFormat.CurrencyDecimalSeparator = ".";
    cib.NumberFormat.NumberGroupSeparator = ",";
    cib.NumberFormat.NumberDecimalSeparator = ".";

    // add some region info also
    cib.LoadDataFromRegionInfo(new RegionInfo("CA"));
    cib.RegionEnglishName = "RegionInfo derived from French-speaking Canada";

    cib.Register();

    Console.WriteLine("New culture created.");
}
catch (Exception e)
{
    Console.WriteLine(e);
    Console.ReadKey();
}

This code registers the custom culture identified by the culture name in the %WINDIR%\Globalization system directory, where %WINDIR% is the Windows operating system directory. This will make the custom culture available to other applications.
CultureInfo test = new CultureInfo("fr-CACustom");

[Note: in order to have access to the CultureAndRegionInfoBuilder class you need a reference to the sysglobl assembly which is not reference by default in most Visual Studio project templates.]


Openvpn, two tap network adapters

Question: I have installed openvpn client on my pc (windows 7) and I have two tap network adapters. In this way I can open two openvpn connections at the same time. What I would like to understand is how it's decided each connection I open which tap adapter will be chosen. The first available network adapter is chosen or some other logic exists?
Answer: The OS will choose the route (and thus interface) with the lowest metric. To tweak which interface is used you can push a route with a particular metric; for example
<code>push route "10.10.10.0 255.255.255.0 10.0.0.2 1"
</code>
from the man page
<code>--route network/IP [netmask] [gateway] [metric]
</code>
Comment: And in the default case, with same metrics, i'm not sure which one wins. Maybe the first that appeared in the routing table.

Openvpn, two tap network adapters


How to setup a development server on Linux?

Question: I am developing a new web site for a client who is already on the web with an old site.
I need to develop the site under a different name (dns) and when it's ready, move it safely to a right name.
I am developing and hosting on AWS under Ubuntu using multi-site setup.
When I am ready I will pointing the DNS to my development server and by doing so I will be on air with the real site.
My question is: While developing I will be directing another domain to the development server say something like deveopment.com by the time I am ready to go live, I will be pointing the real domain to it, say real.com
Other than the dns' what else will I have to change on the server?
Will I have to change anything in the DB? Remember it's on the same server and I can use the same DB.
Am I likely to run into any trouble?
Comment: If your development server becomes the live (production) server itself, please take extra care for security considerations (eg other vhosts that may operate on dev, other services that run, OS updates etc.). Often dev servers tend to be more "relaxed" securiy-wise.
Answer: It should work with no or limited changes. However, some modules include fully qualified paths in database tables or variables, so it is worth checking.
Some areas to look at are:

settings.php, particularly the database array, $cookie_domain, and $base_url
The sites directory: are you using the default directory or one tied to your development environment? If your material is in sites/my.dev.com then you'll have my.dev.com in the files table
URL related modules like securepages, xmlsitemap, and so on

When I am moving from dev to production, I also use drush to double-check that I missed nothing. Running drush vget dumps the content of the variables table, so I can grep that for URLs. For example to see all the variables that have www.indiemade.com hardcoded:
$ drush vget | grep indiemade
securepages_basepath: 'http://www.indiemade.com'
securepages_basepath_ssl: 'https://www.indiemade.com'
seotools_base_url: 'https://www.indiemade.com'
xmlsitemap_base_url: 'http://www.indiemade.com'
...

One other tool you might want to look into is drush migrate, well explained here.
Answer: Normally not. If you are not using any special, domain related, modules (Mike domain access for example) you should be fine. Of course it is always a good idea to test it first(for example with a subdomain) to see  how the  site behaves on a new domain.


Pegar notícias por meio da URL

Question: Recentemente vi um vídeo no youtube, onde o cara por meio da URL de uma notícia que se encontrava no uol, globo e outros sites do tipo, ele recuperava o titulo da noticia, o corpo e as imagens junto com as formatações usada. A aplicação foi escrita com o framework LARAVEL.
Que tipo de recursos se utiliza para fazer uma aplicação dessa ? tem alguma biblioteca no LARAVEL que facilita isso ?
Comment: No laravel não sei, mas com `php`, através do `curl` ou `file_get_content` funciona
Comment: Qual vídeo?????
Answer: Para fazer isso você vai precisar inevitavelmente fazer um parsing do HTML da página. Você vai precisar usar um DOM parser para fazer isso.
O que o DOM Parser vai fazer é pegar o HTML que você baixou e transformar ele em um objeto DOM no qual você pode navegar e pegar as informações que você precisa.
Eu particularmente já fiz alguns projetos deste tipo, e os maiores problemas que você vai encontrar são basicamente dois:
1) Cada site (e as vezes diferentes sessões ou matérias do mesmo site) tem uma estrutura HTML diferente, fazendo com que você tenha que fazer diferentes mapas dom para cada sessão / site.
2) Os HTMLs dos sites (mesmo dos grandes como UOL, terra) têm htmls mal formatados, com erros. Isso pode eventualmente dar erro na hora de fazer o parse do dom, o que vai complicar sua vida.
O segredo é buscar um parser que faça um pré-processamento do html para corrigir erros, ou que seja tolerante aos erros.
Na última vez que trabalhei um projeto destes, fiz um robozinho com java, pois tem uma biblioteca pronta em Java que é perfeita para isso, que você consegue buscar os dados no HTML como se fosse o jquery. É muito legal!
https://jsoup.org/
Abraço e boa sorte!
Comment: Muito obrigado.

Pegar notícias por meio da URL


MySQL query to get sum of user and group by week

Question: I have two tables user_profile and tracked_search. The user_profile table has user details and tracked_search tracks search made by user.
Whenever a user makes a search this search entry goes in tracked_search table. If nothing is searched for a particular date nothing is added in tracked_search.
I need to develop a report where in I need to show data from last 6 months for every week
for example
Date       week_count   user_count
2017-05-01    18           10
2017-05-08    19           50
    .
    .
2017-07-03   27            80
    .
2017-10-2    40           20
   .
   .
2017-10-23   43           40

the data should be grouped by week and user_count is number of distinct user who made search for that week.
even if there is no data for a particular week it should print the week date, week count and user count as 0
my tables as follows
User_profile
user_id  user_name user_emailId        user_passsword   user_role creation_date
  1        Mac       email@example.com      password123       USER     23/10/2017
  2        Shane     email@example.com    password123       USER     23/10/2017

  Tracked_search
  id      created             content  search_term,  user_id
014af54e 2017-10-15 18:36:49  ARTICLE     latest       1
08f55f2d 2017-10-18 18:34:04  EVENT       upcoming     1
1e74f026 2017-10-25 18:37:11  DISCUSSION  newest       2
20075e4a 2017-10-22 18:35:41  ARTICLE    latest        1
22cde973 2017-10-17 18:36:49  ARTICLE     latest       2
2d1d3314 2017-10-16 18:36:49  ARTICLE     latest       2

Comment: I think I just saw you post this as an R question, but that aside, you need to show us at least your table structure, ideally some sample data which generates that output.
Comment: in user_profile  table i have only user details and user_id, while in tracked_search i have  id, user_id, date and what thing he searched ie a string
Comment: @Suyash, please update your question accordingly, with the actual column names so people can help you with your query. Also, please include what you have tried so far.
Comment: @kchason i have updated my question plz check
Comment: Two thoughts not directly related to the question: 1) You should be extremely wary of storing a plain-text password. It should ideally be hashed with something better than MD5 or SHA1, and salted. 2) There are several definitions of a week. See here: [WEEK()](https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_week) and [YEARWEEK()](https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_yearweek)
Comment: hi wodin this was just an example and i have actually hashed the password value. Thanks for suggestion though.
Answer: This is based on my answer to your other question:
Assuming week mode 3, since based on your question you seem to want weeks starting on a Monday. But perhaps you want mode 1, 5 or 7 instead (See WEEK()):
SELECT weeks.day, weeks.yearweek % 100 AS week, COUNT(DISTINCT ts.user_id) AS user_count
FROM (
    SELECT MIN(ADDDATE('1970-01-01', t4.i * 10000 + t3.i * 1000 + t2.i * 100 + t1.i * 10 + t0.i)) AS day,
           YEARWEEK(ADDDATE('1970-01-01', t4.i * 10000 + t3.i * 1000 + t2.i * 100 + t1.i * 10 + t0.i), 3) AS yearweek
    FROM (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS t0,
         (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS t1,
         (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS t2,
         (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS t3,
         (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS t4
    GROUP BY YEARWEEK(ADDDATE('1970-01-01', t4.i * 10000 + t3.i * 1000 + t2.i * 100 + t1.i * 10 + t0.i), 3)
) AS weeks
LEFT OUTER JOIN tracked_search AS ts
    ON weeks.yearweek = YEARWEEK(ts.created, 3)
WHERE weeks.day >= '2017-05-01'
AND weeks.day < '2017-10-30'
GROUP BY weeks.yearweek;

Using the sample data in your question it returns the following:
+------------+------+------------+
| day        | week | user_count |
+------------+------+------------+
| 2017-05-01 |   18 |          0 |
| 2017-05-08 |   19 |          0 |
| 2017-05-15 |   20 |          0 |
| 2017-05-22 |   21 |          0 |
| 2017-05-29 |   22 |          0 |
| 2017-06-05 |   23 |          0 |
| 2017-06-12 |   24 |          0 |
| 2017-06-19 |   25 |          0 |
| 2017-06-26 |   26 |          0 |
| 2017-07-03 |   27 |          0 |
| 2017-07-10 |   28 |          0 |
| 2017-07-17 |   29 |          0 |
| 2017-07-24 |   30 |          0 |
| 2017-07-31 |   31 |          0 |
| 2017-08-07 |   32 |          0 |
| 2017-08-14 |   33 |          0 |
| 2017-08-21 |   34 |          0 |
| 2017-08-28 |   35 |          0 |
| 2017-09-04 |   36 |          0 |
| 2017-09-11 |   37 |          0 |
| 2017-09-18 |   38 |          0 |
| 2017-09-25 |   39 |          0 |
| 2017-10-02 |   40 |          0 |
| 2017-10-09 |   41 |          1 |
| 2017-10-16 |   42 |          2 |
| 2017-10-23 |   43 |          1 |
+------------+------+------------+

Comment: @ Wodin in the count part it shows count of only current date and not for the full week
Comment: @Suyash no, if you look at the output for week 42 (starting 2017-10-16) it shows 2. This is from your data where you had two records for user_id 1 (on the 18th and 22nd) and 2 records for user_id 2 (on the 16th and 17th). So there was only 1 record on the 16th, but the user_count correctly shows 2, because there were two separate users who downloaded something during week 42 according to your sample data.
Answer: I was able to solve this using the following query. hope it will help someone
select
t1.attempt_date,
coalesce(SUM(t1.attempt_count+t2.attempt_count), 0) AS attempt_count
from
(
  select DATE_FORMAT(a.Date,'%Y/%m/%d') as attempt_date,
  '0' as  attempt_count
  from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
  ) a
  where a.Date BETWEEN NOW() - INTERVAL 6 MONTH AND NOW()
  group by SUBDATE(a.Date, WEEKDAY(a.Date - INTERVAL 1 day))
)t1
left join
(
  select count(t1.user_count) as attempt_count, t1.created_date FROM (select distinct ts.user_id as user_count, date(ts.created) as created_date from tracked_search ts
inner join user_profile up ON up.id = ts.user_id
group by ts.created
order by ts.created) t1
Group by SUBDATE(date(t1.created_date), WEEKDAY(date(t1.created_date)))
)t2
on t2.created_date = t1.attempt_date
group by DAY(t1.attempt_date)
order by t1.attempt_date desc;

Comment: Why do you `inner join user_profile...`? You do not use it in the query. Also, your query returns an attempt_count of 4 for the test data in your question. Your question said you needed the `number of distinct user who made search for that week`. There are only two distinct users in your test data, so 4 is obviously wrong. Also, your query returns 0 for every other week, whereas the weeks starting with dates `2017-10-09` and `2017-10-23` should each show 1, since according to your test data there was a record for user 1 on the 15th and one record for user 2 on the 25th.
Comment: Suyash your `t2` subquery is returning records for `2017-10-15`, `2017-10-16` and `2017-10-25` using the test data in your question. The `left join` causes the ones for `2017-10-15` and `2017-10-25` to be ignored because they are not Mondays and the `t1` subquery only has Mondays.


What will be the number of reachable states if Petri-Net model states are in loop

Question: If i have a Petri-net Model of 8 Places and 8 Transactions.There is not any dead state in this model because the token is in loop and going through all 8 places in first loop. In second and remaining loops it will go through 6 places because the token will come to  Place3 when T5 is executed. Here i want to know what will be the number of reachable states. Is Reachable states will infinite (because of the loop)  or what ?
Comment: Are `s1`,`s2`,`s3`, and `s4` indeed *states* of the model or *places* of the Petri net?
Answer: It's a little hard to answer without seeing the exact net, but assuming it's a simple loop with one token, then there are four states -- distinct labeling of the places with tokens -- that repeat infinitely.
Update
Aha! That's a whole 'nother kettle of fish.  Olay, so hand-simulate it. I did it by putting one finger on each token and following them. I'm going to name the places p_0 through P_7 by taking P_0 at top left and P_7 at bottom right, so the left column is P_0, P_1, P_2, the middle is P_3, P_4, the right P_5, P_6, P_7. So, we start with the labeled places as {P_0,P_7}.
Start:

{P_0, P_7}, T_1, T_6 fire.
{P_1, P_3} and T_1,T_4 fire.
{P_2, P_4} and T_2, T_5 fire and here's the kicker:
{P_2, P_3, P_5} now all have tokens. There is no pathway that "eats" tokens, no sinks, so every time P_4 gets a token, T_5 fires, and a new token appears in P_5. T_5 will be enabled infinitely often, the number of tokens grows by at least 1 every time, and so the reachability set is infinite.

This is a nice slide deck on Petri nets. http://www.labri.fr/perso/anca/FDS/Pn-ESTII.pdf
Answer: I think the number of "reachable states" of your net is infinite.
I took the liberty of creating an interactive PDF version of your diagram so that you can "manually" fire the transitions and see for your self the kind of markings the evolve from firing the enabled transitions.
An Interactive Version of Usman's Petri Net 1
Here is the link: https://www.academia.edu/34702296/An_Interactive_Version_of_Usmans_Petri_Net
Comment: Thanks for checking it out. I uploaded a copy of document to the following url: https://www.academia.edu/34702296/An_Interactive_Version_of_Usmans_Petri_Net. I will also change the original link from http://www.aespen.ca/AEnswers/1440257847.pdf to the new one. Thanks again.
Comment: The link is dead.


Objects are not valid as a React child (found: object with keys {id, name, price, description, quantity})

Question: I am creating an e-commerce kind of react project and getting the following error
i am getting an error while creating a react project

"Objects are not valid as a React child"

(found: object with keys {id, name, price, description, quantity}).
this error is occurring when i am passing "cartctx.additem(book)" in the button tag
import { Fragment, useContext, useEffect,useState } from "react";
import  {CartContext}  from "../context/cartcontext";
import './books.css';

function Books(){

    const cartctx=useContext(CartContext);

    const[books,setbooks]=useState([]);
    useEffect(()=>{
        async function FetchBooks(){
        const response=await fetch('my firebase database url');
        const data= await response.json();
        const loadedbooks=[];
        for(const key in data){
            loadedbooks.push({
                id:data[key].id,
                name:data[key].name,
                price:data[key].price,
                description:data[key].description
            })
        }
        setbooks(loadedbooks);
    }
    FetchBooks();
},[]);

return (

     {books.map((book)=>(

{book.name}

{book.price}

{book.description}

<button onClick={cartctx.additem(book)}>Add</button>

     ))}

);
}
export default Books;

following is the context component
import { React, useReducer,createContext } from "react";

export const CartContext =createContext({
    items:[],
    additem: (item) => { },
    removeitem: (id) => { }
});

function CartRuducer(state, action) {
    if (action.type === 'additem') {
        const existingitemindex = state.items.findIndex(
            (item) => item.id === action.item.id
        );

        const updateditems = [...state.items];
        if (existingitemindex > -1) {
            const updateditem = { ...state.items[existingitemindex],
                 quantity: state.items[existingitemindex].quantity + 1 };
            updateditems[existingitemindex] = updateditem;
        }

        else {
            updateditems.push({ ...action.item, quantity: 1 })
        }

        return { ...state, items:updateditems };

    }
    if (action.type === 'removeitem') {
        const existingitemindex = state.items.findIndex(
            (item) => item.id === action.item.id
        );
        const updateditems = [...state.items];
        const existingitem = state.items[existingitemindex]
        if (existingitem.quantity === 1) {
            updateditems = updateditems.splice(existingitemindex, 1);
        }
        else {
            const updateditem = { ...existingitem,
                 quantity: existingitem.quantity - 1 };
            updateditems[existingitemindex] = updateditem;
        }
        return { ...state, items:updateditems };
    }

    return state;
}

function CartContextProvider( {children}) {
    const [cart, dispatchfunction] = useReducer(CartRuducer, { items: [] });

    function additem(item) {
        dispatchfunction({ type: 'additem', item })

    };
    function removeitem(id) {
        dispatchfunction({ type: 'removeitem', id })
    };
    const Cartctx = {
        items: cart.items,
        additem,
        removeitem
    }

   console.log(Cartctx);

    return(
    <CartContext.Provider value={Cartctx}>{children}</CartContext.Provider>)
}
export default CartContextProvider;

i don't know where the problem is
Answer: you are directly invoking cartctx.additem(book) when rendering the component. The onClick attribute should be assigned a function, but you are executing the function immediately.
replace this line:-

<button onClick={cartctx.additem(book)}>Add</button>

with this line:-

<button onClick={() => cartctx.additem(book)}>Add</button>

Comment: Thanks this helped, I am getting my desired object in console but the error is still appearing when I click the "Add" button


Solutions of the functional equation $f(x+1)= xf(x)$

Question: I have come across a question of functional equation
$$f(x+1)= xf(x).$$
My question is how can we solve these type of functions. I have tried to use substitutions like $x= x-1$ and some manipulations but could't find the function. I also have tried to use differentiation's basic definition. I am still unable to solve the functional equation. Please try to clear my query.
Comment: This is the functional equation of the $\Gamma$ function (gamma function).
Answer: The first idea is always to plug in special values for $x$ - but what is "special" may depend on the functional equation. Here, $x=0$ suggests itself as it leads to $f(1)=0$. After that, one readily finds by induction that $f(x)=0$ for all $x\in\Bbb N$. Incidentally, the recursive nature of the functional equation allows us to describe the quite large set of solutions:
Let $g\colon[0,1)\to\Bbb R$ be an arbitrary function and define $f\colon \Bbb R\to \Bbb R$ recursively as
$$f(x)=\begin{cases}g(x)&0\le x<1\\
(x-1)(x-2)\cdots(x-\lfloor x\rfloor)\cdot g(x-\lfloor x\rfloor)&x\ge1\\
\frac{g(x+\lceil -x\rceil)}{x(x+1)\cdots (x+\lceil -x\rceil)}&x<0\end{cases} $$
Then $f$ solves the functional equation, and evey solution of the functional equation is of this form.
Answer: This can be seen as a first order recurrence relation, which can be recast to a first order difference equation by taking the logarithm.
$$f(x+1)=xf(x)$$
can be written
$$g(x+1)=g(x)+\log x.$$
The solution of such recurrences is made of the general solution of the homogeneous equation (obviously a constant), and a particular solution. In this particular case, we see that for integer $x$,
$$g(n)=\sum_{k=0}^{n-1}\log(k)+g(0)=\log((n-1)!)+g(0).$$
More generally, for real $x$,
$$g(x)=g(\lfloor x\rfloor+\{x\})=\sum_{k=0}^{\lfloor x\rfloor-1}\log(k+\{x\})+g(\{x\})$$
and
$$f(x)=\prod_{k=0}^{\lfloor x\rfloor-1}(k+\{x\})\,e^{g(\{x\})}=\frac{\Gamma(x)}{\Gamma(\{x\})}e^{g(\{x\})}=\frac{\Gamma(x)}{\Gamma(\{x\})}f(\{x\}).$$
Without more specification, $f$ is arbitrary on $[0,1)$ or any other unit interval.


Ao invés de mapas como utilizar um vetor de struct para o problema em C++?

Question: Primeiramente tenho uma struct
strcuct Ficha{

      int resgistro;
      float pontuacao;

 }Fichas[100];

é o seguinte vou ler de modo aleatório dados, mas um dado sempre na lista vai começar com o numero que não é inteiro ligado apontuação
0.5//pontuação
89933//registro
49494
0.4
87474
0.6
89044
88443
86965

O problema é o seguinte 0.5 é dos dois registro que vem em baixo, 0.4 é apenas 87474 e depois vem 0.6 que pertence ao registro que tiverem em baixo da pontuação essa é a lógica.
Bom como dados estão num arquivo txt
Leitura
void lerArquvivo(){
    ifstream Arquivo;
    Arquivo.open("Regeistro.txt");
    char linha[10];
    float n;
    while(Arquivo.getline(linha,10)){

        Arquivo >> n;

        separa(n);

        }
     Arquivo.close();
     }

Então crie uma função que separa inteiro de não inteiro.
void separa(floar valor){
    int x = valor;
    float y = valor;
         if(x==y){
            //cout<<"Inteiro"<<endl;
                           }else{
                      //cout<<"Não e Inteiro"<<endl;
                            }
                        }

Ai vem, como tenho que armazenar no vetor Fichas Fichas[i].registroe Fichas[i].pontuacao, eu não consigo fazer para armazenar nos números da posição do vetor relacionada.
Como exemplo do problema.
posição do vetor      registro     pontuação
     0                   0            0.5
     1                  89487          0
     2                  78474          0
     3                    0            0.4
     .
     .......

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54599/discussion-on-question-by-rodolfo-ao-inves-de-mapas-como-utilizar-um-vetor-de-st)
Answer: O que pode fazer para concluir a leitura é o seguinte:
#include <string>
#include <sstream>
#include <ifstream>

// ...

ifstream file("Registro.txt");
float pontuacao;
std::string line;
while (std::getline(file, line)) {
    if (line.find('.') != std::string::npos) { // Se contém um ponto, é float
        std::stringstream(line) >> pontuacao;
    } else {
        int registro;
        std::stringstream(line) >> registro;
        // Inserir (pontuacao, registro) na sua tabela
    }
}

Repare que aqui a pontuação é lida e persistida entre as linhas até que uma nova pontuação é encontrada. E quando um número de registro é lido, ele pareia com a pontuação mais recente lida.


Limitar caracters no tesseract portable

Question: Atualmente eu estou utilizando o tesseract portable integrado com java para poder identificar alguns caracteres, mas estou enfrentando alguns problemas como:
Alguns campos somente data como : 01/02/2013
Aparece algo assim: 0Il0S/S013
Só que não segue nenhum padrão. Alguém faz alguma ideia se tem como criar um dicionário padrão somente para caracteres como 0-9 e /?
Lembrando: Eu sei que existe para C, só que a versão portable ainda não encontrei.
Answer: Só tenho usado o tesseract em Linux, via linha de comando, ou em scripts que mandem
a linha de comando fazer o trabalho...
1) criar um ficheiro de configuração mydata com os caracteres válidos:
tessedit_char_whitelist 0123456789/-

2) depois invocar o tesseract como:
tesseract f.png zzz   mydata

produzindo zzz.txt só com digitos e '/' e '-'
Para bons resultados vale a pena investir na qualidade (resolução) da imagem inicial...
Se o âmbito for mais amplos provavelmente será util indicar a língua.
É natural que o interface Java, C, etc tenham funcionalidade para definir
as "whitelists".
Existe ainda a possibilidade de retreinar tesseracts (duvido que se justifique).

Limitar caracters no tesseract portable


Why is $\sup_{x\in X}\sup_{y:x = g(y)}f(y) = \sup_{x\in X}f(x)$

Question: Let $f$ be a function from $X$ to $\mathbb R$ and $g$ be a function from $X$ to $X$. Furthermore, define $h(x) = \sup_{y:x=g(y)}f(y)$.
Then it apparently holds that $$\sup_{x\in X}h(x) = \sup_{x\in X}\sup_{y:x=g(y)}f(y) = \sup_{x\in X}f(x)$$
This is used in the prove of the invariance property of MLEs (c.f. https://stats.stackexchange.com/questions/333737/maximum-likelihood-is-not-re-parametrization-invariant-so-how-can-one-justify-u). I don't understand why the second equality follows. My professor said it is "obvious", however, I don't see why.
Comment: $h(x)$ is defined only when $x$ is in the range of $g$. The question makes sense and it is correct if you assume that $g$ is surjective.
Answer: Kavi Rama Murthy's objection can be gotten around either by changing the statement to $$\sup_{x \in g(X)} h(x) = \sup_{x \in X} f(x)$$ or defining
$h : X \to \overline {\Bbb R}$, with $\sup_{x \in \emptyset} f(x) := -\infty$.
In either case, the statement is true.
Now let $M = \sup_{x\in X} f(x)$. For any $m < M$, there is a $y_m\in X$ with $f(y_m) > m$. Let $x = g(y_m)$. Then $h(x) \ge f(y_m) > m$. Therefore $\sup_{x \in X} h(x) > m$ for all $m < M$. Since $h(x) \le M$ for all $x$, we must have
$$\sup_{x \in X} h(x) = M$$


why after setting LD-LIBRARY_PATH and ld.so.cache properly, there are still library-finding problems?

Question: I have a certain shared object library in a special directory which I

make sure special directory is in $LD_LIBRARY_PATH
make sure this directory has read and execute permisions for all
make sure appropriate library directory is in ld.so.conf and that root has done a ldconfig
(verify by checking for library using ldconfig -p as normaluser.
make sure it is has no soname problems (i.e. create a few symlinks if necessary)

Now, say I compile a program that needs that special library, a program packaged in a  typical Open Source manner which ./configure && make, etc) and it says -lspecialibrary cannot be found, an error which a lack of any of the above checks would also probably throw.
A workaround I have done is to symlink the library to /usr/local/lib64 and suddenly the library has ben found. Also when compiling a relatively simple package, I manually add -L/path/to/spec/lib and that also has worked. But I regard those two methods as hacks, so I was looking for any clues as to why my list of checks aren't good enough to find a library.
(I particularly find the $LD_LIBRARY_PATH of shallow use. In fact I can exclude certain libraries from it, and they will still be found in a compilation process).
Answer: $LD_LIBRARY_PATH and ldconfig are only used to locate libraries when running programs that need libraries, i.e. they are used by the loader not the compiler. Your program depends on libspeciallibrary.so. When running your program $LD_LIBRARY_PATH and ldconfig are consulted to find libspeciallibary.so.
These methods are not used by your compiler to find libraries. For your compiler, the -L option is the right way to go. Since your package uses the autotools, you should set the $LDFLAGS environment variable:
LDFLAGS=-L/path/to/lib ./configure && make

This is also documented in the configure help:
./configure --help


How to send email via Gmail using Excel VBA? The message could not be sent to the SMPT server

Question: I found several variations to send email via Gmail in VBA and watched a YouTube demo using the sub below.
I tried smtpserverport 25 and 465.
I tried smtpserver smtp.gmail.com and smtp.office365.com.
I have the Microsoft CDO Reference selected.
I verified the Gmail password and get no error messages, no compile errors.
I call the sub from the main routine above via send_email_via_gmail. I added a Msgbox just past the send statement to make sure the sub is called and it does reach it but I never get the emails. I have O365.
Sub send_email_via_gmail()
Dim myMail As CDO.Message
Set myMail = New CDO.Message
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "firstname.lastname@example.com"
myMail.Configuration.fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "xxxxxxx"
myMail.Configuration.fields.Update
With myMail
.Subject = "Test email from Stock App"
.From = "email@example.com"
.To = "email@example.com"
.TextBody = "Test email from Me to Me"
End With
On Error Resume Next
myMail.Send
Set myMail = Nothing
End Sub

When I remove the On Error statement I do get a run-time error

The message could not be sent to the SMPT server. The transport error code was 0x80040217. The server response was not available.
Comment: Remove the `On error`-statement and see if an error occurs
Comment: The gmail SMTP server seems not to accept your mail. see https://stackoverflow.com/questions/9157087/getting-error-transport-error-code-was-0x80040217-while-sending-email-in-asp-net
Comment: When I remove the On Error statement I do get a run-time error stating "The message could not be sent to the SMPT server. The transport error code was 0x80040217. The server response was not available."
Comment: Thank you, that helped.  Now I need to decide if I really want to turn off 2-step verification and turn on Less Secure App Access.
Answer: Don't turn off 2-step verification ... create a custom gmail password for this app.
https://support.google.com/accounts/answer/185833?hl=en


Animação para diminuir o tamanho de um cubo no Unity

Question: Olá!
Estou no Unity usando C# e tenho um cubo que, quando eu aperto 'q', ele diminui pra 0.5 de escala partindo da escala 1 e quando eu solto o 'q', ele volta para a escala 1. Queria que houvesse alguma rápida animação do decrescimento e crescimento do cubo e pensei em fazer um For pra isso, estou certo? Há alguma função específica para isso?
Comment: inclua o seu código à pergunta
Answer: Usa o DOtween:
https://assetstore.unity.com/packages/tools/animation/dotween-hotween-v2-27676
<code>int duracao = 5;
    private void Update()
    {

        if (Input.GetKeyDown(KeyCode.Q))
        {
            gameObject.transform.DOScale( new Vector3(0.5f, 0.5f, 0.5f), duracao);
        }

        if (Input.GetKeyUp(KeyCode.Q))
        {
            gameObject.transform.DOScale(new Vector3(1, 1, 1), duracao);
        }
    }
</code>


How can I upgrade my processor from X3065 to X3220?

Question: I have a Dell Poweredge R200 server which has an ancient Xeon 3065 processor. I see in the servers specs that it can accommodate Xeon 3200 series, but not sure if I buy a bare-boned Xeon 3220 processor (without heatsink etc.) , will it fit easily on motherboard? If not, what exactly should I buy to upgrade my processor? Thanks
Answer: It will physically fit yes, they're both LGA775 chips but the 3220 has a TDP of nearly twice that of the 3065, you may have heat management issues that would affect the life of your server.
Comment: I see the point about TDP. What about X3320? I just bought a new X3320. I have no idea if it comes with a heatsink or not. Do you reckon it will fit on the server? and will have heat issues?
Comment: well the 3320 is only 95w so should be better than the 3220, how about an L3360? same TDP as your current chip, same socket - if your BIOS supports it then you should be just fine.
Answer: You wan a Dell #311-8328 CPU Upgrade kit. Doesn't void the warranty and comes with a properly sized heat sink (might be the same, might not).
Comment: So do you think buying a Dell upgrade kit the only safe way to do the upgrade? If not, what consideration should I have when I buy a CPU from elsewhere? thanks
Comment: I don't deal with "custom modified" servers much, as the warranty and support SLAs are typically well outside a normal business's requirements. Any X3220 processor should work; it would be the heatsink and any other parts that are included in the kit that you'd be missing (along with the warranty and support of course).


How to proxy context to different backend context in apache

Question: I'd like to configure apache so that http://my-domain.com/myapp serves a Python webapp running in CherryPy on a backend server.
Here's what's in the vhost:
    RewriteRule ^/myapp/?(.*) http://backend-server:8000/$1 [P]
    ProxyPassReverse /myapp/ http://backend-server:8000/

When I trace the request/response, I see:
GET /myapp HTTP/1.1
Host: my-domain.com

And then:
HTTP/1.1 303 See Other
Date: Thu, 15 Sep 2011 21:46:35 GMT
Server: CherryPy/3.1.2
Content-Type: text/html;charset=utf-8
Location: http://my-domain.com/somwhere-else/

As you can see, the CherryPy webapp sends a 303 redirect to /somewhere-else/
Any ideas why the Apache ProxyPassReverse doesn't transform the Location to http://my-domain.com/myapp/somewhere-else?
Answer: Your source location is /myapp, while your ProxyPassReverse is for /myapp/; context of the proxied location doesn't match, so the ProxyPassReverse doesn't apply.
Why the mod_rewrite proxy?  This should accomplish the same, and have no trailing slash consistency issues:
ProxyPass /myapp http://backend-server:8000
ProxyPassReverse /myapp http://backend-server:8000

Comment: Thanks much for the reply. I tried your suggestion, but, unfortunately, I'm seeing the same response. Perhaps I'm missing some other Apache directive? I'll keep digging....
Comment: @Dave CherryPy might be getting sensitive about the `Host:` header - try adding `ProxyPreserveHost on`.  Still, Apache should catch and translate that redirect, unless it doesn't think it should; is there anything different about the new URL versus the old?  Host name (is there a `www`?), port, protocol - any difference in these things to the original request will cause Apache to leave the `Location:` header alone.
Answer: I had same problem and fix it as follow:
For some reason both context path must be the same so, I mod my application context path to be the equal (note extra "/" on passResever)
    ProxyPass               /jira           http://192.168.1.30:8080/jira
    ProxyPassReverse        /jira/          http://192.168.1.30:8080/jira

Answer: The problem is that the backend app serves back a Location header with the public  name "my-domain.com", so ProxyPassReverse doesn't recognize it. The backend server should not know  the public name (frontend name), it should only know itself by the name "backend-server".


Word frequency counter for excel using Python

Question: I have the following python code to count the number of occurrences in an excel file. This is written to work even if a cell contains a sentence. However, for some reasons it's not working and I get TypeError: argument of type 'Cell' is not iterable.
Can someone help.
import xlrd
import os
for filename in os.listdir("D:\MyData\MyPythonCodes\Excel reading\search using xlrd"):
if filename.find('xlsx') != -1:
    print(filename)
    workbook = xlrd.open_workbook(filename)
    sheet = workbook.sheet_by_name("Sheet1")
    values = []
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            if " " in sheet.cell(row,col):
                values.append(str(sheet.cell(row,col).value.split(" ")))
            else:
                values.append(str(sheet.cell(row,col)))
print(values.count("abcd")) times")

Answer: you may need the following changes :
import xlrd
import os

for filename in os.listdir("D:\MyData\MyPythonCodes\Excel reading\search using xlrd"):
    if filename.find('xlsx') != -1:
        print(filename)
        workbook = xlrd.open_workbook(filename)
        sheet = workbook.sheet_by_name("Sheet1")
        values = []
        for row in range(sheet.nrows):
            for col in range(sheet.ncols):
                value = str(sheet.cell(row,col).value)
                if " " in value:
                    for word in value.split(" "):
                        values.append(word)
                else:
                    values.append(value)

        print("%s times" % values.count("abcd"))

Comment: Great! The good news is, it's not giving me any error. However, no matter what I have in my sheet, the counter returns 0 value.
Comment: sorry i didn't look at the last line. `str(value.split(' '))` will give you something like `"['abcd', 'abcd']"` , you want to delete the space and join the values or get the separate values in your list ?
Comment: Well. I just need the number of times abcd has occurred in my list.
Comment: so you need to loop on `value.split(' ')` instead of append `"['abcd', 'abcd']"` in the list `values`.  print your list to see what's inside, you will understand what's wrong
Comment: I am new to Python. It would be great if you could elaborate on the code.
Comment: print(value) returns "['abcd', 'abcd']" since I am using append. But not sure how to loop on value.spli(' ')
Comment: `values.count("abcd")` can only count the items in your list that match 'abcd', it cannot find the word 'hidden' in a sublist or a subchain. check the edit
Comment: Appreciate your help PRMoureu. But I am still unable to do so. Can you post the correct version of code if possible? I know it's a little more to ask. :)
Comment: what do you get with `print(values)` or `values.count("abcd")` ?
Comment: print(value) >> ["['Ritesh', 'a']", "text:'abcd'"]  print(value.count("abcd")) >> 0
Comment: i don't know what's inside your excel file but it's weird you get these results with the code i edited above, except for the ':' which is not handled
Comment: my excel cell contains only two entries, A1: Ritesh a and A2: abcd. It's just for testing. All I want to do is count the number of occurrences of a specific word in an excel file.
Comment: Awesome!! Now I understood how to use loop in this case. Many thanks.


How can I load a migration in a KernelTest?

Question: I'm trying to test a migration with a KernelTest, but I'm running into an issue when I try to load the migration plugin.
My migration is defined in my_module/migrations/my_migration.yml. In my KernelTest, I've listed my_module and migrate in the $modules static property.
In a custom form, I use the following to load a migration plugin:
/** @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface $plugin_manager */
$plugin_manager = \Drupal::service('plugin.manager.migration');
$migration = $plugin_manager
  ->createInstance('MY_MIGRATION');
// Next, create MigrateExecutable, etc...

However, when I use this same code in my KernelTest, $migration is always FALSE. I feel like this is because my migration is not loaded (?) when I enable my module in the test, but I'm not sure what to do about it. What am I missing here? How can I load my migration in the test?
Comment: I must've had something strange going on in my test class that caused that to fail.
Answer: The migrate module provides a base Kernel test class, Drupal\Tests\migrate\Kernel\MigrateTestBase, which has a getMigration() method baked in.
For example, this works and the test passes:
<?php

namespace Drupal\my_module\tests\Kernel;

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\Tests\migrate\Kernel\MigrateTestBase;

class MyMigrationTest extends MigrateTestBase {

  protected static $modules = [
    'my_module',
    'migrate',
    // etc...
  ];

  public function testMigration(): void {
    $migration = $this->getMigration('MY_MIGRATION');

    $this->assertInstanceOf(MigrationInterface::class, $migration);
  }

}

However, it's not necessary to extend MigrateTestBase, this also works and test passes:
<?php

namespace Drupal\my_module\tests\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\migrate\Plugin\MigrationInterface;

class MyMigrationTest extends KernelTestBase {

  protected static $modules = [
    'my_module',
    'migrate',
    // etc...
  ];

  public function testMigration(): void {
    /** @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface
    $plugin_manager */
    $plugin_manager = \Drupal::service('plugin.manager.migration');
    $migration = $plugin_manager
      ->createInstance('MY_MIGRATION');

    $this->assertInstanceOf(MigrationInterface::class, $migration);
  }

}


Document classification sample size

Question: I'm working on a document binary classification problem where I have a decent sized corpus of about 30,000 documents (600-1000 words each). My approach is to select a sample of documents and manually classify them, create a naive Bayes model, and apply it to the rest of the data.
The biggest question is how to determine the number of documents to manually classify. Are there any rules of thumb?
Comment: It depends, how many categories do you have ?
Comment: It's a binary problem so there are two.
Answer: There is no rule of thumb that I am aware of. But counting can provide some insight.
Calling :

$p$ the number of different words,
$l$ the number of words per document,

You would like your estimate of $P(X_i=1|word_j)$ to be evaluated many times (say 10). Indeed, this is what naive Bayes rely on to perform classification.
Therefore, you need about $10p$ observations. Each line brings you $l$ observations. Supposing you chose them as different as possible, you would like to have around $10p/l$ lines. In your case, this amounts to $p/100$.

Document classification sample size


MySQL UPDATE issue

Question: I've got an update statement that won't seem to work out for some reason.
else if (isset($_POST['save'])) {
  $query = "UPDATE assignments
               SET expdate = '$expdate',
                   dispdate = '$dispdate',
                   duedate = '$duedate',
                   name = '$name',
                   cat1 = '$cat1',
                   cat2 = '$cat2',
                   cat3 = '$cat3',
                   schoolid = '$schoolid',
                   classid = '$classid',
                   public = '$public',
                   tags = '$tags',
                   description = '$description',
                   symbol = '$symbol'
             WHERE id = '$assignmentid'
               AND teacherid = '$uid'";
  echo $query;
  mysql_query($query);
}

I've tried much but can't seem to get it to update the row. I know that the function is executing though because echo $query; outputs the query.
The specific string after variables are parsed is:
UPDATE assignments
   SET expdate = '1325401200',
       dispdate = '1293865200',
       duedate = '1325401200',
       name = 'Test 7',
       cat1 = '138',
       cat2 = '0',
       cat3 = '0',
       schoolid = '1',
       classid = '33',
       public = '1',
       tags = 'New Vista High School,,80302,Patrick,Turmala,Test 7,,,138,No sub-categories,No sub-categories,test7,2012,testNew Vista High School,,80302,Patrick,Turmala,Test 7,,,138,0,0,teste,2012,testes',
       description = 'Test 7',
       symbol='teste'
 WHERE id = '21'
   AND teacherid = '538'

Is it a syntax error? What is going on?
Thanks to anyone.
Comment: echo `mysql_error()` after `mysql_query()`. If it's a syntax error, it will become plain.
Comment: Are you sure the row has id of 21 and teacherid of 538?
Comment: Also, are your three date columns MySQL DATETIME types, or are they INTs accepting UNIX timestamps from PHP?
Comment: I assume is no records with id='21' AND teacherid='538' in `assignments` table
Answer: try to use
UPDATE assignments set `fieldname`= values where ...

and echo mysql_error to see the exception.
Answer: Mostly because there is Mysql Reserved Words in your query like public,
You should use ` to quote that.
Edit: public is not mysql reserved word, try mysql_error() to see the error msg.
Comment: `public` is not a reserved keyword: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
Answer: Can you let me know the error / exception what you are getting.
I thought of that there is a problem in length of the column. The length for column tags is too short to hold the given value.

MySQL UPDATE issue


MCEM algorithm in normal distribution

Question:
Consider $z_1,\ldots,z_n$ as a sample of observations of $Z$ and
  $y_1,\ldots,y_n$ the missing data,
where $Z\sim N(\mu,\sigma^2+1)$ and $Y\sim N(0,1)$.
i)Find the expression of $u_{p+1}$ and $\sigma^2_{p+1}$ given the
  current values $\mu_p$ and $\sigma^2_p$.
ii)Implement in R the EM algorithm for estimate $\mu$ and
  $\sigma^2$.Use as data a sample of $rnorm$

First I found that $Y\mid Z=z\sim N(\frac{z-\mu}{\sigma^2+1},\frac{\sigma^2}{\sigma^2+1})$. Then I found the likelihood
$$L\propto (\frac{\sigma^2+1}{\sigma^2})^{\frac{n}{2}}e^{-\frac{1}{2}\frac{\sigma^2+1}{\sigma^2}\sum(y-(\frac{z-\mu}{\sigma^2+1}))^2}$$
$$\log L=\frac{n}{2}\log(\sigma^2+1)-\frac{n}{2}\log(\sigma^2)-\frac{1}{2}\frac{\sigma^2+1}{\sigma^2}\sum (y-(\frac{z-\mu}{\sigma^2+1}))^2$$
So taking the derivative
$$\frac{\partial}{\partial\mu}\log L=-\frac{\sigma^2+1}{\sigma^2}\frac{1}{\sigma^2+1}\sum (y-\frac{z-\mu}{\sigma^2+1})=-\frac{1}{\sigma^2}(\sum y-\frac{nz}{\sigma^2+1}+\frac{n\mu}{\sigma^2+1})$$
developing this I get
$$\hat{\mu}=-(\sigma^2+1)\overline{Y}+z$$
This will be my $\mu_{p+1}$? I am studying through this book Casella.

THE EM Algorithm

Compute $Q(\theta\mid\hat{\theta}_{(m)},x)=E_{\hat{\theta}_{(m)}}[\log L^c(\theta\mid x,z)]$
  where the expectation is with respect to
  $k(z\mid\hat{\theta}_m,x)=\frac{f(x,z\mid\theta)}{g(x\mid\theta)}$
Maximize $Q(\theta\mid\hat{\theta}_{(m)},x)$ in $\theta$ and take $\theta_{(m+1)}=\operatorname{argmax}\limits_\theta$$Q(\theta\mid \hat{\theta}_{(m)},x)$

EDIT:
I think perhaps a mistake as I did, because if $\hat{\mu}$ is the $u_{p+1}$ it will not depending on the value of the previous iteration
EDIT2: I think there is no way to make the M step without using simulation, so confused with this topic, this would be a case of mixture of distributions, since Y and Z have different distributions?
Comment: You shouldln't write $Z$~$N$; rather the proper usage is $Z\sim N$, coded as Z\sim N. That gets you proper spacing and no mismatch in fonts.  Likewise \mid afford proper spacing in things like $\Pr(A\mid B)$ (as opposed to $\Pr(A|B)$, which is not correct usage).  I also changed $log L$ to $\log L$, coded as \log L.  That not only prevents italicization but also affords proper spacing in expressions like $a\log b$.  I also cleaned up your "argmax".  I await approval of the edits. ${}\qquad{}$
Comment: (But my edits have so far not address sizes of parentheses, e.g. $\displaystyle\left(\sum_{i=1}^n\frac{A_i}{B_i}\right)$ as opposed to $\displaystyle(\sum_{i=1}^n\frac{A_i}{B_i})$.  Just using \left( and \right) takes care of that.  I don't use \left( and \right) in things like f(x) since there's no size issue then and it makes the code cluttered.) ${}\qquad{}$
Comment: Also: _Why_ write "Where $Z\sim N(\mu,\sigma^2+1)$ and $Y\sim N(0,1)$." with a capital initial "W" as if it were the beginning of a new sentence??  I've seen that _only_ on the internet. I don't understand the appeal of such an absurdity. ${}\qquad{}$
Comment: @askazy : I'm quite rusty on EM algorithms, but I'll take a look.
Comment: I did some caculation, I think $\mu_{p+1}=\mu_{p}=\mu$ for any iteration for this case. I don't know how to solve the variance. Hope somebody else can solve.
Comment: @DeepNorth but how you get it?
Comment: I will show you the detail as how to get $\mu$ during weekend, but I may be wrong.I am also learning the EM algorithm.
Comment: @MichaelHardy You will give me some help on my problem?
Comment: Are you writing u for $\mu$? How does the distribution of a random vector follow a univariate gaussian? I think this question needs a bit of editing.
Comment: As I understand it, the monte carlo part of the MCEM is in the E step, not the M step. The M step is usually done with pen and paper.
Comment: @Taylor Really? How I can do it.
Comment: $Q(\theta, \hat{\theta})$, once you have a $\hat{\theta}$ is a function in $\theta$. Take the derivative and set it equal to zero.
Comment: @Taylor The problem is that I need to estimate $\mu$ and $\sigma^2$ and I think we can not solve the equation for $\sigma^2$
Answer: Ok, let me show  how I did it  for $\mu$, but if i am wrong, i hope someone can point out.
First let us compute the complete likelyhood (i.e the likelyhood for observed and missing together, or some people call it as augmented likelyhood).This is not difficult.
$L^c(\mu|z,y)\propto exp\left \{  -\frac{1}{2}[\sum_{i=1}^{n}(z_i-\mu)^2 +\sum_{i=1}^ny_{i}^2]\right \}$
$z_i$ is observed value with $ N(\mu,\sigma^2+1)$ distribution, here we suppose $\sigma $ is known. $y_i$ are missing values. We omitted all constants for the likelihood function.
Next we calculate the likelihood for the observed values.
$L(\mu|z)\propto exp\left \{  -\frac{1}{2}\sum_{i=1}^{n}(z_i-\mu)^2 \right \}$
The condition pdf of missing $y_i$ conditional on observed $z_i$ and $\mu$ is calculated by $L^c(\mu|z,Y)/L(\mu|z)$ which is: $exp(-\frac{1}{2}\sum_{i}^ny_i^2$). This is the product of i.i.d distribution of $N(0,1)$
It seems like we even don't need this step to show that missing values have a $N(0,1)$ distribution,
Anyway, now we know that conditional on observed $z_i$ and $\mu$, missing value $y_i$ has a $N(0,1)$ distribution.
Next step, we need to calculate the expected value of log likelihood of complete (or augmented) likelihood function conditional on an initially guessed $\mu_0$ and observed values $z_i$. i.e $E[logL^c(\mu|z,Y)|\mu_0,z]$
Further we can write this expectation as
$E\left \{-\frac{1}{2}[\sum_{i=1}^{n}(z_i-\mu)^2 +\sum_{i=1}^ny_{i}^2]|\mu_0,z\right \}$
Since $Z_i$ are all observed value. The expected value for $-\frac{1}{2}\sum_{i=1}^{n}(z_i-\mu)^2$ is just itself. i.e we treat the first part as constant.
So, for the second part we plug in an initial guess $\mu_0$, then we can use a condition we get before, i.e conditional on $\mu$ (here is $\mu_0$) and observed $z_i$, $Y$ has a $N(0,1)$ distribution.
So, $E \left \{ -\frac{1}{2}[\sum_{i=1}^ny_i^2]|\mu_0,z\right \}=E \left \{ -\frac{1}{2}[\sum_{i=1}^n(y_i-\mu_0+\mu_0)^2]|\mu_0,z\right \}=E \left \{ -\frac{1}{2}[\sum_{i=1}^n(y_i-\mu_0)^2+2\sum_{i=1}^n(y_i-\mu_0)\mu_0+\mu_0^2]|\mu_0,z\right \}=-\frac{1}{2}(n+\mu_0^2)$
Note $E(y_i-\mu_0)^2$ is the variance of $y_i$
and  $\sum_{i=1}^n(y_i-\mu_0)=0$
So the Expectation for the complete log likelihood
$E\left \{-\frac{1}{2}[\sum_{i=1}^{n}(z_i-\mu)^2 +\sum_{i=1}^ny_{i}^2]|\mu_0,z\right \}=-\frac{1}{2}[\sum_{i=1}^{n}(z_i-\mu)^2+n+\mu_0^2]$
Next take partial derivative of the expectation in term of $\mu$ and set it to zero
we get $\mu=\bar{z}$, we even don't need a initial $\mu_0$ for this case.
Anyway, I think I have not totally understand the EM algorithm yet,the solution might be totally wrong.

MCEM algorithm in normal distribution


Finding set of subsets satisfying certain properties

Question: I came across an interesting puzzle question that can be reduced to the following mathematical question.
Consider a set of seven elements $S=\{a, b, c, d, e, f, g\}$.
We want to construct a set of subsets of $S$ given a few conditions.
(1) For any two different elements in $S$, there is exactly one subset containing them.
(2) Any two distinct subsets $S_1, S_2$ of $S$ satisfy $S_1\cap S_2=\{x\}$ for some $x\in S$.
(3) The cardinality of the set of subsets is strictly less than $7$.
Also, we assume that $S$ contains at least four elements such that no three of them belong to the same subset.
The question is, does such a set of subsets exist?
I am having trouble getting an answer. Any help is appreciated.
Comment: @David not necessarily, surely? Considering condition (1) alone, $\{S\}$ satisfies it
Comment: I am not sure this is possible with condition (3) because condition (1) implies there must be at least 21 sets of subsets to allow for all possible pair combinations.
Comment: Yes. My mind slipped for a moment and thought I was restricted to subsets of cardinality 2.
Comment: @Shuri2060 Yes, elements
Comment: @MauroALLEGRANZA Yes but those four points have a condition on them
Comment: @David You can do it in much fewer than $21$.
Comment: do the x have to be unique if not:

$\{\{a,b\},\{c,b\},\{d,b\},\{e,b\},\{f,b\},\{g,b\}\}$ could work for 2 and 3 but not 1.
Comment: This is the 7 point Fano plane again only in another disguise (do link to your earlier question) or more correct the Fano plane is a form of this one
Answer: No, it's not possible (as Shuri2060 points out, having the whole of $S$ as a subset breaks the extra fourth rule).
First, suppose there is a subset of size $4$, say $\{a,b,c,d\}$. We must have other subsets which cover the eight pairs $a,f$, ..., $d,f$ and $a,g$, ..., $d,g$. Now no subset can cover more than two of these without having a pair in common with the first subset, and any subset which does cover two of these eight pairs must include $f$ and $g$, so at most one subset covers two of them. Thus there would have to be at least seven extra subsets to cover all these pairs. So we can't do it if any subset has size $4$. Exactly the same argument would apply if our starting subset was $\{a,b,c,d,e\}$ of size $5$. If we have a subset of size $6$ then there are $6$ other pairs to cover, and each other subset can cover at most one without covering a pair that's already done, so we need at least seven subsets in total.
On the other hand, if every subset has size at most $3$ then each subset covers at most three pairs, and there are $21$ pairs to cover, so at least $7$ subsets are required. (It is possible with exactly $7$ subsets of size $3$: take $abf$, $ace$, $adg$, $bcd$, $beg$, $cfg$, $def$. This construction is the Fano plane.)
Comment: mb about the earlier question - I see what you meant. It's possible with exactly 7, but the question requires it to be less than
Comment: Yes, and there's only one way to do it with exactly seven, because the construction with one set of size $6$ and six of size $2$ also doesn't satisfy the fourth rule.


Build a grid with time slots in multiple rooms

Question: I need to build a grid for one day (Feb. 27) that allows users to reserve time-slots. There are 12 1/2 slots with a limit of 8 bookings for each slot (in 8 different rooms). The users are authenticated...this is not open to the public.
I'm guessing this is possible with Calendar module and Jquery without having to install another module. Any ideas?

Drupal 7
Comment: Would Entity Registration work for this item?
Answer: The bat module - https://www.drupal.org/project/bat would work for this use case without any custom code required.


Optimal value in $\max_{x} \max_{y} f(x,y) = \max_{x,\ y} f(x,y)$

Question: I am trying to understand a few things about sequential and simultaneous optimization in [1]. In this post, it is shown that
$$\max_{x} \max_{y} f(x,y) = \max_{x,\ y} f(x,y).\tag{1}$$
Thanks to @Shiv Tavker comment, I understand that in order to get the optimal value $z^*=(x^*, y^*)$ in the RHS of $(1)$, we have to solve the system $\nabla_z f(z) = 0$ w.r.t. $z$, where $z = (x,y)$.
In addition, from the LHS of $(1)$ we have,
$${x^*}' = \arg \max_x f(x, y)\tag{2}$$ and $${y^*}' = \arg \max_y f({x^*}', y)\tag{3}.$$ Let ${z^*}' = ({x^*}', {y^*}')$.
As far as I understand, I think that given $(1)$, we can state that ${z^*}' \equiv {z^*}$. However, I am thinking if there are any cases that ${z^*}' \equiv {z^*}$ does not hold? Could you please someone give some comments or an answer of things are not so simple? Any help is highly appreciated.
EDIT1: Let $$\mathcal{f}(x, y) = -\frac{1}{2}\:\mathbf{z}^T \left(\mathbf{A} + \frac{xy}{2} \:\mathbf{I}\right)^{-1} \mathbf{z} - \frac{y}{6} \lambda - \frac{y}{12}x^3,$$ where $x\geq 0$, $y,\lambda > 0$, $\mathbf{A}$ a real symmetric positive semmi-definite, and $\mathbf{z}$ are fixed.
EDIT2: Let $\mathbf{t}(x,y) = - (\mathbf{A} + 0.5 x y\: \mathbf{I})^{-1} \mathbf{z}$. If we first solve $\partial_x f(x,y) = 0$ we get $$x = \| \mathbf{t}(x,y)\|\tag{4},$$ for $y >0$. Then, if we solve $\partial_y f(x,y) = 0$ and use $(4)$ we get $$\sqrt[3]{\lambda} = \| \mathbf{t}(x,y)\|.\tag{5}$$
Next, suppose that we first solve $x = \| \mathbf{t}(x,y)\|$ w.r.t. $x$ to get an optimal ${x^*}'$ and then solve $\sqrt[3]{\lambda} = \| \mathbf{t}({x^*}', y)\|$ w.r.t. $y$ to get ${y^*}'$. Can we say that ${z^*}' \equiv {z^*}$?
Comment: Yes, you can set the derivative to be zero for both of the variables simultaneously. Note that.. this is same as setting gradient, $\nabla f = 0$. However, beware you may end up in local optimas.
Comment: Do you mean: $${x^*}'(y) = \arg \max_x f(x, y)  \qquad (2)$$
$${y^*}' = \arg \max_y f({x^*}'(y), y) \qquad (3).$$
Let ${z^*}' = ({x^*}'({y^*}'), {y^*}')$.
Comment: @darkmoor I think you should go straight to the point (your $f(x, y)$) in the question.
Comment: What would $\max_y f(x,y)$ mean?
Comment: @RiverLi thanks for the interest. Yes this is my case. The solution ${x^*}'$ depends on $y$.
Comment: @RiverLi actually my equation is

 $$\mathcal{f}(x, y) = -\frac{1}{2}\:\mathbf{z}^T \left(\mathbf{A} + \frac{xy}{2} \:\mathbf{I}\right)^{-1} \mathbf{z} - \frac{y}{6} \lambda - \frac{y}{12}x^3,$$

where $\lambda$, $\mathbf{A}$, and $\mathbf{z}$ are fixed. I was hopping for a more general question that is why I didn't mention it in the main post. Any help is highly appreciated.
Comment: @darkmoor Is $A$ real symmetric positive definite? Is $\lambda > 0$? Is the domain is $(0, \infty)^2$? Do you want to solve the optimization problem, or want to analyze if ${z^*}' \equiv {z^*}$ as you said in the question?
Comment: @RiverLi thanks again for the interest, I did some edits in my post. Generally I am trying to solve $\max_{x,y} \: f(x,y)$ by using $(1)$. That is by solving it sequentially which I fond more easy that solving it simultaneously which I found more difficult.  So at first place I am interested to know if ${z^*}' \equiv {z^*}$. In any case, I am very grateful for any additional information.
Comment: @RiverLi I add some more details in my post. I hope it is more clear now of what I am asking.
Comment: @podiki $\max_y f(x,y)$ is the maximum with respect to $y$ for a generic fixed $x$. It is therefore a function of $x$.
Answer: If $A$ is positive definite then $A=X^TDX$, where $D$ is a diagonal matrix with the eigenvalues $\lambda_i$ of $A$. Hence $$z^T\left(A+\frac{xy}{2}I\right)^{-1}z=(Xz)^T\begin{pmatrix} \lambda_1+\frac{xy}{2} & 0&\cdots&0 \\ 0 &\lambda_2+\frac{xy}{2}&\cdots&0 \\\vdots&\vdots&\ddots&0\\0&0&\cdots\lambda_n+\frac{xy}{2} \end{pmatrix}^{-1}(Xz)=\sum_{i=1}^nw_i^2\left(\lambda_i+\frac{xy}{2}\right)^{-1},$$ with $w=Xz$.
Otherwise, if you denote $$M=A+\frac{xy}{2}I,$$ you can see that $MM^{-1}=I$ and follows that
$$\frac{\partial\,M}{\partial\,x}M^{-1}+M\frac{\partial\,M^{-1}}{\partial\,x}=0.$$
You find that $$\frac{\partial\,M^{-1}}{\partial\,x}=-\frac{y}{2}\left(M^{-1}\right)^2.$$
Hence, if $$\frac{\partial\,f(x,y)}{\partial\,x}=\frac{y}{4}z^T\left(M^{-1}\right)^2z-\frac{y}{4}x^2=0.$$ The condition on $y>0$  gives you $$x^2=z^T\left(M^{-1}\right)^2z.$$
If you also have $$\frac{\partial\,f(x,y)}{\partial\,y}=\frac{x}{4}z^T\left(M^{-1}\right)^2z-\frac{\lambda}{6}-\frac{1}{12}x^3=0.$$
It follows that
$$\frac{x}{4}x^2-\frac{\lambda}{6}-\frac{1}{12}x^3=0.$$ And you have $x^*=\sqrt[3]{\lambda}$.
This helps you to handle with the equation $\nabla f(x,y)=(0,0)$.
Remark:

Equation (2) probably  gives you implicit curves, say $X(x,y)=0$, hence your equation (3)  looks to becomes a constrained optimization problem, which can be harder to solve (this thread can be useful). If this last problem has only one solution then this thread imply that it is the one you are looking for.

In a general case equations $\partial_x f(x,y) = 0$ and $\partial_y f(x,y) = 0$ probably  gives implicit curves to you, say $u(x,y)=0$ and $v(x,y)=0$. This gives you a system of equations, with two equations and two variables, that you can try to solve numerically, like with Newton's method or other that you can find on SearchOnMath.

The set of solutions of $X(x,y)=0$ is a subset of the set of solution of $u(x,y)=0$.
Comment: Thanks for the interest. Could you please elaborate a little more on how this helps to handle the equation $\nabla f(x,y)=(0,0)$ for entire $f(x,y)$?
Comment: Indeed, I think that the equation $\nabla f(x,y)=(0,0)$ can be changed to a system of two equations, or two polynomial equations, in two variable. Probably you will need a numerical method to solve them.
Comment: Could you provide a more detailed answer on the whole problem or elaborate on ${z^*}' \equiv {z^*}$?
Comment: I did some change in my answer. I am trying to find an example to clarify my point.
Comment: [This example](https://www.wolframalpha.com/input?i=f%28x%2Cy%29%3D-%28x%5E%282%29%2By%5E%282%29-1%29%5E%282%29+%28x%5E%282%29%2Bxy-4%29%5E%282%29) is to  try to help.
Comment: In this example I want to show that $\min_xf(x,y)$ is a number, in this case is $0$. But the $\arg\min_xf(x,y)$ gives you the set $E$ containing both implicit curves $x^2+y^2-1=0$ and $x^2+xy-4=0$. On the other side, the equation $\partial_xf(x,y)=0$ has a bigger set of possible solution.
Comment: Why $X(x, y) = 0$ is a function of $x$ and $y$ and not only a function of $y$ as the optimal $x^*$ is fixed? Also, why the aforementioned analysis helps to deal with the simultaneous optimization $\nabla f(x,y)=(0,0)$? Last by not least, could you please elaborate a little more on the Remark 3.?
Comment: I understand that your equation (2) is in a general context. So the aforementioned example show you that $X(x,y)=0$ can gives you more that one implicit curve. And even one impicit curves can gives you more then one function, say $x(y)$. And, in general, $x^*$ is unknown at this point.
Comment: In general, the equation $\nabla f(x,y)=(0,0)$ is a way to find possible local minimizing points. It can gives you saddle point, local minimum or maximal points, for instance.
Comment: But, in your particular function given by EDIT1, equation $\nabla f(x,y)=(0,0)$ gives you only one $x=x^*=\sqrt[3]{\lambda}$. It remain to find possible values to $y$ in the equation $(\sqrt[3]{\lambda})^2=z^T\left((A+\frac{\sqrt[3]{\lambda}y}{2}I)^{-1}\right)^2z$ and test it to exclude possible non minimal points of $f(x,y)$. @darkmoor
Comment: So for some $\lambda$, we can compute $x=x^*=\sqrt[3]{\lambda}$ and then solve somehow the non-linear equation? Will we take the same solution if we have solved somehow $\nabla f(x,y)=(0,0)$ simultaneously?
Comment: Yes. You can think about the hessian matrix to test local minimum points.
Comment: Unfortunately, I do not catch your comment. Can you please be a little more precise on my two comment questions? Thanks.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/134931/discussion-between-jose-c-ferreira-and-darkmoor).


Como usar mais de um caractere de separação no método split()?

Question: Eu gostaria de quebrar uma String em várias substrings, para isto estou usando o método split(). Acontece que, eu não tenho certeza de quais caracteres podem estar na variável que utilizarei.
Exemplificando:
String words[] = line.split(" ");

Este código atende ao que estou precisando, estou considerando que será usado somente o "  " para separar as palavras. Mas o problema é que essa entrada será lida de um arquivo de texto onde usuário pode colocar qualquer caractere entre as palavras.
Então, eu precisaria criar algo do tipo:
String words[] = line.split(" #@_\\/.*");

É possível fazer isto em Java? Alguma solução?
Answer: Uma possibilidade é:
    String a = "Exemplo, de. separar- string+ por* carater";
    //Como quer todos os caracteres pode usar esta expressão regular:
    String[] parts = a.split("[\\W]");

    for(String i:parts){
        System.out.println("===" +i);
    }

Output:
run:
===Exemplo
===
===de
===
===separar
===
===string
===
===por
===
===carater

Para remover os espaços também deverá alterar esta linha de código:
String[] parts = a.split("[\\W][ ]");

Output:
===Exemplo
===de
===separar
===string
===por
===carater

Comment: @mxn Em expressões regulares `\W` significa qualquer caractere que não seja uma letra ou número ou um *underline*.
Comment: Funcionou! Poderia explicar melhor o que o `[\\W]` significa ali?
Comment: obrigado utluiz, estava a procura dessa informação para juntar a resposta
Comment: @mxn repara que editei a expressão regular assim `[\\W][ ]` assim remove os espaços também, como estava `[\\W]` guarda os espaços também...
Comment: A edição que você fez deixou de funcionar: `a.split("[\\W][ ]");` não funciona. `a.split("[\\W]");` funciona. O resultado de `a.split("[\\W][ ]");` é o mesmo postado pelo @bigown. Tem como editar e deixar como estava?
Comment: eu estou a executar este código, para ver se estava correto(por isso detetei os espaços) mas curioso que comigo funcionou direito
Comment: No meu caso não funcionou. Se possível, deixe as duas implementações então, pois somente a primeira deu certo aqui.
Comment: é muito estranho, mas sim vou fazer essa edição...
Answer: Solução com \W
Nas expressões regulares implementadas no Java, conforme documentação da classe Pattern, existe uma classe de caracteres \w (minúsculo), que representa os caracteres que formam palavra. Seria o mesmo que [a-zA-Z_0-9].
Existe também a classe de caracteres \W(maiúsculo), que representa o oposto da anterior, isto é, caracteres que não formam palavras.
Uma solução simplista seria usar o \W para quebrar a String por qualquer caractere que não seja de uma palavra, incluindo qualquer pontuação e espaço.
Mas há problemas com esta abordagem:

Não considera caracteres especiais que comumente fazem parte de palavras, como é o caso do hífen, por exemplo.
Não considera caracteres acentuadas pois eles não fazem parte do conjunto de caracteres de palavras do \w.

Solução específica
Uma solução mais específica seria definir um conjunto de caracteres que devem "quebrar" a String. Exemplo:
String caracteres = " #@_\\/.*";

Depois, você coloca esses caracteres entre colchetes, o que em expressões regulares significa uma classe personalizada de caracteres. Exemplo:
String words[] = line.split("[" + Pattern.quote(caracteres) + "]");

O método Pattern.quote acima garante que os caracteres receberão o escape necessário para não estragar a expressão regular.
Exemplo completo
String line = "1 2#3@4_5/6.7*8";
String caracteres = " #@_\\/.*";
String words[] = line.split("[" + Pattern.quote(caracteres) + "]");
for (String string : words) {
    System.out.print(string + " ");
}

Saída:

1 2 3 4 5 6 7 8

Caracteres especiais em sequência
Com a expressão acima, podem ficar palavras em branco no vetor, caso sejam encontrados dois caracteres especiais ou espaços em sequência. Isso é comum no caso de uma frase que contém um ponto final ou vírgula seguido de um espaço em branco.
Para evitar que isso aconteça, basta acrescentar um + à direta da classe personalizada para que o split capture a sequência de caracteres especiais num único bloco, de uma só vez. Exemplo:
String words[] = line.split("[" + Pattern.quote(caracteres) + "]+");

Answer: Acho que isto resolve seu problema:
import java.io.*;

 class Test{
   public static void main(String args[]){
      String line = new String("banana*batata.pepino#alface_tomate@cenoura cebola/abacate|morango\\laranja");
      for (String retval: line.split(" |#|@|_|\\\\|\\/|\\.|\\*") ){
         System.out.println(retval);
      }

   }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Estou usando um operador or do RegEx afinal o split() é baseado em RegEx.
Comment: Não sei se o RegEx está certo porque não costumo usá-lo mas é basicamente isto.
Comment: Não funcionou para mim. Ele gerou uma `String` vazia, não sei o que foi "splited" mas não foram os caracteres, hehe. Mesmo assim, obrigado.
Comment: Tinha um probleminha mesmo mas agora testei e funcionou no que testei.


How To logout and close any active forms in Delphi

Question: Sorry for my bad English, first this is the logout syntax.
When I click logout, all active forms keep showing up and not closing.
procedure Tf_utama.KELUAR1Click(Sender: TObject);
begin
if MessageDlg('Logout ??',mtConfirmation,mbOKCancel,0)=mrOK
then

DATAINPUTAN1.Visible:=False;
INFODATA1.Enabled:=False;
TRANSAKSI.Enabled:=False;
LAPORAN1.Enabled:=False;
PENGATURAN1.Enabled:=False;

f_databuku:=nil;
f_rakbuku:=nil;
f_permintaan_pembeli:=nil;
f_rakbuku:=nil;
f_pengguna:=nil;
f_transaksi_penjualan:=nil;
f_transaksi_pembelian:=nil;
f_supplier:=nil;

StatusBar1.Panels[0].Text:='Nama Pengguna :';
StatusBar1.Panels[1].Text:='Hak Akses :';
end;

On each form to close I am using:
procedure Tf_caribuku.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
f_caribuku:=nil;
end;

Answer: That's not how you close and free the form. You are just assigning nil to form pointers, which doesn't close them. What you have to call is TForm.Close(). Also, you have to open your if MessageDlg(... statement with begin..end; blocks if you want to execute multiple commands if statement is satisfied. So your code would look something like this:
procedure Tf_utama.KELUAR1Click(Sender: TObject);
begin
  if MessageDlg('Logout ??',mtConfirmation,mbOKCancel,0) = mrOK then
  begin
    DATAINPUTAN1.Visible:=False;
    INFODATA1.Enabled:=False;
    TRANSAKSI.Enabled:=False;
    LAPORAN1.Enabled:=False;
    PENGATURAN1.Enabled:=False;

    f_databuku.Close;
    f_rakbuku.Close;
    f_permintaan_pembeli.Close;
    f_rakbuku.Close;
    f_pengguna.Close;
    f_transaksi_penjualan.Close;
    f_transaksi_pembelian.Close;
    f_supplier.Close;

    StatusBar1.Panels[0].Text:='Nama Pengguna :';
    StatusBar1.Panels[1].Text:='Hak Akses :';
  end;
end;

Also, if any of forms you're trying to close is not created, I believe it will fail with AV exception. Better way to do this is to make another class which will serve as form container, e.g. TFormContainer, where you can Add and Remove forms on need. That way, upon logout, opened forms will be in TFormContainer class, and you can close them.
Comment: still error, maybe because  not every form open or  not created. and how to use `TformContainer`? sorry i Still don't get it.
Comment: Finally i can solve this.

`procedure Tf_utama.KELUAR1Click(Sender: TObject);
begin
 if MessageDlg('Logout ??',mtConfirmation,mbOKCancel,0) = mrOK then
  begin
    DATAINPUTAN1.Visible:=False;
    INFODATA1.Enabled:=False;
    TRANSAKSI.Enabled:=False;
    LAPORAN1.Enabled:=False;
    PENGATURAN1.Enabled:=False;`

    f_databuku.Free;
    f_rakbuku.Free;
    f_permintaan_pembeli.Free;
    f_rakbuku.Free;
    f_pengguna.Free;
    f_transaksi_penjualan.Free;
    f_transaksi_pembelian.Free;
    f_supplier.Free;
     end;
    end;`
Comment: You should not call SomeForm.Free. Why? Doing so you prevent corect form termination. For instance if you free up the min form the application won't close as it would othevise. And that is becouse the form can't notiffy TApplication class about its destruction, also calling Someform.free prevents OnClose or OnCanClose events to be fired.
Comment: that true, and now i find syntax to resolved it. With Use `if Assigned(f_databuku) then f_databuku.Close;` like that.