Find a center and radius of circle that is an image of Mobius Transformation of real axis

Question: I need to find a center and radius of a circle that is an image of real axis under homography
$$ h(z)= \frac{z-z_1}{z-z_2} $$
I found out that homography preserves symetric points, therefore because
$$ \infty \quad and \quad 0\ $$ are symmetric with respect to generalised circle (real axis) then their images are also symmetric with respect to image of real axis
$$ h(\infty)=1 \quad and \quad h(0)=\frac{z_1}{z_2} $$
Any hints or solutions would be appreciated.
Answer: The inverse funtion to $f$ is equal $$g(z) =h^{-1} (z) =\frac{z_2 -z_1}{z-1}$$ thus $$f(\{z: \mbox{Im}z =0\} ) =g^{-1} (\{z: \mbox{Im}z =0\})$$
Answer: That's not quite right. $0$ is symmetric to itself wrt the real line, and ditto for $\infty$. Take the point $z_2$ instead. First consider what happens when $z_2 \in \mathbb R$. If $z_2 \notin \mathbb R$, then you can exploit the symmetry to find the point which is mapped to the center of the circle. The distance between the center and the image of $\infty$ is the radius.
Answer: Applying Inversive Geometry
$\newcommand{\Re}{\operatorname{Re}}\newcommand{\Im}{\operatorname{Im}}$
The center of the inversion of $h(z)=\frac{z-z_1}{z-z_2}$ is at $z_2$ and the line, $L$, containing $z_2$ and $\Re(z_2)$ is perpendicular to the real axis. Thus $h(L)$ is a line which is perpendicular to $h(\mathbb{R})$ at both intersections, $h(\infty)$ and $h(\Re(z_2))$. This means that those points are antipodal.
Since
$$
h(\infty)=1\qquad h(\Re(z_2))=\frac{i\Re(z_2)-iz_1}{\Im(z_2)}
$$
we get the radius, $r$ and the center, $k$, of $h(\mathbb{R})$ to be
$$
r=\frac{|z_1-z_2|}{2\Im(z_2)}\qquad k=\frac{i\,\overline{z_2}-iz_1}{2\Im(z_2)}
$$


where is the source code for "Powered by Drupal"

Question: Someone told me the footer text "Powered by Drupal" in Drupal7 is provided by theme_system_powered_by(), which is turned into a block by system_block_info() and system_block_view(). I wonder in what file(s) these functions can be found. Thanks a million.
Comment: If all you want to do is prevent "Powered by Drupal" from being displayed, you can turn off the "Powered by Drupal" block on the admin/blocks page.
Answer: Here's the API documentation for all your needs:

theme_system_powered_by()
system_block_info()
system_block_view()

Also, please note that modifying the output of theme_system_powered_by() should be done using a theme hook from your theme code. If you wonder how to achieve this, this might be a relevant article for you.
Answer: All the functions are defined in the system.module file, at the following lines:

system_block_info(), line 2021
system_block_view(), line 2053
theme_system_powered_by(), line 3387

This information is normally not useful, as the code of those functions (as other Drupal functions) is visible on the API reference site. The core modules should not be edited.


nginx subdomain using domain config

Question: When I browse to sub.example.com, it just goes to the index.html of example.com and doesn't use the subdomain config.
    # redirect all traffic to https
server {
    listen 80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

server {

    listen 443 ssl;
    root /var/www/html/example;
    index index.html index.htm index.php;
    server_name example.com;
    include /etc/nginx/ssl.conf;
    client_max_body_size 0;

    location / {
        try_files $uri $uri/ /index.html /index.php?$args =404;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # With php7-cgi alone:
        fastcgi_pass 127.0.0.1:9000;
        # With php7-fpm:
        #fastcgi_pass unix:/var/run/php7-fpm.sock;
        fastcgi_index index.php;
        include /etc/nginx/fastcgi_params;
    }

}

server {
    listen 443 ssl;
    server_name  sub.example.com;
    include /etc/nginx/ssl.conf;

    location / {
            proxy_pass http://#internalip#/;
            include /etc/nginx/proxy.conf;
        }
}

IE: When I go to example.com it loads /var/www/html/example/index.html and when I go to sub.domain.com it still loads /var/www/html/example/index.html instead of redirecting to http://#internalip#/ like it should. any ideas? i must be doing something wrong with the config here.
Comment: The config seems fine, however if you go to `http://sub.example.com/` you will get a redirect to `https://example.com/`, whereas `https://sub.example.com/` should directly return the content of `http:///`.
Comment: Sorry I thought I changed them all to example. Thanks, that was the issue. Any idea what variable the original request is stored in so that i can dynamically send to https? so i can do https://$url$request_uri  ?
Answer: You have hard coded a permanent (cached indefinitely by browsers) redirect for not only the example.com domain name but, since there are no other other servers defined for plain http on port 80, every (sub-) domain and all HTTP  requests gets redirected to https://example.com
you probably want something like
server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

where you generate a redirect to the $host name used in the original request.
Please note that you will need to clear your web browser cache or use a new anonymous browser window to test and invalidate cached permanent redirects after you changed your config
Comment: Thanks this worked great!

nginx subdomain using domain config


Some ambiguities about used training dataset in bagged trees

Question: I have some ambiguity about dividing training dataset in Bagging tree.
In fact I have found in this article About Decision Tree Ensembles- Bagging
That : the idea is to create several subsets of data from training sample chosen randomly with replacement.
I want to understand which of the next solutions is bagging technique: if the total dataset is D (Without the target value y)
Solution 1:

Splitting D to X_train and X_test :

Splitting X_train to sevral subtraining sets like : X_train1, X_train2, X_train3, X_train4 etc. where X_train1 + X_train2 +X_train3+X_train4 +....=X_train.

Finally training each dataset separatly and generating different model for each trained dataset.

Average of all the predictions (generated trees) is used to get the unique final output tree

OR
Solution 2:

Splitting D to X_train1 and X_test1 :
Training the dataset and generating the first decision tree
Splitting D to X_train2 and X_test2
Training the dataset and generating the second decision tree
etc.
Average of all the predictions (generated trees) is used to get the unique final output tree
Comment: Solution 2 looks like k-fold cross validation
Answer: Solution one is correct.
You set apart the test set (that will work as an indepentent dataset), and train individual trees on randomly sampled subsets of the training data with replacement.
In the end, you test your model in the initially separated test set, and average the predictions and the result is the random forest prediction.
It wouldn't be much profitable to have an individual test set for each tree, since each individual tree was trained in a limited sample!
Comment: "each tree only has available a random subset of features " it seems you are talking about Random Forest but here I am talking about the initial solution of Bagged tree before improving with random Forest
Comment: @baddy thanks for the correction! Edited the answer :) Still, solution 1 would be the correct one
Comment: Thanks for your time


Ruby - Imprimindo zero como casa decimal

Question: Estou aprendendo a programar em Ruby, e para ir treinando, uso o Uri Online Judge, onde resolvo exercícios que são apresentados, faço o código em alguma linguagem que a plataforma aceite (nesse caso o Ruby) e depois envio para o sistema, mas a saída tem que ser exatamente igual a que é apresentado, como por exemplo, exibir duas casas decimais (dois números após o ponto), não pode ser nem mais nem menos.
Estou com dificuldade em fazer o Ruby exibir os zeros da casa decimal.
Como por exemplo o numero 1051 (estou com dificuldades em outros exercícios também, mas esse foi o mais recente), o código é:
a = 1000 * (8/100.0)
b = 1500 * (18/100.0)
s = gets.to_f
if s >= 0 and s <= 2000
    puts "Isento"
elsif s > 2000 and s <= 3000
    s -= 2000
    s *= 8/100.0
    puts "R$ #{s.round 2}\n"
elsif s > 3000 and s <= 4500
    s -= 3000
    s *= 18/100.0
    s += a
    puts "R$ #{s.round 2}\n"
elsif s > 4500
    s -= 4500
    s *= 28/100.0
    s += a + b
    puts "R$ #{s.round 2}\n"
end

Ele deve exibir duas casa decimais, mas quando a saída iria/deve apresentar casas decimais com "0", ele não exibe. Já somei a variável com 0.001 mas mesmo assim, exibe apenas 1 casa decimal em caso de zeros.
Como posso resolver isso, ou é um bug do próprio Ruby?

exemplo de saída apresentado pelo URI:
Answer: Você pode a saída do ponto flutuante, tente:
puts "R$ %0.02f\n" % s.round(2)

ao invés de
puts "R$ #{s.round 2}\n"

Resultado pra mim foi ok, se eu entendi bem sua pergunta:
4520.00
R$ 355.60

Boa sorte.
EDIT: mais algumas dicas de formatação
Comment: deu certo.. não sabia que tinha essa forma de se imprimir em Ruby, conhecia epenas a que eu apresentei e `puts "R$ " + s.to_s`
Comment: @n3h heheh, pois eh. Essa forma lembro que usava muito no C, bem útil para esses caso também. Bons estudos.
Comment: sim, eu também fiz os mesmos exercícios em C, e é bem parecido mesmo (`printf("%.2f", s);`). obrigado pela orientação..


can't Get stream of mp3 file in wp7 application

Question: i'm building a wp7 application for a game using silverlight & XNA
 i have an mp3 file called  "Punch1.mp3" (Build action : resource )  stored inside a folder called "SoundEffects" inside the project folder
and i want to play the file using this code
         StreamResourceInfo info;

         Uri myuri = new Uri("/SoundEffects/Punch1.mp3", UriKind.Relative);
         info = App.GetResourceStream (myuri);
         punch1 = SoundEffect.FromStream(info.Stream ) ;

punch is defined in the code here :
public static SoundEffect punch1;

the problem is that it raises a nullreference exception in the third line claiming that info is null
and that's true in the debugging mode , i found that the resource stream info is null
i think this is because the it can't read the file although the uri is correct
Comment: can you please paste code that refers to what info an punch1 are need to see where you declare these please.. thx
Answer: You can try two things
- Clean and rebuild the project
- Try appending project name in URI "/PhoneApp1;component/SoundEffects/Punch.mp3"

Comment: when i append the project name this would be an absolute or relative uri ?
Comment: I think it would be relative because you are still accessing it relatively through your project
Comment: i've tried and didn't work , also i've tried on another pc didn't work as well
Answer: Since you're using the XNA assembly anyway, you can use TitleContainer.OpenStream instead (with a relative URI) and have the audio file build set as Content.
Comment: That exception is being thrown because `FromStream` expects a wave file, not an MP3. http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.soundeffect.fromstream.aspx You'll have to convert it if you want to use the `FromStream` method. But you can still use the `TitleContainer.OpenStream` method to load the WAV.
Comment: i've tried the code above here :
             Stream stream = TitleContainer.OpenStream(@"soundeffects\ahhh1.mp3");
             punch1 = SoundEffect.FromStream(stream) ;
the stream object managed to read the file and when debugging it has a lenght and offset which seems promising
but the second line rises a InvalidOperationException
Answer: I agree with Haris Haqsan that your URI string is bad.
Uri myuri = new Uri("/PhoneBoxing;component/SoundEffects/Punch1.mp3", UriKind.Relative);

But you should also consider switching to using content files instead embedding them at resources as it can help your application start up time.  Depending on the amount of files we are talking about, it can make a big difference.
Set your Build Action to content and your code should look like:
FileStream stream = new FileStream("/SoundEffects/Punch1.mp3", FileMode.Open, FileAccess.Read);

Comment: the uri is working well the problem was fromstream method accepts only wav files
Answer: in the following code :
     Uri myuri = new Uri("/SoundEffects/Punch1.mp3", UriKind.Relative);
     info = App.GetResourceStream (myuri);
     punch1 = SoundEffect.FromStream(info.Stream ) ;

SoundEffect.FromStream() expects a wave file stream not an MP3 as shown here : http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.soundeffect.fromstream.aspx .
so solution to find a mp3 > wav convertor or just find another way to load mp3 to WP7
considering the picture this is normal URI in normal cases can't evaluate expression of isfile .
Answer: I was experiencing the same issue on my machine, the InvalidOperationException is a little confusing.  All I had to do was re-encode the wav file to the specifications listed on MSDN.
After I did that, it worked perfectly.


Criando Schedule pra transferir arquivos CSV do WinSCP pra um FTP

Question: Preciso transferir arquivos de extensão CSV que estão numa pasta do meu servidor em Linux (acessível via WinSCP pelo Windows) para um FTP. Pra isso, é necessário criar uma schedule que faça essa transferência diariamente.
Encontrei esse link que envolve criação e uso de schedules usando WinSCP, mas me ficou meio vago.
O que eu poderia fazer nesse caso?
Answer: Você certamente conhece o PuTTY, ele tem um utilitário chamado PSCP, que faz transferência de arquivos via SFTP, ou SSH. Ele pode usar uma sessão criada dentro do PuTTY para a conexão, algo assim:
<code>%Path_Putty%\pscp.exe arquivo.csv SESSAO_SSH:/home/user/
</code>
Isso irá transferir o arquivo.csv para o /home/user/ configurado como SESSAO_SSH no PuTTY.
Crie um BAT, ai é só utilizar o agendador de tarefas do Windows para chamar o BAT.
Configure a sessão com usuário e chave de acesso SSH, ai não precisa de senha.
Um exemplo de BAT
<code>@echo off

:pscp_path
SET PSCP=ERRO
if EXIST "%ProgramFiles%\PuTTY\pscp.exe" SET PSCP="%ProgramFiles%\PuTTY\pscp.exe"
if EXIST "%ProgramFiles(x86)%\PuTTY\pscp.exe" SET PSCP="%ProgramFiles(x86)%\PuTTY\pscp.exe"

if %PSCP% == ERRO goto erro_putty

SET PLINK=ERRO
if EXIST "%ProgramFiles%\PuTTY\plink.exe" SET PLINK="%ProgramFiles%\PuTTY\plink.exe"
if EXIST "%ProgramFiles(x86)%\PuTTY\plink.exe" SET PLINK="%ProgramFiles(x86)%\PuTTY\plink.exe"

if %PLINK% == ERRO goto erro_putty

echo "Enviando arquivos de exportação para servidor"
%PSCP% *.txt CentOS_SSH:/opt/dj/djsystem/integracao
move *.txt processado

echo "Chamando execução do script no servidor linux"
%PLINK% CentOS_SSH sh importa.sh

echo "Copiando arquivos de importação para diretório local"
%PSCP% CentOS_SSH:/opt/integracao/*.txt .

echo "Chamando execução do script de remoção dos arquivos"
%PLINK% CentOS_SSH rm -rf /opt/integracao/*.txt

goto fim

:erro_putty
ECHO Putty não conseguiu instalado.

:fim
</code>


To fit a curve to model direct mail marketing responses. How to obtain the % of responses that are likely to occur each day

Question: I'm trying to model the responses from a direct mail marketing campaign so that I can use it to forecast for future campaigns.
I started, in the code below, with the average number of responses by day of a historical campaign (contained in the vector: "responses"). I was then able to fit a 63-day (8-wk) smooth curve to model the data. But I now need a way to use this curve to help me with forecasting. For example, if I think I'll get x number of total responses from a campaign, I need to know when those responses are most likely to happen. In other words, I need the daily "factors" (i.e. the percentage of the total responses that is most likely to respond on each day).
p.s. if anyone has a better way of approaching this I'd love to hear!
#vector of direct mail marketing responses over 63 days
responses <- c(
24.16093706,  41.59607507,  68.20083052,  85.19109064,  100.0704403,  58.6600221,  86.08475816,  88.97439581,  65.58341418,  49.25588053,  53.63602085,  47.03620672,  29.71552264,  32.85862747,  31.29118096,  23.67961069,  19.81261675,  18.69300933,  17.25738435,  12.01161679,  12.36734071,  14.32360673,  11.02390849,  9.108021409,  9.647965622,  8.815576548,  5.67225654,  5.739220185,  6.233999138,  5.527376627,  5.024065761,  5.565266355,  4.626749364,  3.480761716,  4.621902301,  4.518554271,  4.075985188,  3.204946787,  3.174020873,  2.966915873,  2.129178828,  2.673009031,  2.410429043,  2.331287075,  2.509300578,  2.13820695,  2.53433787,  1.603934405,  1.555813592,  1.834605068,  1.842905685,  1.454045577,  2.08684322,  1.318276487,  0.807666643,  1.333167088,  1.004526525,  1.180110123,  1.078079735,  1.151394678,  1.426747942,  0.699119833,  0.583347236)

set.seed(2)
install.packages("MASS")
library("MASS")

shape_and_scale <- fitdistr(responses,'weibull')

#check the shape and scale
shape_and_scale

#plug in the shape and scale
#essentially taking the total number of respondants and for each, doing a random simulation for what day they'll respond- according to a weibull distribution
#rweibull makes it a random generation
#also need to create a variable for the total number of responses
total_responses <- 1121
day_response <- round(rweibull(total_responses,0.70730466,13.79467490)+.5)

day_response

day_response_frequency_table <- as.data.frame(table(round(rweibull(total_responses,0.70730466,13.79467490)+.5)))

day_response_frequency_table
#notice that it extends beyond our 63 day limit for modeling a campaign

#create a factor with levels so that we can limit our distribution to 63 days
day_response_with_levels <- factor(day_response, levels=0:63)
day_response_with_levels
response_frequency <- as.data.frame(table(day_response_with_levels))
response_frequency

#now use dweibull and the curve() function to create a curve
?dweibull
curve(x*dweibull(x,0.70730466,13.79467490),from=0, to=63)

Comment: What are you asking? It's hard to tell because (1) a lot relies on people reading and understanding your code and (2) you write about "projections," a "factor," "forecasting," and "applying" something in vague ways that could mean anything from fitting a curve to predicting future values.  Could you edit this post to help readers get a clearer idea of what you need to accomplish?
Comment: @whuber

To be clear I _deseasonalized_ or _normalized_ my responses to account for the variations in day-of-the-week, holidays, promotions, etc...is this what you're talking about?   So in my case the responses that I averaged were free of daily seasonal variability and just represent the aging of a direct mail campaign.  At a high level, I need to forecast responses for future direct mail campaigns.  I have data from previous campaigns and just need to know what % should come in day 1, day 2, ... etc. not accounting for seasonality.  Then I'll seasonalize the smooth response curve afterward.
Comment: @whuber

I tried to make my question more clear.  Does what I'm looking to do make sense now?
Comment: It is much clearer, thank you. I'm not sure you are aware this is a vast subject: you can find out about many approaches by following our [tag:time-series] links. Your code is rather curious though: one thinks of a "response" as a count or perhaps a monetary quantity. The values in your `responses` vector, given up to nine decimal places, obviously are not either one of those! Count responses often will be modeled in subtly different ways than other kinds of responses, so this could be an important detail.
Comment: @whuber

ah, I see how that could have been confusing.  The responses vector was calculated as an _average_ number of responses on a certain day of a campaign (for example, day 1 usually gets ~24.16 responses on average).  Do you have any suggestions given that I've already created the weibul curve?
Comment: The Weibull curve will be useless to you: it surely is a terrible model of future outcomes because it does not capture any information about how the results vary with time. Moreover, using raw averages is not a good idea because it overlooks the variations in uncertainty associated with different total responses. These considerations show why it can be so important to explain what kind of data you *really* have and to ask how to achieve your analytical objetives, rather than starting with the results of your processing and asking where to go next.
Comment: That is interesting and useful information, Ryan, and well worth incorporating in your question. You might want to consider taking a step back by describing your original data and their expected behavior, then asking for ideas about how to conduct a forecast in this circumstance. That would open up many additional approaches to your problem.
Answer: The data, responses, that you have can be modeled more generally than a probability distribution. A probability distribution is always normalized to 1 while your data contains more information, it also has a magnitude. I think that a more general type of function would also be better since in that case (if the function stems from good arguments well) the model seems to link closer to a physical interpretation (which is more intuitive) rather than using a phenomenological model
(Note: The Weibull distribution does have a physical interpretation when applied to processes that generate size distributions, e.g. a process that randomly breaks bigger pieces into smaller pieces, but in the case of the application here, the shape of a response impulse in a time series, it has no clear meaning)

Modelling with simple exponential function.
Your data can be reasonably described by using a series of exponential functions.
$$Y(day)_{response} = 286*e^{-\frac{day}{3}}-269*e^{-\frac{day}{7}}$$
more precise coefficients are 286.254*exp(-0.1536516*day)-268.6887*exp(-0.3326013*day)

 For your information the Weibull function in the graph is a = 163.7235 k= 1.4914 l=0.1098 weibull <-a*(time*l)^(k-1)*exp(-(time*l)^k) found by using the nls function
Physical interpretation
These kind of exponential expressions may be interpreted in terms of a differential equation with two parameters (https://en.wikipedia.org/wiki/Multi-compartment_model). E.g. you can imagine a (auxiliary/not measured) variable $X$ which is the amount of people that do not know about the campaign which slowly decreases once the campaign advances.
$$\dot X = -c_1 X$$
and the variable $Y$ is the amount of people that create a response. Which gets filled up by a fraction $f$ from the people from $X$ that get to know the campaign but decreases because people loose interest:
$$\dot Y = fc_1 X -c_2 Y $$
these have the solution:
$$\begin{bmatrix} Y(t) \\ X(t) \end{bmatrix} = \begin{bmatrix} Y(0)-Q \\ 0 \end{bmatrix} e^{-c_2 t} + \begin{bmatrix} Q \\ X(0) \end{bmatrix} e^{-c_1 t} $$
with $Q = f X(0) \frac{c_1}{c_2-c_1}$.
Note: you may, of course, argue for different models as well based on other (better) ideas about the change of $Y$. E.g. the decay of $X$ is not necessarily exponential as prescribed by the equations here, or other factors than this $X$ as the pool of people that do not know about the advertisement might be included (I just came up with this model after making the exponential fit and as a possible physical explanation).

Temporal effect
In the above figure I have marked every sixth day of the week in the color red. This is to emphasize that on top of the exponential model there seems to be some weekly pattern. You can see this by the red marked dot being the relatively low point in a weekly (7 day period) pattern that moves around the trend which is the modeled function.
It could be possibly to incorporate this pattern or temporal variation into the model as well (I do not think it is possible with some simple auto correlation and moving average model, although I might be mistaken, and I would model it with some additional correction function on top of the exponential function or by fitting some computational model, ie. solving the differential equations with $c_1$ and $c_2$ being time varying parameters).
You should be more clear about the data for this to work out. For instance is the average done on time sequences that always start on the same day? Or if it is corrected then how is this done. Describe more exactly the data, and make some plots or show some descriptions (possibly it is out of the scope of a Q&A to get to the bottom of this).
Splitting the data
The analysis would greatly improve when you fit to the individual curves instead of the average. In that way you can see better

the validity of the model
increase the complexity of the model (currently the degrees of freedom is low since the large amount of data is reduced to only a single time series)
obtain information about the variation/distribution of the
parameters  and the error distribution (which provides more insight
than the variation of the output, and this is what you can use to
make predictions with estimates for error)
and also you might
group the data and investigate how the model parameters may be a
function of other variables, for instance the type of campaign.


Is there a way to plot the tuning parameter selection in mgcv?

Question: Take a simple analysis using generalized additive models in mgcv:
 x <- seq(0, 1, length=500)
 y <- sin(2*pi*x)^2 + rnorm(500, sd=0.2)
 m <- gam(y ~ s(x))

I know how to see the final tuning parameter selected (type m$sp). Is there a way to plot the GCV vs. smoothing parameter to graphically see how it was selected? I know you can do stuff like this in glmnet when you choose the elastic net penalty size. Anything like this for mgcv? Thanks
Comment: What would you put on the y axis?  OOS mse?
Comment: the smoothing parameter
Comment: You'd put the GCV score on the y-axis and the log smoothness parameter on the x-axis.
Comment: How do you extract those values from the fitted object?
Comment: You can't; the GAM isn't fitted as a path of models in the sense of lassso penalties and similar. It is optimised using very efficient algorithms and we don't need actual crossvalidation to choose the optimal lambda, hence models for a sequence of lambdas are not estimated during fitting. You need to optimise the model for a fixed value of lambda and extract the score you want as I show in the answer below.
Answer: The way to do this is to fit the GAM for known values of the smoothness parameter $\lambda$, and set the smoothness parameter for each fit. You can then extract the GCV score from each model and plot them against the sequence of $\lambda$ values.
To fix the smoothness parameter you use the sp argument. For your example data this means setting sp to be a length one vector. If you are doing this for multiple parameters you'll need to fit models over a grid of 2 or more smoothness parameters.
Here is an example using your dummy data set:
## packages
library("mgcv")
library("ggplot2")

## data
set.seed(42)
x <- seq(0, 1, length=500)
y <- sin(2*pi*x)^2 + rnorm(500, sd=0.2)
df <- data.frame(x = x, y = y)

## Generate GCV traces
lambda <- 1e-6
gcv <- numeric(length = 100)

## loop over values of lambda, fixing sp
for (i in seq_along(gcv)) {
    m <- gam(y ~ s(x, k = 20), data = df, method = "GCV.Cp", sp = lambda)
    gcv[i] <- m$gcv.ubre
    lambda <- lambda * 1.1
}

## gather results
res <- data.frame(lambda = 1e-6 * 1.1^{0:99}, gcv = gcv)

## plot
ggplot(res, aes(x = lambda, y = gcv)) +
    geom_line() +
    scale_x_log10() +
    xlab(expression(lambda)) +
    ylab("Score")

This produces

You can do this for the other fitting methods available in mgcv also; the score is always in $gcv.ubre, despite the name of that component.
You'll notice that it take a lot longer to fit those models than it does to find the optimum value of $\lambda$ using GCV if you fitted without setting sp. mgcv has very efficient algorithms for selecting the optimal lambda and the steps it takes along the GCV surface (curev) will not produce a nice curve and typically aren't worth saving in the model object as a result. Hence the need to do the fitting iteratively, as shown above, to yield a nice curve of values over $\lambda$.
The above methods requires a little tuning to get right; you need to set lambda small enough initially and not increase it took quickly to home in on the minimum of the curve.
Comment: Perhaps, Schluter's version with sapply is faster... https://www.zoology.ubc.ca/~schluter/R/Model.html (see at the end)


Image encryption IndexError: list index out of range

Question: I am using a double strength XOR encryption to encrypt a bytearray of an image and than rewrite the array into the image file. When I use small numbers for the encryption keys this works great and the file is unreadable until it's run through the code with the same keys, decrypting it. However, I want to use 256-bit keys for protection and anytime I generate these keys and attempt the XOR my function exception runs and I get an index overflow error like this- IndexError: list index out of range
I assume the encrypted bytes are too big for the image file, any way I can fix this?
#Encryption/decryption keys
key1 = random.randrange(1, 115792089237316195423570985008687907852837564279074904382605163141518161494336)
key2 = random.randrange(1, 115792089237316195423570985008687907852837564279074904382605163141518161494336)
#In the extraordinarily rare case that both keys are equal regenerate key2
while(key1 == key2):
    key2 = random.randrange(1, 115792089237316195423570985008687907852837564279074904382605163141518161494336)

def secureImg(name):
    try:
        #Path to image
        path = name+".jpg"
        #Open file to read
        file = open(path, "rb")
        #Storing image data
        image = file.read()
        file.close()
        #Converting image into byte array to perform encryption on numeric data
        image = bytearray(image)
        #Performing XOR operation on each value of bytearray
        for index, values in enumerate(image):
            image[index] = (values ^ key1) ^ key2
        #Opening file to write
        file = open(path, "wb")
        #Writing encrypted data in image
        file.write(image)
        file.close()
    except Exception:
        print("Img error caught: ", Exception.__name__)

Comment: is it practical or hypothetical? There are multiple issues in this code, besides proper xoring
Comment: @Marat it is an early stage of a future practical application. Currently the focus is getting everything working before cleaning things up. All suggestions for better code are encouraged, but a solution to the issue is preferred
Answer: Main issues:

Xor is not aligned on chunks. single byte from image is being xored with a potentially very long number - the result is unlikely to be one byte.
Xor is a commutative operation. There is no reason to use two keys - it is the same as using one, key1 ^ key2.
Images tend to have a lot of predictable bytes in the header, which makes possible to reconstruct the key

Smaller items: use context managers (with ...), don't blanket try-catch, etc.
So, ignoring all conceptual issues it'd be something like:
from itertools import repeat
import os

KEY_SIZE = 1024

key = os.urandom(KEY_SIZE)

def bogus_encrypt(name):
    path = name+".jpg"
    with open(path, 'rb') as fh:
        # generally, bad idea; better limit to reasonable increments, few Kb to Mb
        raw_data = fh.read()

    encrypted_data = b''.join(a^b for a, b in zip(raw_data, repeat(key)))

    with open(path, 'wb') as fh:
        fh.write(encrypted_data)

Answer: Expanding on @Marat's idea, reading in the entire file to encrypt is not necessary, you can operate on individual chunks:
from itertools import repeat
from functools import partial
import os

KEY_SIZE = 1024

key = os.urandom(KEY_SIZE)

def bogus_encrypt(name):
    path = f"{name}.jpg"

    with open(path, 'rb') as infile, open(f'encrypted_{name}.jpg', 'wb') as outfile:
        # create a .read() function that takes no arguments
        reader = partial(infile.read, 2**20) # 2**20 bytes is 1Mb

        # iter can be used on a function that takes no
        # arguments, the second arg is a sentinel value
        # telling the loop to stop
        for chunk in iter(reader, b''):
            encrypted = b''.join(a^b for a, b in zip(chunk, repeat(key)))
            # write the chunk to new file
            outfile.write(encrypted)


Cardinality of all dense and countable sets of $\mathbb{R}$

Question: What is the cardinality of the following set:
$$\mathbb{A}:=\{A \ : A\subseteq\mathbb{R} \ \  \text{dense and countable}\}$$
(Is $\mathbb{A}$ a separable space?)
Thank You!
Comment: The question whether something is a separable space presupposes that a topology is given on that something.  Did you have a particular topology on $\mathbb A$ in mind?
Answer: The cardinality of $\Bbb R$ is $2^\omega$ (or if you prefer, $2^{\aleph_0}$), so $\Bbb R$ has $\left(2^\omega\right)^\omega=2^{\omega\cdot\omega}=2^\omega$ countable subsets. Thus, the cardinality of $\Bbb A$ is at most $2^\omega$, since not all countable subsets of $\Bbb R$ are dense in $\Bbb R$. However, it turns out that even though not all of these $2^\omega$ countable subsets are dense, there are $2^\omega$ of them that are dense. Here's one way to show this.
For $x,y\in\Bbb R$ write $x\sim y$ if and only if $x-y\in\Bbb Q$.

Prove that $\sim$ is an equivalence relation on $\Bbb R$.
Prove that for each $x\in\Bbb R$ the $\sim$-equivalence class of $x$ is $x+\Bbb Q=\{x+q:q\in\Bbb Q\}$ and is therefore countable.
Conclude that $\sim$ has $2^\omega$ equivalence classes.
Show that each $\sim$-equivalence class is dense in $\Bbb R$.

The set $\Bbb A$ isn't a space at all until you give it some topology: it's just a collection of subsets of $\Bbb R$.
Comment: Mr Brian M. Scott, Thank You!
Answer: Here is a slightly more fun way to do this:
First note that there are at most $\mathbb R^\mathbb N$ countable sets of real numbers, calculate the cardinality and see that this means that there cannot be more than $2^{\aleph_0}$ countable sets of real numbers.
Secondly note that $P=\mathbb{Q\setminus N}$ is dense in $\mathbb R$. Now for every $A\subseteq\mathbb N$ we have that $P\cup A$ is dense and countable. It is easy to see that if $A\neq B$ then $P\cup A\neq P\cup B$. Therefore we actually found $2^{\aleph_0}$ dense sets of real numbers which are subsets of $\mathbb Q$.
This shows that there cannot be more than $2^{\aleph_0}$ countable dense sets. As remarked by others, separability is a topological property and it is unclear what topology you are giving this collection.
Answer: $\mathbb{Q}$ is countable.  So $\mathbb{R}\setminus \mathbb{Q}$ is uncountable.  For each irrational $x$, the set $\mathbb{Q} \cup \{x\}$ is also dense in $\mathbb{R}$.  Hence there are an uncountable number of dense subsets of $\mathbb{R}$.
Comment: What is the cardinality of the set in question? Just saying the set is uncountable does not suffice here.


How can I interpolate a variable from a command line argument into a string?

Question: My program takes a command line argument which I would like to use to change the working directory of my Perl script.
use strict;
use warnings;
use Getopt::Std;
use Cwd 'chir';

my %opts=();
getopts('a:v:l:', \%opts);
my $application = $opts{a};
my $version = $opts{v};
my $location = $opts{l};

print "$application, $version, $location\n";

if($application eq 'abc') {
    #print "you came here\n";
    chdir "/viewstore/ccwww/dst_${application}_${version}/abc/${location}";
    print $ENV{PWD};
    print "you came here\n";
}

I've previously tried with chdir '/var/tmp/dst_$application/$version/$location';, but that did not work either.
The current version of the code gives this warning.

Global symbol "$application_" requires explicit package name at ./test.pl line 20. Execution of ./test.pl aborted due to compilation errors.

Line 20 is the one with chdir.
Comment: Please [edit] your question to include the stuff you've tried.
Comment: i have tried like
Comment: use Getopt::Std;

my %opts=();

 getopts('a:v:l: \%opts);

 my $application = $opts{a};
 my $version = $opts{v};
 my $location = $opts{l};

 if($application eq 'abc')

{
  chdir '/var/tmp/dst_$application/$version/$location';
}
Comment: i am getting exception near dst_$application as concentation error
Answer: You are using single quotes '' in your chdir command. Single quotes do not do variable interpolation in Perl. That means that '/var/tmp/dst_$application/...' means /var/tmp/dst_$application/..., and not /var/tmp/dst_foo/....
You need to use double quotes "" to interpolate variables in strings.
chdir "/var/tmp/dst_$application/$version/$location";

This will create /var/tmp/dst_foo/... instead.
If you need to separate a variable from the rest of the string, use this notation.
print "${foo}bar";

This is different from "$foobar" because Perl thinks the whole $foobar is the variable name.
Comment: i have tried double quotes but the values are not getting replaced in the script, Those variables I am updating from command line arguments
Comment: @mahesh please update your question with the code you have now.
Comment: use strict;
      4 use warnings;
      5
      6 use Getopt::Std;
      7
      8 my %opts=();
      9    getopts('a:v:l:', \%opts);
     10 my $application = $opts{a};
     11 my $version = $opts{v};
     12 my $location = $opts{l};
     13
     14 print "$application, $version, $location\n";
     15
     16 if($application eq 'abc')
     17
     18 {
     19 #print "you came here\n";
     20 chdir "/viewstore/ccwww/dst_$application_$version/abc/$location";
     21 print "you came here\n";
     22 }
Comment: Global symbol "$application_" requires explicit package name at ./test.pl line 20.
Execution of ./test.pl aborted due to compilation errors.
Comment: @mahesh you made a lot of effort to put the line numbers there. Why don't you just edit your question?!
Comment: use strict;
use warnings;
use Cwd 'chdir';

use Getopt::Std;

my %opts=();
   getopts('a:v:l:', \%opts);
my $application = $opts{a};
my $version = $opts{v};
my $location = $opts{l};

print "$application, $version, $location\n";

if($application eq 'abc')
{
#print "you came here\n";
chdir "/viewstore/ccwww/dst_$application_$version/abc/$location";
print $ENV{PWD};
}
Comment: i tried to add the same in question, but some how stackoverflow was not accepting my question
Comment: @mahesh Stack Overflow does not allow you to post additional questions because this question was so badly received. You don't need to add a new question. You need to EDIT the existing one. I posted a comment on the question with a link to the edit form. You can read all about editing [https://meta.stackexchange.com/a/21789/202151](here). However, I've updated my answer and included the solution already. If that solves your problem, please read [ask] and then mark an answer as accepted. That will also help lift your question ban. Thank you.
Comment: thanks for prompt response, But when i try to edit the question i am getting exception you code not properly formatted. I have tried all the ways to post my code. I am unable to Find your solutions
Comment: @mahesh I've edited your question for you. Look at how I did the formatting to see what you did wrong. You need to do use `"dst_${application}_${version}`.
Comment: Thanks a ton i got it, I have another question when we are using chdir in the perl script after running the command I am returning to the current location where i am running the script. How to stay in the change directory
Comment: @mahesh I don't know. Please ask a new question for that. If you can't do that yet, you will need wait until the ban is lifted. See https://meta.stackexchange.com/a/86998/202151 for details about that. In the meantime, I believe accepting this answer would be a good start, if you feel it helped you. (I hate coercing people to accept my answers, this is just a suggestion).


Interior of the closure of an open set

Question: I am trying to solve the following problem.

Let $E \subset \mathbb{R}^2$ be open. Prove that $\mathring{\overline{E}} = E$ does not hold in general.

I haven't been able to think of a counterexample in $\mathbb{R}^2$. In $\mathbb{R}$, I can take $E = (1,2) \cup (2,3)$. As $E$ is a union of open sets, it is open. It's closure is then $[1,3]$, but the interior of $[1,3]$ is $(1,3) \neq E$ .
I can't figure out how to generalize this argument to $\mathbb{R}^2$.
Comment: Take two open squares that "touch" themselves along an edge. The edge will act like $\{2\}$ in your 1-dimensionnal example.
Comment: @TheoBendit I understand why that's the case, but I'm struggling to apply this hint.
Comment: @BradG. Sorry, I missed the assumption that $E$ is open. My hint was indeed difficult (to impossible) to apply!
Comment: Take $E = \Bbb R^2\setminus A$ where $A$ is any closed set with empty interior.
Answer: An alternate approach which you might find easier, if you can't convince yourself that Nightflight's $E$ is open.
Hint: Take $E = \Bbb{R}^2\setminus\{(0,0)\}.$ Convince yourself $E$ is open. What is $\overline{E}$?
Subhint for proving $E$ is open:

 What is the complement of $E$? What do you know about the complement of open/closed sets?
Comment: If you know the sequential version of closedness, you can just observe that every (convergent) sequence taken from $\{(0, 0)\}$ is constantly $(0, 0)$, and hence converges to $(0, 0) \in \{(0, 0)\}$. Otherwise, you need to show $E$ is open directly; for $(x, y) \in E$, take the open ball whose radius is $\|(x, y)\|$, and prove that it is contained in $E$.
Comment: @BradG. Any set of the form $\{x\}$ in a metric space is closed as its complement is the open set $\bigcup_{y \neq x} B(y, d(x,y))$, a union of open balls, hence open.
Comment: This example makes sense to me. $\{(0,0)\}$ is closed, so $E$ is open. Then $\overline{E} = \mathbb{R}^2$, the interior of which is $\mathbb{R}^2$. The only remaining question I have is, how would I prove that $\{(0,0)\}$ is closed? It's easy in $\mathbb{R}$ to show that $\{0\}$ is not open by taking complements, but I don't know how to prove it in $\mathbb{R}^2$.
Comment: @BradG. Well, what is your definition of closed?
Answer: You said $E$ is open, and you gave an example of a union of two intervals.
Generalization of interval may be $I_1\times I_2$ forms: $I_1, I_2$ is both interval.
So the specific answer is $E=(-1,0)\times(-1,1)\cup(0,1)\times(-1,1)$.

 $\overline E=[-1,1]\times[-1,1]$, so $\mathring{\overline{E}}=(-1,1)\times(-1,1)\ne E$.
Comment: @BradG. , it is basically derived by defenition of product topology. If $A, B$ is both open set, then $A\times B$ is not just open set, but also element of **base of product topology**.
Comment: This is very helpful, though I don't know how to prove that $I_1 \times I_2$ is open in general. Do you have any tips for showing that?

Interior of the closure of an open set


Mq upgrade from 8.0 to 9.3 in midvision server

Question: We have a requirement to upgrade midvision mq server 8.0 version to 9.3 version in midvision MQ server. I have no idea how we can upgrade it. Any step by step guide
Kindly suggest me the steps how we can upgrade with the minimal downtime
Answer: I used Google to search on your question and the first hit was IBM MQ Migration paths.
And the instructions for doing it are Upgrading IBM MQ


What is the difference between fitting multinomal logistic regression and fitting multiple logistic regressions?

Question: In an analysis where the dependant variable Y has 4 levels (say A, B, C, and D) and there are several independent variables (including important interaction terms), one could think of multiple ways to describe the data (in a frequentist approach).
First, one could (and probably should) fit a multinomial logistic regression, which would output only 3 OR (missing one for the reference level). These ORs are a bit tricky to interpret, especially when the reference level of Y is chosen arbitrarily, as changing it will change the reported coefficients.
Second, one could make 4 binary dummy variables for each Y level and fit 4 logistic models. This would output one OR for each level, representing the odd of encountering it or not. These ORs are much easier to read and interpret, for both statisticians and non-statisticians.
Given this (and hoping I didn't state too much nonsense), how is the second approach wrong? What should not be interpreted in such an approach? (this question is about the interpretation, not the maths which are clearly described in several places)
Human Context: with such a categorical dependant variable, I want to interpret the interaction term. No level would make sense as the reference level. Describing the variable would be easier with 4 ORs and it seems to fit the data pretty well (as I could witness using plots). I'm also afraid editors would not understand the OR from the multinominal model, which will be quite hard to explain to my non-statisticians colleagues anyway.
Comment: @JoeKing yes, but done together rather than separately for improved efficiency and for keeping information about correlations among outcome types--think of this as analogous to a multivariate (multiple outcome) regression--and against a common reference category. See the section in Agresti's [Categorical Data Analysis](https://www.wiley.com/en-us/Categorical+Data+Analysis%2C+3rd+Edition-p-9780470463635) on "Nominal Responses: Baseline-Category Logit Models" (section 8.1 in the third edition, section 7.1 in the second edition).
Comment: Separate models produces discordant results, because, for a given combination of predictor values, the estimated probabilities will almost surely not sum to 1.
Comment: I always thought that, at it's heart, multinomial logistic regression was a series of logistic regressions.
Answer: The problem is how best to display the results, not the multinomial analysis per se. Yes, the intercept and regression coefficients can seem hard to interpret in a multinomial model. Those coefficients simply provide the starting point for data display. Although you have log-probabilities for most groups expressed relative to a single reference category, there is nothing to prevent you from combining those probabilities in any way you want, along with associated error estimates.
Use the multinomial regression probabilities for the categories in ways that display sets of outcome categories that might be of interest as a function of the predictor values. If you want to transform the results into odds ratios in a way that makes your point about an interaction term for a predictor, or display single-category results against all others, just do so starting with your properly constructed multinomial model. In general, you can display any linear combination of model predictions you want, along with error estimates based on the formula for the variance of weighted sum of correlated variables. To make your life easier, there are packages like the R emmeans package that will do the calculations for you.
Comment: Thanks for your answer. However, I feel like both approaches yield different kinds of interpretations. The `emmeans` package proved very interesting in this case but unfortunately didn't fit my actual needs. Since they are a bit out of the scope of this theoretical question, I made another one: https://stats.stackexchange.com/questions/496537/how-to-analyze-the-evolution-of-a-multilevel-variable-with-an-interaction. I'd be glad if you could take a look!
Comment: @DanChaltiel look more carefully at `emmeans`. For [multinomial models](https://cran.r-project.org/web/packages/emmeans/vignettes/models.html#N) it builds a "reference grid" of estimated results for all predictor combinations; with `mode="prob"` it fills that grid with predicted probabilities (and error estimates) for ALL outcome levels. It has tools for [comparisons and contrasts](https://cran.r-project.org/web/packages/emmeans/vignettes/comparisons.html) to evaluate any particular hypotheses you wish to test. Those facilities should meet your needs, although there will be a learning curve.


changing machine Network Adapter Ip lead to SQL Server service failure

Question: I configured my sql server to listen on ip:192.168.1.2 but since my machine get IP from DHCP may my last IP be differ from previous one on next start up.
in this situation when sql service wants to start, it cant find previous IP and cant start.
I would like to know ,is there a solution as SQL update itself IPs automatically?or I have to update IPs manually on every start up?
as I saw, when I changed my IPs and restart machine or SQL service it doesn't Modify Ip.
Thanks
Comment: Why do you configure SQL to listen to a specific IP if you're using DHCP?
Comment: You can't use static IP or Named Pipe?
Comment: @SimonLoh I cant use static IP but I dont know anything about Named Pipe and how can connect to remote Server with named pipe.
Comment: @OlaEkdahl I cant use static IP
Comment: @hamed - Instead of using IP, you were using computer name instead, that is named pipe
Comment: @SimonLoh only computer name or something like this : **server=np:\\hostname\pipe\pipeName**
Answer: Perhaps you may try Named Pipe?
http://devproconnections.com/database-development/sql-server-performance-tip-favoring-tcpip-over-named-pipes
Are your system hard-coded the IP address and not allowed to be change?
Comment: I want to have remote access to another machine. whether the named pipes are proper solution?
Comment: @hamed What do you mean by "remote access" ? Are you mean RDP in?
Comment: for using named pipes I should enable Named Pipes. whether I must Enable TCP/IP? is there need to determine user pass in connection string?
Comment: remote access means the client and server aren't on same machine
Comment: I found it is impossible to establish a remote access to remote server through named pipes without tcp/ip enabled and configured. if I want to configure tcp/ip I will connect through tcp/ip. as you know I dont want dealing with tcp/ip configuration since problem I said in my question


Alter pagination start index

Question: Is it possible to make the pagination system numbering correspond to the page number you are on?
For example, instead of having /media-releases (page 1), /media-releases?page=0 (page 1), and /media-releases?page=1 (page 2) having /media-releases (page 1), /media-releases?page=1 (page 1), and /media-releases?page=2 (page 2).
This seems like a small change, but I believe an important one for usability.
Comment: I answered [a similar question](http://drupal.stackexchange.com/questions/53736/how-to-configure-pager-numbers-match-uri-string-in-drupal-7/53741#53741). Although no real solution it might give some pointers.
Answer: You could do it by implementing hook_url_outbound_alter(), and hook_url_inbound_alter().
With the first hook, you alter the links that are being output from Drupal; you would increase the value of $options['query']['page'].
With the second hook, you alter the links being received from Drupal; you should find the '?page=' string in the URL, and decrease the number after that string.
Keep in mind that $_GET['page'] can be a string like '1,2,4,5,6' if the page has more than one pager. See the code of pager_find_page().
Also, hook_url_outbound_alter() receive the query parameters in $options, while hook_url_inbound_alter() receives just a string for the URL, which also contains the query part.

Alter pagination start index


Formatação de texto em um JTextPane

Question: Olá, tenho um JTextPane e gostaria de formatar partes de seu conteúdo. É possível fazer isto?
JTextPane areaDeTexto = new JTextPane();
areaDeTexto.setText = "Este texto está formatado em negrito.\nEste em itálico.\nEste em sublinhado.\nE este não está formatado!";

O que faço neste código?
Answer: Tente usar o html, colocar os textos nas tags ,  e , mas lembre de dar setContentType("text/html")
Tente usar o código abaixo
public class Formatar {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
            frame.setSize(300, 300);
            frame.setVisible(true);
        JTextPane tp = new JTextPane();
            frame.getContentPane().add(BorderLayout.CENTER,tp);
            tp.setContentType("text/html");
            tp.setText("Texto em Negrito, Texto em Itálico, Texto Sublinhado");
    }
}

Answer: A resposta do amigo Gui_Biem está muito boa!!
Mas vou deixar a minha também.
 Supondo que ambas as classes estejam no mesmo pacote:
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class EstiloTextPanel extends JTextPane {

    private Style negrito;
    private Style italico;
    private Style normal;

    public EstiloTextPanel(StyledDocument doc) {
        super(doc);
        initStyles();
    }

    public EstiloTextPanel() {
        super();
        initStyles();
    }

    private void initStyles() {
        normal = StyleContext.getDefaultStyleContext().getStyle(
                StyleContext.DEFAULT_STYLE);

        negrito = getStyledDocument().addStyle("bold", normal);
        StyleConstants.setBold(negrito, true);

        italico = getStyledDocument().addStyle("italic", normal);
        StyleConstants.setItalic(italico, true);
    }

    public void insertBoldText(String text) throws BadLocationException {
        getStyledDocument().insertString(getStyledDocument().getLength(), text,
                negrito);
    }

    public void insertItalicText(String text) throws BadLocationException {
        getStyledDocument().insertString(getStyledDocument().getLength(), text,
                italico);
    }

    public void insertNormalText(String text) throws BadLocationException {
        getStyledDocument().insertString(getStyledDocument().getLength(), text,
                normal);
    }

}

e também:
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.text.BadLocationException;

public class TestandoEstiloTextPanel extends JFrame {

    private EstiloTextPanel verPanel;

    public TestandoEstiloTextPanel() throws BadLocationException {
        super("FORMATADO");

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 300);
        setLocationRelativeTo(null);

        verPanel = new EstiloTextPanel();
        add(verPanel, BorderLayout.CENTER);
        verPanel.setEditable(false);

        verPanel.insertBoldText("Negrito\n");
        verPanel.insertItalicText("Itálico\n");
        verPanel.insertNormalText("Normal\n");

        setVisible(true);
    }

    public static void main(String[] args) throws BadLocationException {
        new TestandoEstiloTextPanel();
    }

}

Formatação de texto em um JTextPane


Is the main(String[] args) method predefined or user-defined in java

Question: The main() method is starting point of all java programs. All predefined methods are declared/defined in some class like println() method is defined in PrintStream class
Now WHERE is the main() method declared/defined? Its not present in the Object class, where I presumed it to be  .
Or is it that the main() method is a user-defined method. If so, why can't we say
    public static void main(int args){}

or
    public void main(String args){}

Please someone explain this,
Thanks in advance.
Comment: the main method is defined in the class you compile/run
Comment: this looks like a question posted minutes ago... maybe the homework for the weekend somewhere .....
Comment: You can perfectly define those two methods. They just aren't valid entry points for a Java program, because Java expects a static method, named main, returning void, and taking an array of Strings as argument.
Comment: Did you read [javadoc main method](https://docs.oracle.com/javase/tutorial/getStarted/application/#MAIN) ?
Comment: yes your right ,JRE calling exactly same format as you said .so main() method is some were declared. were it was declared this is my actual dout    Actually this question was asked in interview which i was attended.i given ans exactly as you said but he is not satisfied with ans @JBNizet
Comment: It's declared in your class. Java looks for such a declaration in the class you ask it to execute, and if it doesn't find it, it will display an error message and stop. That's all.
Comment: so I can say It was user defined method @JBNizet
Comment: Yes, you can say it like that.
Answer: Simply because the java program (i.e., java.exe on Windows) was written to use public static void main(String[]) as the entry point.  This is not a fundamental feature of the language.  It's entirely possible that some other program could use a different method as the entry point.
Answer: You can say:
public void main(String args){}

It's just that your program won't run, but it does compile.
The main method seems like magic at first sight, doesn't it?
It looks like a user-defined method (it is). yet all programs start here.
The trick here is java. When you run your program, you do a command like this, right?
java MyClass

Immediately after that, Java finds a .class file named MyClass and finds a class called MyClass in that file. Then it will automatically look for a main method with the exact signature:
public static void main(String[] args)

And then Java calls this. If you declare it any other way, Java can't find it.
Note that this is not a language feature. The JLS does not mention this at all. It's just how the java command is designed.
Comment: you are right ,but My actual Questions is it was predefined or user defined method.
Comment: It's a user defined. Maybe I was not clear enough, but my first sentence is saying that you _can_ declare it another way. The program still compiles but it won't run. I am kind of implying that it is defined by you. Sorry! @Srinu


Reading in a file - java.io.FileNotFoundException

Question: public void loadFile(int level){

    try {
                //Create new file
                levelFile = new File("assets/levels.txt");
                fis = new FileInputStream(levelFile);
                isr = new InputStreamReader(fis);
                reader = new BufferedReader(isr);

                //Code to read the file goes here

Using this code, however, I keep getting the above error (java.io.FileNotFoundException).
The file definitely exists in my Assets folder and has the correct name.  I've found a couple of similar questions on here and have tried various things including refreshing the project, cleaning the project, using "levels.txt" instead of "assets/levels.txt" but I keep getting this error.
Any ideas why?
Comment: And once again a downvote with no comment as to why.  This helps nobody.
Comment: The path is not what you think it is. Have you tried debugging?
Comment: Are these resources supplied by you or the user?  If by you, access them as an [tag:embedded-resource] by `URL`.  If the user, offer them a [`JFileChooser`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html).
Comment: Maybe you should know what current work directory is at first. System.out.println("Working Directory = " + System.getProperty("user.dir"));
Comment: @AndrewThompson This is s a file that is supplied by me.  It contains level layout information for my game which is exported from a little level creator / editor that I wrote using swing
Comment: Giving you an upvote to negate it. Sorry for the bad apples of the community.
Answer: Because you're dealing with outside the package, getResource() will be the best solution for your problem:
URL url = getClass().getResource("/assets/levels.txt");
File f = new File(url.toURI());
//....

Or you can directly get the input stream using getResourceAsStream() method :
InputStream  is= getClass().getResourceAsStream("/assets/levels.txt");
isr = new InputStreamReader(is);

It's better since you don't have to use FileInputStream.
Note that URISyntaxException must be caught with FileNotFoundException or declared to be thrown.
Comment: There is little point in converting the `URL` to a `File`.  Most methods/constructors that will accept a `File` will also accept an `URL`.
Answer: In an Android project, the right way to read the content of asset files is by using the AssetManager. Asset files are the files you put in the assets/ folder of your Android project. This is mentioned briefly in the sidebar on the Accessing Resources page in the Android docs.
In particular, you can open the file assets/levels.txt and create a BufferedReader like this:
InputStream stream = context.getAssets().open("levels.txt");
BufferedReader reader = new BufferedReader(
            new InputStreamReader(stream));

Notice that the argument of the open call is simply levels.txt, not assets/levels.txt.
For more details see the full docs of AssetManager.
Comment: This should be the accepted answer, as it is the proper Android way of reading local files.
Comment: Hi @Jabos yes this is an Android project.  Basically what I've done is, write a level editor in Java/Swing. This outputs level layout information to a text file which I put in my assets folder and then run the app on my tablet / handset.  Is this the correct way of doing this?  If I use inputStream as you've indicated in the last part of your answer, it doesn't seem to work how would I integrate this line into my code?  Do I use it instead of file levelFile = new file?  Thanks! :-)
Comment: @Zippy see my updated answer. This is the right way to read asset file content in an Android project.
Comment: Thank you for the answer @janos, for some reason I had trouble with this, so I used Azad's similar answer.  Thanks :-)
Comment: @Zippy I amended my answer to be really specific. This is the right way of doing this, and I've never had a problem with it. If you have trouble with this method, then I you must be doing something wrong. You should fix *that*, rather than choosing a less clean solution.


How would you describe this set in plain English?

Question: To me it seems like this set is equivalent to set of all integers?
$\{n \ | \ n \ \text{is an integer and} \ n = n + 1\}$
Comment: The empty set? Or is there a typo?
Comment: I'd say the empty set as well. It's not possible to have $n=n+1$.
Comment: It's not a typo. It's a bit strange. I agree. I found this in Sipser's Theory of Computation book -- Chapter 0.
Comment: After edit. Still the empty set :) Are you trying to base something on Peano's axioms?
Comment: @CindyAnderson Not strange at all. A perfectly reasonable definition of the empty set!
Comment: Ok thank you for the confirmation.
Answer: The set with no elements, i.e, the empty set.


Menu Item won't respond to click

Question: the "Exit" MenuItem responds perfectly but the "Change Name" is a problem.. i can't figure out whats wrong, Can Someone help please... I know the userName.setUserName is working ok.. cuz i'm using it in another class and it works perfectly. just can't figure out whats wrong
Here's the code
public class MenuBar extends JMenuBar{

    // variable declaration
    private JMenu menu;
    private JMenuItem menuItem;
    private JMenuItem changed_Name;
    private JMenuItem exit;

    public MenuBar(){

        init();

    }

    private void init(){

       menu = new JMenu("File");
       add(menu);

       changed_Name = new JMenuItem("Change Name");
       changed_Name.setMnemonic(KeyEvent.VK_C);
       changed_Name.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.ALT_MASK));
       changed_Name.getAccessibleContext().setAccessibleDescription("This Will Allow a Name Change");
       menu.add(changed_Name);

    exit = new JMenuItem("Exit");
    menu.add(exit);

    menu = new JMenu("Help");
    add(menu);

    menuItem = new JMenuItem("Help & Docs");
    //menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, KeyEvent.CHAR_UNDEFINED) );
    menuItem.getAccessibleContext().setAccessibleDescription("Get Help or View Software documents");
    menu.add(menuItem);

    menuItem = new JMenuItem("About");
    menu.add(menuItem);

    MenuHandler menuHandler = new MenuHandler();
    menuItem.addActionListener(menuHandler);
    exit.addActionListener(menuHandler);

}

private class MenuHandler implements ActionListener{

    AgentName userName = new AgentName();

    @Override
    public void actionPerformed(ActionEvent e) throws UnsupportedOperationException {

            Object menuItem_Command = e.getActionCommand();

            if(menuItem_Command.equals("Change Name")){
                userName.setUserName(userName.getUserName());
            }
            else if(menuItem_Command.equals("Exit")){
                System.exit(0);
            }

    }

}
}

Comment: problem seem to be `menuItem_Command.equals("Change Name")` to check yourself what is going on, I suggest you to [check how to debug your app in Eclipse](http://www.vogella.com/tutorials/EclipseDebugging/article.html) tellme if you are using different IDE
Answer: You never register the MenuHandler with the changed_name JMenuItem...
Also, beware, you are reassigning menuItem multiple times, meaning hat only About is been registered with the MenuHandler
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setJMenuBar(new MenuBar());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MenuBar extends JMenuBar {

        // variable declaration
        private JMenu menu;
        private JMenuItem menuItem;
        private JMenuItem changed_Name;
        private JMenuItem exit;

        public MenuBar() {

            init();

        }

        private void init() {

            menu = new JMenu("File");
            add(menu);

            MenuHandler menuHandler = new MenuHandler();

            changed_Name = new JMenuItem("Change Name");
            changed_Name.setMnemonic(KeyEvent.VK_C);
            changed_Name.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.ALT_MASK));
            changed_Name.getAccessibleContext().setAccessibleDescription("This Will Allow a Name Change");
            changed_Name.addActionListener(menuHandler);
            menu.add(changed_Name);

            exit = new JMenuItem("Exit");
            menu.add(exit);

            menu = new JMenu("Help");
            add(menu);

            menuItem = new JMenuItem("Help & Docs");
            //menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, KeyEvent.CHAR_UNDEFINED) );
            menuItem.getAccessibleContext().setAccessibleDescription("Get Help or View Software documents");
            menuItem.addActionListener(menuHandler);
            menu.add(menuItem);

            menuItem = new JMenuItem("About");
            menuItem.addActionListener(menuHandler);
            menu.add(menuItem);

            exit.addActionListener(menuHandler);

        }

        private class MenuHandler implements ActionListener {

//          AgentName userName = new AgentName();

            @Override
            public void actionPerformed(ActionEvent e) throws UnsupportedOperationException {

                Object menuItem_Command = e.getActionCommand();

                System.out.println(menuItem_Command);

                if (menuItem_Command.equals("Change Name")) {
                    System.out.println("Yippe");
//                  userName.setUserName(userName.getUserName());
                } else if (menuItem_Command.equals("Exit")) {
                    System.exit(0);
                }

            }

        }
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }
}

Generally speaking, you should really need to extend JMenuBar, but simply create an instance and add the menus you need to it
You may also consider having a look at How to Use Actions, which are self contained units, which contain their own configuration and action logic
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import static javax.swing.Action.ACCELERATOR_KEY;
import static javax.swing.Action.MNEMONIC_KEY;
import static javax.swing.Action.NAME;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setJMenuBar(new MenuBar());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ChangeNameAction extends AbstractAction {

        public ChangeNameAction() {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.ALT_MASK));
            putValue(MNEMONIC_KEY, KeyEvent.VK_C);
            putValue(NAME, "Change Name");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Change name");
        }
    }

    public class ExitAction extends AbstractAction {

        public ExitAction() {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_4, KeyEvent.ALT_MASK));
            putValue(MNEMONIC_KEY, KeyEvent.VK_X);
            putValue(NAME, "Exit");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    public class HelpAction extends AbstractAction {

        public HelpAction() {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
            putValue(MNEMONIC_KEY, KeyEvent.VK_H);
            putValue(NAME, "Help & Docs");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Help and docs");
        }
    }

    public class AboutAction extends AbstractAction {

        public AboutAction() {
            putValue(NAME, "About");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("About");
        }
    }

    public class MenuBar extends JMenuBar {

        // variable declaration
        private JMenu menu;
        private JMenuItem menuItem;
        private JMenuItem changed_Name;
        private JMenuItem exit;

        public MenuBar() {

            init();

        }

        private void init() {

            menu = new JMenu("File");
            add(menu);

            menu.add(new ChangeNameAction());
            menu.add(new ExitAction());

            menu = new JMenu("Help");
            add(menu);

            menu.add(new HelpAction());
            menu.add(new AboutAction());

        }

        private class MenuHandler implements ActionListener {

    //          AgentName userName = new AgentName();
            @Override
            public void actionPerformed(ActionEvent e) throws UnsupportedOperationException {

                Object menuItem_Command = e.getActionCommand();

                System.out.println(menuItem_Command);

                if (menuItem_Command.equals("Change Name")) {
                    System.out.println("Yippe");
                    //                  userName.setUserName(userName.getUserName());
                } else if (menuItem_Command.equals("Exit")) {
                    System.exit(0);
                }

            }

        }
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }
}

Comment: it was actually that.. can't believe i missed that.. i had registerd exit but forgot for Chane Name.. thanks much mad pro
Comment: @Juice It's easy to miss
Answer: It is probably working, but you do not get feedback because you are changing the name to the previous one. If you put some other value in the  setUserName method you will see

Menu Item won't respond to click


Random permutation with a scientific calculator

Question: I have 8 people whom I want to divide into 2 groups. The allocation must be uniformly at random, i.e., every person must have equal probability of joining either group.
We came across a situation where we had to do this, but we did not think about the process deeply. All we had at our hands was a scientific calculator to generate the randomness. We asked the first person to generate a random integer from 1 to 8. Odd numbers and even numbers generated two different groups. The second person kept generating a number till he had a number different from the first person's number, and so on. However in this method, the probability of the second person to join either groups is not the same.
The task is pretty simple if we can have a random permutation of $\{1,2,\ldots,8\}$, but all we had was a calculator. How best could we have accomplished this task?
Comment: Your approach is the same as @user51547's, and they are both uniform. You say "the second person has a different probability to join each group", but there was a 50% chance that he would be forced to choose from 4 odd and 3 even, and a 50% chance for 3 odd and 4 even. Your method is fair.
Comment: There are $\binom{8}{4}=70$ ways to divide people into two groups. Assign each of these a number from $1$ to $70$ then use the calculator to generate a random number between $1$ and $70$.
Comment: Assign each person a number 1-8, and repeatedly sample from {1,...,8} until you have four distinct numbers.
Answer: If the groups don't have to be equinumerous, you can draw for each person a number from $\{0,1\}$. We have to exclude the situations, where all people are going to one group, ie. the drawn sequence is $[0,0,0,0,0,0,0,0]$ or $[1,1,1,1,1,1,1,1]$.
There also occurs a negative draws (eg. $[0,0,0,1,1,1,0,1]$ and $[1,1,1,0,0,0,1,0]$), but for each division there are exactly two different draws, so it doesn't affect the probability.
You can then draw a random number $n$ from $\{1,2,...,2^8-2\}$ and divide people using its' binary representation (eg. for $n=38$ the sequence will be $[0,0,1,0,0,1,0,0]$).


java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Question: I am developing a Java EE application in which I need Base64 Encoding/Decoding
So I added commons-codec-1.5.jar in WEB-INF/lib folder of my application and used
import org.apache.commons.codec.binary.Base64;

in the Java file.
During compile time, when I type Base64, it shows encodeBase64String method is available. But during runtime it is throwing an exception like this:
java.lang.NoSuchMethodError:org.apache.commons.codec.binary.Base64.encodeBase64String

I have the JAR in the buildpath, but still I don't understand why it throws me the above error.
Comment: Post how you are calling this method.
Answer: That method was introduced in Commons Codec 1.4. This exception indicates that you've an older version of Commons Codec somewhere else in the webapp's runtime classpath which got precedence in classloading. Check all paths covered by the webapp's runtime classpath. This includes among others the Webapp/WEB-INF/lib, YourAppServer/lib, JRE/lib and JRE/lib/ext. Finally remove or upgrade the offending older version.

Update: as per the comments, you can't seem to locate it. I can only suggest to outcomment the code using that newer method and then put the following line in place:
System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation());

That should print the absolute path to the JAR file where it was been loaded from during runtime.

Update 2: this did seem to point to the right file. Sorry, I can't explain your problem anymore right now. All I can suggest is to use a different Base64 method like encodeBase64(byte[]) and then just construct a new String(bytes) yourself. Or you could drop that library and use a different Base64 encoder, for example this one.
Comment: I updated my answer with a code line which should give you further insight as to where the `Base64` class is actually been loaded from during runtime.
Comment: Another strategy to pinpoint if its same class thats being picked or a different one is to use reflection to print out all public methods of Base64 class.
Comment: @BalusC-I cleaned and build the project.Then i deployed my WAR into tomcat.Interestingly it started working fine.Please see this another question of mine regarding java [link](http://stackoverflow.com/questions/7687100/org-apache-http-util-encodingutils-getbytespostdata-base64-removing-from)
Comment: Thanks for the reponse BalusC.I searched my whole system for this jar.I could not find any old jar anywhere in my system.All i have is a commons-codec-1.5.jar in my Webapp/WEB-INF/lib
Comment: @BalusC-the above System.out.printed the following                                                      file:/C:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/Project_name/WEB-INF/lib/commons-codec-1.5.jar
Comment: That is plain weird. I'd have guessed that you were using Glassfish 3.0.x which has version 1.3 in its lib, but I see that you're actually using Tomcat 7.0.x which shouldn't have any Commons Codec in its lib. Right now I can't suggest anything else than just using another method or to replace Commons Codec Base64 by a different Base64 encoder/decoder implementation.
Comment: By the way, which JARs do you have more in your `/WEB-INF/lib`? Perhaps one of them is repackaging Commons Codec. Even though I'd have expected that the code source location would have returned it..
Comment: @BalusC-I was using Sun's encoding previously.I came through this [doc](http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html). Then i changed to apache commons-codec.I will try with the above and let you know.
Comment: @BalusC- i have the following jars in the WEBINF/lib: activation.jar,aspectjweaver.jar,axis.jar,classes12.jar,commons-beanutils-1.8.3.jar,commons-codec-1.5.jar,commons-collections-3.2.jar,commons-dbcp-1.3.jar,commons-digester-1.8.jar,commons-discovery-0.4.jar,commons-logging-1.1.1.jar,commons-pool.jar,jaxrpc.jar,mail.jar,saaj.jar,servlet.jar,webserviceutils.jar,wsdl4j.jar
Comment: I don't recognize any which could have repackaged codec. But that `servlet.jar` definitely doesn't belong there. Remove it. Tomcat has already its own.
Comment: @BalusC, that line of code gives a null pointer error. anyway how can i access encoder and decoder methods in Base64.class, I am using eclipse and it can't locate those methods
Answer: Some Google tooling such as GWT has an embedded version of commons-codec with a pre-1.4 Base64 class. You may need to make such tooling JARs inaccessible to your code by refactoring your project such that only the parts of your code that need that tooling can see the dependency.
Answer: @Adam Augusta is right, One more thing
Apache-HTTP client jars also comes in same category as some google-apis.
org.apache.httpcomponents.httpclient_4.2.jar
and commons-codec-1.4.jar both on classpath, This is very possible that you will get this problem.
This prove to all jars which are using early version of common-codec internally and at the same time someone using common-codec explicitly on classpath too.
Answer: Download  this jar
It resolved my problem, this is 1.7.
Answer: I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib
Comment: This solved my problem. I am using JBoss 5.1.0 GA and deploy a EAR on this server. I need the commons-codec 1.6 for an api included in the project. The JBoss server has a commons-codec 1.3 jar in his lib folder. I want to deploy all libs needed by my project in the ear, than this error occurs. When I copy the commons-codec 1.6 in the lib folder (the old one still exist), it works.
Answer: You need the Apache Commons Codec library 1.4 or above in your classpath.
This library contains Base64 implementation.
Answer: Try add 'commons-codec-1.8.jar' into your JRE folder!
Answer: Simply create an object of Base64 and use it to encode or decode, when using org.apache.commons.codec.binary.Base64 library
To Encode

Base64 ed=new Base64();
String encoded=new String(ed.encode("Hello".getBytes()));

Replace "Hello" with the text to be encoded in String Format.
To Decode

Base64 ed=new Base64();
String decoded=new String(ed.decode(encoded.getBytes()));

Here encoded is the String variable to be decoded


Code showing on every content page

Question: I'm pretty new to Drupal but have take my company's half-baked site from the server and gotten a working instance of it in my local wamp stack working.  The only problem is that it seems on every page there is a section of code being inserted:
<?php
if ( isset($entity->field_job_id['und'][0]['safe_value'] )) {
   $job_id = $entity->field_job_id['und'][0]['safe_value'] ;
   $application_link_form = '
<form action="/careers/application" method="POST">
    <input type="hidden" name="job_id" value="' . $job_id . '" />
    <input type="submit" value="Apply online" class="job-application-link" />
</form>';
   print $application_link_form;
}
 ?>

This is showing a section of this code plus an "Apply Online" button at the top of each section of content.  It doesn't seem to matter what the content type of the content and the site which I imported all the files and db from has no such code - not even when I view source is there anything even commented out.  Hopefully this code gives you some context as to where this is ocurring - it comes immediately following this series of divs:

In any case, I cannot figure out where to find this code in order to get rid of it.  I'm not seeing any modules relating to this, etc.  And I just am baffled as to why it would start showing up after importing from a site that doesn't display this.  If anyone can think of any possibilities, please let me know!
Comment: Have you tried finding the code? With grep, or an IDE, or any other search tool?
Comment: Thanks for the suggestion.  I just searched on numerous pieces within the code, includign "job_id" "/careers/application" "application_link_form" etc., and come up with nothing - searching within c:\wamp\www.
Comment: PHP code in a Custom Content Panel pane??
Answer: If it's not in the source, it's in the DB. At a guess, this is code that someone entered using the PHP filter, but the PHP filter is not active so it's showing up as text.
As to where it is in the DB, there's many possibilities. I'd use brute force to search the DB in its entirety. (That's easy for me to say as I have a copy of SQLyog to hand. I'm sure there are other tools that provide this functionality, though: I think PhpMyAdmin has it.)
Addendum: looks like it's in a custom pane, so the table panels_pane is the most likely culprit. Ideally you want to find how it's getting inserted onto the page. Do you have the module Panels Everywhere enabled?
Comment: `drush sql-dump | grep` makes such a search trivial almost everywhere :) (Except on windows of course)
Comment: It's being loaded as a block I think so admin/structure/blocks should help you locate it and disable it. It's a very bad idea to have PHP in a block.
Comment: Thanks. I used phpMyAdmin and the only reference to job_id was a row in the webform_component table.  I also looked in the filter module.  The only difference between my version and the one on the server for that is that the one on the server is as follows.  Both have an entry for Display Suite but when going in to configure those, on the server there is a checkbox (checked) for Display Suite Evaluator whereas that does not show up for the local instance. The Display Suite module I have locally is more recent then the one on the server. Should I try to remove it and install an earlier version?
Comment: Sorry, I did not see your addendum.  Panels is enabled for Node Template Home, and Job openings.  Is that helpful?
Comment: Ok, I drilled down into the Note Template and in the preview I get the exact code that is coming through.  Here's the url that I'm at: http://localhost/admin/structure/pages/nojs/operation/node_view/handlers/node_view_panel_context/preview.  So the question is, how do I get this not to show?
Comment: One more item of note - on the public site, the button (which say Apply for Job is viewable on nodes that are of Job content-type.  Only those, though, whereas on my local instance it's showing for everything...
Comment: The PHP is checking for a field which presumably doesn't exist on other types, so that's why the button doesn't appear everywhere. There are much better ways to achieve the same end, but to enable it to be executed you need to enable the Display Suite customer text format. I have never used it but it is described in the Display Suite documentation so if you hunt around you should find how to turn it on.
Answer: I consulted a Drupal expert in our company who looked through the instance.  He diagnosed a couple of causes.  For one, the PHP Filters module was not enabled.  Additionally, I needed to set the PHP Evaluator option for "Display Suite Code" (in Configuration > Content Authoring > Text Formats > Display Suite Code).  These two items fixed the issue.
According to him, the code was in the panels in order to display an Apply Online button conditionally above some content.  He thought it was unnecessarily complex to do it in the way the previous Drupal Dev did it.  Being a newb, I wouldn't presume to offer my own opinion. ;-)
Answer: As Alfred says, it's going to either be in the code or the database.
If you have the sql data dump, you can open that in a text editor and search for the code.
The fact that it's found here in your html

... leads me to think that it's a block within your content region that's injecting this code.
Go to Admin > Structure > Blocks and see what blocks are enabled in the content region, try disabling them.
Comment: The `block-system-main` block is the system block that contains page content.  It's not actually a real block *per-se*.
Comment: Only one block is enabled and changing that had no effect.

Code showing on every content page


Excel Formula Help: Within 1 week, but no more than one week

Question: I am looking to create a formula in which

if the date is passed today it will display "OVERDUE",
if the date is within 7 days from today/a week from today then it would display "1 week left",
but if the date is more than a week away then the cell will remain blank.

The Overdue and 1 week left command are working, but not the third. I don't know how to contain the 1 week formula to just within 1 week so that it doesn't overlap with the third.
e28 and down is my date assigned column
g28 and down is my reminder/status column

=IF(ISBLANK(E28),"", IF(E28TODAY()-7,"1 WEEK LEFT!", IF(E28>TODAY()-8,""))))

*sorry I'm new. This post is erasing my less than and greater than signs.
Your help will be greatly appreciated!! Thank you in advance.
Answer: Use
<code>=IF(E28-TODAY()>0,"Overdue",IF(TODAY()-E28<=7,"1 WEEK LEFT",""))
</code>
Answer: Try the following formula:
<code>=IF(ISBLANK(E28),"",IF(E28<TODAY(),"OVERDUE",IF(E28-TODAY()<=7,"1 WEEK LEFT!",IF(E28-TODAY()>7,""))))
</code>


Code Refactoring Trying to use Polymorphism and std::map

Question: I have this class
struct B {
   B( int x=0 ) { }
   virtual void something() {
          std::cout << "B()";
   }
};

struct A {
     B b;
     int a;
     A( int a, int b_ ) : a(a), b(b_) {a}
};

I have implemented another class C
 struct C : public B {
   C( int x ) : B(b) { }
   virtual void something() {
          std::cout << "C()";
   }
};

What is the best way to get A use C instead of B ?
I already tried this :
struct A {
         B  & b;
         int a;
         A( int a, B &b_ ) : a(a), b(b_) {a}
    };

But then I have to use std::map<int, A>
which is giving compilation errors:
'A::A' : no appropriate default constructor available.

so i did this :
struct A {
             B  & b;
             int a;
             A( int a=0, B &b_=B() ) : a(a), b(b_) {a}
        };

in my main
std::map<int,A> mmap;
for( int i=0;i<5;++i ) {
   auto & b = C();
   mmap.insert( std::make_pair(i,A(i,b) ) ) ;
}

but these C's object in mmap's A become B as soon as auto & b goes out of scope.
Its not working. How to fix it ?
Comment: You can't bind temporaries to non-const references.
Comment: @chris what should i do then in the constructor of A ?
Answer: In the A constructor, you try to assign a temporary instance of B to reference to B, which is illegal.
What you have to do is to change this reference by a pointer to this class :
#include <iostream>
#include <memory>
#include <map>

using namespace std;

struct B {

   B( int x=0 ) { }
   virtual void something()
   {
        std::cout << "B()";
   }
};

struct A {
        shared_ptr b;
        int a;
        A( int a = 0, shared_ptr b = shared_ptr(new B()) ) : a(a), b(b) {}
};

struct C : public B {
    C( int x ) { }
    virtual void something()
    {
        std::cout << "C()";
    }
};

int main()
{
    shared_ptr b = shared_ptr( new C(0));
    // Polymorphic test
    b->something();

    A a (0, b);
    // map test
    map<int, A> my_map;
    my_map[0] = a;

    return 0;
};

If you can not use C++11, just change smart pointers by naked pointers and handle the dynamic memory properly as usual. Or even better : use the Boost library, as mentioned by chris.
Comment: `make_shared` is a much better option for initialization, and there's always `boost::shared_ptr` pre-C++11 :)
Comment: Oh yes, I forgot to mention the boost library sorry. But I didn't know for make_shared. Thank you for the tips. Usually I use the "reset" method of the smart pointer, because it's simpler and shorter. (and also "auto")
Comment: is it not possible with Reference ?
Comment: No, because you have to have a default constructor for A which means that you have to pass to the reference a "fake" value if there is no parameter, which is illegal. You can achieve this with naked pointers but it will be ugly compared to the solution with smart pointer.

If you can't use C++11, you must take a look at the boost library to avoid a lot of headache during debugging and memory leak tracking :)


Swapping rows within the same pandas dataframe

Question: I'm trying to swap the rows within the same DataFrame in pandas.
I've tried running
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0], a.iloc[1]
a.iloc[0], a.iloc[1] = c, b

but I just end up with both the rows showing the values for the second row (3,4).
Even the variables b and c are now both assigned to 3 and 4 even though I did not assign them again. Am I doing something wrong?
Answer: Use a temporary varaible to store the value using .copy(), because you are changing the values while assigning them on chain i.e. Unless you use copy the data will be changed directly.
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0], a.iloc[1]

temp = a.iloc[0].copy()
a.iloc[0] = c
a.iloc[1] = temp

Or you can directly use copy like
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0].copy(), a.iloc[1].copy()
a.iloc[0],a.iloc[1] = c,b

Comment: Yes by default they hold the reference to main object . Whatever changes  you do will reflect on main object. So u need copy.
Comment: Oh yes this solved the problem. Many thanks! I'm still unsure about when values are on a chain. Would you say that it would be safer to just always use the `.copy()` method when I am assigning new variables?
Answer: The accepted answer does not make changes the index name.
If you only want to alter the order of rows you should use dataframe.reindex(arraylike). Notice that the index has changed.
Comment: Yes, using `.reindex()` is the one.
Answer: In this way, it can be extrapolated to more complex situations:
a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
rows = a.index.to_list()
# Move the last row to the first index
rows = rows[-1:]+rows[:-1]
a=a.loc[rows]

Answer: df = pd.DataFrame(data = [[1,2],[4,5],[6,7]], index=['a','b','c'], columns = ['A', 'B'])

df

df.reindex(['a','c','b'])


How do I disable the "code not covered" glyphs in the OpenCover UI extension for Visual Studio 2015?

Question: I would file a bug report but it seems like such an obvious piece of functionality that I must be missing something...
These are the glyphs that appear in the editor window in the same bar as the breakpoints to indicate that a line of code was not covered by my unit tests.
I'd like to disable them temporarily since they cover up my breakpoints.
Extension I'm talking about
Answer: Clicking on menu OpenCover -> OpenCover Results will open a window (unless it is alrady open and docked somewhere)
In the top of this window, there are 3 menu buttons. The middle one enables\disables the glyphs (circles).


HKEY CURRENT USER - Key intermittently disappears

Question: I have a TFS build that runs on a server and requires a registry key to be available. More details about this here:
https://stackoverflow.com/a/25054572/426422
My problem is that once in a while this key vanishes from HKCU without a trace.
To my knowledge there aren't any server restores or anything going on. The user account the key is under is a tfs service account and so no user is logging in and doing anything out of the ordinary either.
What could cause a registry key in HKCU to just intermittently disappear like this?
Answer: You could run Process Monitor on the server and filter on that specific registry key. When it's deleted it will show up with who did it and then you can investigate why
Comment: I don't think anyone is logging in as the service account and deleting anything. There are only two folks who know the password and one of them is me.
Comment: Running this will tell you who/what/when deleted it and then you can start you investigation of why
Comment: I understand about Process Monitor but I am asking if there are any common reasons aside from human intervention as to why a key could disappear. I've never heard of keys just vanishing.
Comment: you could have some configuration management software that is removing it, AV software, ect. You wont know until you perform the auditing with a tool


Pseudo Class :current

Question: I am trying to make my menu bar background go black when you are on that page, eg. if you're on the SFX page the SFX tab will be black, not red.
This is my HTML:

            Home
            Editorial
            SFX
            Occasion
            Artwork
            Body Painting
            Contact
            About

And My CSS:
#menuBar {
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
    width: 810px;
    height: 30px;
    top: 53px;
    vertical-align:central;
}
#menuBar a {
    background: #AA0000;
    padding-top: 2px;
    padding-bottom: 2px;
    padding-left: 11px;
    padding-right: 11px;
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
    color: Beige;
    text-decoration: none;
    font-weight:bold;
    font-size:18px;
    font-family: Gabriola,"Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, sans-serif;
}

#menuBar a:hover {
    background: #000000;
    transition:all .3s ease-in-out;
    -moz-transition: all .3s ease-in-out;
    -o-transition: all .3 ease-in-out;
    -webkit-transition: all .3s ease-in-out;
}

#menuBar a:focus {
    background:#000000;
}

#menuBar a:current {
    background:#000000;
}

I've tried everything, and its not working. I'm sure it's something simple, but i don't know what it is
Answer: Besides being a brand new pseudo-class that was introduced only relatively recently, :current does not mean what you think it means. Ironically, the same draft does propose another new pseudo-class for links to the current document, called :local-link, but neither of these are implemented because they've only just recently been proposed. (In fact, I just discovered that :local-link has been removed from the Selectors 4 ED as of May 2014 — no idea why, but odds that such a pseudo-class ever gets implemented just got much worse.)
Either way, there is currently no pseudo-class for links that point to the current page. You will need to use PHP to determine which of these links points to the current page, add a class="current" to the appropriate element, and target that class.

Pseudo Class :current