Add www subdomain to my Wildcard Virtualhost

Question: On my local dev server, I set up test sites with the domain like this projectName.dev
Using the setting below in my Apache config file...
NameVirtualHost *:80

<VirtualHost *:80>
   VirtualDocumentRoot  E:/Server/htdocs/projects/%1/www
   ServerAlias *.dev
</VirtualHost>

This allows me to access projectName.dev in the browser and it will load the files from E:/Server/htdocs/projects/projectName/www/
I would like to modify this so that I can also access the same folders if I use the subdomain www so in my example projectName.dev and www.projectName.dev would load the same files.
Can someone help me to do this?  I don't understand the documentation very well
Answer: You could try the following
NameVirtualHost *:80

<VirtualHost *:80>
   VirtualDocumentRoot  E:/Server/htdocs/projects/%-2/www
   ServerName staging.dev
   ServerAlias *.dev www.*.dev
</VirtualHost>

You can use %-2 to always get the "project" name. %-2 give you the second part of the url from the end. For e.g., if url would be http://project1.dev/ then the docroot would be E:/Server/htdocs/projects/project1/www
Comment: Thanks for the help.  Unfortunately this results in the same problem I kept running into...the `project.dev` will load the correct data and `www.project.dev` loads a default apache 404 page
Comment: I have updated my answer.
Comment: 2-3 years of trying to get this to work for my Dev server...I have asked this exact question at least 2-3 times on Serverfault in that time and you are the first one to give me a working solution...THANK YOU!!!
Answer: The ALex_hha reply is correct, the problem is the %1 in the VirtualDocumentRoot. that is replaced by the hostname used. using both multiple wildcard variants and VirtualDocumentRoot is always tricky.
You have 2 solutions:

replace the %1 my a hardcoded projectName.dev.
If you have many projects you would need to create a virtualhost config for each project, but just for one is a good workaround.
create 2 configs:
# www.project.dev format
<VirtualHost *:80>
  VirtualDocumentRoot  E:/Server/htdocs/projects/%2+/www
  ServerName www.*.dev
</VirtualHost>

# project.dev format
<VirtualHost *:80>
  VirtualDocumentRoot  E:/Server/htdocs/projects/%1/www
  ServerName *.dev
</VirtualHost>

the %2+ says that you want the second and forward part of the hostname received. Check the mod_vhost help page for more info
You are not using a unix, but on unix you could also do a symbolic link from the www names to the project names:
cd /srv/
for i in *; do
   # bypass if not a directory
   if [ ! -d "$i" ]; then continue; fi
   # bypass if already created
   if [ -e "www.$i" ]; then continue ; fi
   # bypass if already a www
   echo $i | fgrep -q "www" && continue
   ln -s $i www.$i
done

This way both the projectname and www.projectname point to the same place


Does natural parameter of exponential family need the constant or sign?

Question: For instance the exponential form of gamma distribution is $e^{(\alpha -1)\ln{x}-\beta x+ (something \ about \ only \ \alpha \ and \ \beta) }$, the natural parameters given on wikipedia are $(\alpha -1)$ and $-\beta$, but why not $\beta $ for the second one. Do constants&sign not affect sufficient statistics and natural parameters?
Answer: Well if i get ur question right u are wondering if the form of the parameters affect the distribution? The distributions have a specific form and u can't change it. If u changes -b to b then  $e^{4lnx−3x+(something about only α and β)}$ would belong to the distribution $Gamma(5,-3)$ but in reality it belongs to $Gamma(5,3)$ so yes it is essential that u keep the forms as they are. Of course there are transformations in every distributions formula so u can do different mathematical approaches but they are used intact.
Comment: But then how to we determine the natural parameter& sufficient statistics if we do know that it is a gamma? I am just wondering why is it -$\beta$ at the begining
Comment: In some cases u study a characteristic of a population knowing which distribution follows making assumptions knowing it. In other cases u study a characteristic without knowing the distribution, trying to make one with properties that corresponds to the population. In any case for, every known distribution there are some variables that characterize it. Ex:$Gamma(a,b)$,$Νormal(μ,σ)$,$Exp(θ)$ if u know in which one distribution family a population belongs (gamma family for example), by studying ur sample u can find the (a,b) of the specific gamma the sample belongs.


how to test constants in module?

Question: I have the following module:
 angular.module('config', []).constant('myconstant', somevalue);

I would like to unit test this so I created:
describe('Constants', function () {
  var config;

  beforeEach( inject(function (_config_) {
    module('config');
    config =_config_;
  }));

  it('should return settings',function(){
    expect(config.constant('myConstant')).toEqual('somevalue');
  });

});

Getting an error now:
 Error: [$injector:unpr] Unknown provider: configProvider <- config

How can I fix this?
Comment: It's a constant...it should have zero behavior and it shouldn't be changing.  Why do you want to test it?  This seems like the wrong place to focus your testing efforts.
Comment: Your right dude what was I thinking
Answer: You should be injecting your constant like any other service and not your module. This works for me:
angular.module('config', []).constant('myconstant', 'somevalue');
describe('Constants', function () {
      var myconstant;

      beforeEach(module('config'));

      beforeEach( inject(function (_myconstant_) {
          myconstant =_myconstant_;
      }));

      it('should return settings',function(){
        expect(myconstant).toEqual('somevalue');
      });

    });

how to test constants in module?


Migrating to proj API 6+ without forcing crs input

Question: I'm posting this question here instead of gis.stackexchange.com because I think this is more of a programming question than a GIS question.
The proj migration guide explains how to convert code to proj 6 and later by turning code that looked like this (error handling omitted for brevity):
projPJ pj_longlat = pj_init_plus(source);
projPJ pj_merc = pj_init_plus(target);
pj_transform(pj_longlat, pj_merc, ...)

into code that looks like this:
PJ *P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, source, target, NULL);
proj_trans(P, PJ_FWD, ...);

This is what was done in several projects including mapnik but there is one downside: with the new code, both source and target must be a CRS or otherwise proj_create_crs_to_crs will fail with:
proj_create_operations: source_crs is not a CRS

This means that some applications (for example I successfully used mapnik rendering with a +proj=pipeline projection, which is not a CRS) are not possible anymore.
In a proj issue report a developer points out that it should be possible to avoid proj_create_crs_to_crs by using proj_create manually. But if I understand it correctly, then to create a PJ object that transforms from source to target (and vice-versa) I need a pipeline but if one of my projections contains a pipeline, then this will not work because I cannot have nested pipelines.
So how would I convert code from the PROJ 4 to PROJ 6 API but without removing the ability to input arbitrary transformations, even those that are not a CRS?
Edit
I asked the same question on the PROJ mailing list and got this very helpful reply from Even Rouault. I'll use that to try and implement a solution.
Answer: With help from Even Rouault I managed to submit a pull request to mapnik which will use an alternative code path if the input transforms are not a CRS:
https://github.com/mapnik/mapnik/pull/4309
Essentially, this is doing the following (error checking omitted for brevity):
ctx_ = proj_context_create();
std::string crs_source = pj_add_type_crs_if_needed(source);
PJ *src = proj_create(ctx_, crs_source.c_str());
std::string crs_dest = pj_add_type_crs_if_needed(dest);
PJ *dst = proj_create(ctx_, crs_dest.c_str());
if (proj_is_crs(src) && proj_is_crs(dst)) {
    /* insert proj_create_crs_to_crs and friends from
     * the official migration guide here */
} else {
    /* either src or dst is not a crs, so we need to set
     * up the pipeline ourselves */
    auto formatter = osgeo::proj::io::PROJStringFormatter::create();
    formatter->startInversion();
    formatter->ingestPROJString(source);
    formatter->stopInversion();
    formatter->ingestPROJString(dest);
    transform_ = proj_create(ctx_, formatter->toString().c_str());
}
proj_destroy(src);
proj_destroy(dst);
return transform_;

Most notably, the above alternative codepath does not call proj_normalize_for_visualization, so the user is on their own in case they provide a non-CRS transform that would need normalization.
The function pj_add_type_crs_if_needed comes from the PROJ codebase in src/4D_api.cpp and adds a  +type=crs suffix to a PROJ string (if it is a PROJ string) and can be written like this:
std::string pj_add_type_crs_if_needed(const std::string &str) {
    std::string ret(str);
    if ((str.rfind("proj=", 0) == 0 || str.rfind("+proj=", 0) == 0 ||
         str.rfind("+init=", 0) == 0 || str.rfind("+title=", 0) == 0) &&
        str.find("type=crs") == std::string::npos) {
        ret += " +type=crs";
    }
    return ret;
}


How can I prove that $\cos(\sin x)>\sin(\cos x)$ when $0\leq x\leq \pi$

Question: I had a midterm a few days ago,.. and my question goes like this.
Prove $\cos(\sin x)>\sin(\cos x)$ where $0\leq x\leq \pi$
Also, you can use sinx>x when x>0 without proving it.
How can I prove it strictly?
Comment: see https://math.stackexchange.com/questions/351846/show-that-the-equation-cos-sin-x-sin-cos-x-has-no-real-solutions?answertab=votes#tab-top
Comment: $sin x$ is smaller then $x$ on for $x$ greater then 0
Comment: In particular, see the first answer mentioned in user222031's link.
Answer: $$\cos\sin{x}-\sin\cos{x}=\sin\left(\frac{\pi}{2}-\sin{x}\right)-\sin\cos{x}=$$
$$=2\sin\frac{\frac{\pi}{2}-\sin{x}-\cos{x}}{2}\cos\frac{\frac{\pi}{2}-\sin{x}+\cos{x}}{2}>0$$
because by C-S
$$\sin{x}\pm\cos{x}\leq\sqrt{(1^2+1^2)(\sin^2x+\cos^2x)}=\sqrt2<\frac{\pi}{2}$$


Time Series Data Unobserved Components Model

Question: I am using the Unobserved Components Model to decompose metal price data in Stata. i am using a model with three terms trend, cycle and irregular.
I specif the model below:
ucm copper, model(strend) cycle(1, frequency(1.5)) cycle(2, frequency(2.5))
my first cycle is of order 1 and the second is of 2 (as shown in the stata manual) what does the order of the cycle mean? Can i specify both cycles to be of order 1?
Answer: Unobserved components model, is very flexible modeling tool that can incorporate multiple seasonal and cyclical components. Although I have not used stata personally, the order in cycle statement simply means the number of cycles in your model. In your case you have 2 cycles one with a frequency of 1.5 and the other with a frequency of 2.5


How to install OpenCV on Amazon Linux?

Question: I'm trying to install OpenCV for use with Pastec on an Amazon Linux instance. This is my first time using an Amazon service, and I don't have much experience using linux...
How would I install OpenCV and it's dependencies on Amazon Linux?
I have tried adding the EPEL repository using this command:
$ sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

... which works but it still won't install OpenCV...
$ sudo yum --enablerepo=epel install opencv-core
Loaded plugins: priorities, update-motd, upgrade-helper
948 packages excluded due to repository priority protections
Nothing to do

Answer: It seems that default yum repo for Amazon AMI doesn't contain OpenCV packages.
You can compile it from sources by yourself with the following simple steps:

install necessary packages:

sudo yum install git cmake gcc-c++

clone OpenCV from repository:

git clone https://github.com/opencv/opencv.git

(optionally) choose required version, if you do not do it, the master branch will be built:

git checkout <required version>

compile and install - create folder where you want to build it, enter there and type:

cmake <path to sources>
make
sudo make install

It's basic steps - after this you will have OpenCV with some default modules. You can read cmake output and adjust your installation before actual build. Possibly you should install additional packages for your needs (like libpng, libjpg, python etc.).
Comment: @EliaWeiss that's exactly what I said: "create folder in which you want to build it, enter there and type". The following commands should be executed from that separate directory, and `` is a command-line parameter where your source directory is
Comment: Thanks, it works well. The only problem now is that it takes a very long time to build whenever an instance starts up (like 40 minutes)... Would it be safe to just copy the build folder after running `make` onto every instance, and then just run `sudo make install` with a startup script?
Comment: @jjv360: yes, it's safe if OS and instances are the same, and you have all necessary packages on the target system. It should install everything to the folder specified in cmake first run.
Comment: When I try to checkout 3.1.0; I get this error:
`HEAD is now at 92387b1... Fix java version++`
I switch between openjdk 1.7 and openjdk 1.8 . But it didn't help.
Comment: @bodoroman Why do you think that it is a error? Seems like normal update at specified head. Now you can try to build it.
Comment: FATAL: In-source builds are not allowed.
         You should create a separate directory for build files.
Comment: @EliaWeiss if you tried to run cmake and saw this error, you need to rm /path/to/repo/CMakeCache.txt before running again or you'll continue to see the error
Answer: cmake should be higher than 3.5 in latest linux versions for the purpose of installing opencv and other packages. To install in Fedora or similar flavour use
sudo yum install cmake3

How to install OpenCV on Amazon Linux?


Shadows in UINavigationController stack

Question: In a UINavigationController stack, how can I change the topmost viewController´s layer attributes, like .view.layer.shadowRadius?
In other words, I´d need to change the default shadowRadius which separates the visible viewControllers during swiping back to the RootViewController.
Thanks a lot.
Edit: The problem is not creating the attributes, but getting finding the right view in the stack / having accept it an alternative shadowRadius.
Answer: Best Way is add this extension in your class add extension at the end of your class and Add shadow as well corner radius to any view as well to navigation controller :)
extension UIView {

@IBInspectable
var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
    }
}

@IBInspectable
var borderWidth: CGFloat {
    get {
        return layer.borderWidth
    }
    set {
        layer.borderWidth = newValue
    }
}

@IBInspectable
var borderColor: UIColor? {
    get {
        if let color = layer.borderColor {
            return UIColor(cgColor: color)
        }
        return nil
    }
    set {
        if let color = newValue {
            layer.borderColor = color.cgColor
        } else {
            layer.borderColor = nil
        }
    }
}

@IBInspectable
var shadowRadius: CGFloat {
    get {
        return layer.shadowRadius
    }
    set {
        layer.shadowRadius = newValue
    }
}

@IBInspectable
var shadowOpacity: Float {
    get {
        return layer.shadowOpacity
    }
    set {
        layer.shadowOpacity = newValue
    }
}

@IBInspectable
var shadowOffset: CGSize {
    get {
        return layer.shadowOffset
    }
    set {
        layer.shadowOffset = newValue
    }
}

@IBInspectable
var shadowColor: UIColor? {
    get {
        if let color = layer.shadowColor {
            return UIColor(cgColor: color)
        }
        return nil
    }
    set {
        if let color = newValue {
            layer.shadowColor = color.cgColor
        } else {
            layer.shadowColor = nil
        }
    }
}
}

Comment: My problem is rather finding / calling the appropriate viewControllers view in the stack. Not how to create the attributes. Thanks!

Shadows in UINavigationController stack


What is "Assuming Sphericity" in Anova function?

Question: I am quite newbie of ANOVA, and just learnt how to run the function.
I am using the function 'Anova' from the package 'car' in R, and when I summary the analysis, I see the text:
<code>Univariate Type II Repeated-Measures ANOVA Assuming Sphericity
</code>
My professor told me that, "assuming sphericity" is not the thing she want, and she want some kind of "real" thing. Unfortunately, she does not know R well so she cannot tell me how to do that.
Could you explain me what is "assuming sphericity", and how could I satisfy the requirement of my prof?
Updated:
Thanks for Rolan and Peter, I chose to run "lme" (in package "nlme") and I have the output:
<code>    lme3 <- lme (Z_score ~ WTH1 + WTH2, random = ~1|BTW, data = spf)
    summary (lme3)

> Linear mixed-effects model fit by REML  Data: spf
>        AIC      BIC    logLik
>   327.9795 341.7903 -158.9897
>
> Random effects:  Formula: ~1 | BTW
>          (Intercept)  Residual StdDev: 2.310226e-05 0.8962092
>
> Fixed effects: Z_score ~ WTH1 + WTH2
>                  Value Std.Error  DF   t-value p-value
>(Intercept) -0.6584315 0.1417031 113 -4.646557   0e+00
>WTH11        0.6741030 0.1636247 113  4.119813   1e-04
>WTH21        0.6427601 0.1636247 113  3.928259   1e-04
>Correlation:
>       (Intr) WTH11
> WTH11 -0.577
> WTH21 -0.577  0.000
>
> Standardized Within-Group Residuals:
>        Min         Q1        Med         Q3        Max
> -2.1274596 -0.7449203 -0.1466509  0.6385587  3.2199382
>
> Number of Observations: 120 Number of Groups: 5
</code>
So, you can see, my dataset have 5 columns:
<code>> str (spf)
> 'data.frame': 120 obs. of  5 variables:
>  $ id     : Factor w/ 30 levels "1","2","3","4",..: 1 1 1 1 2 2 2 2 3 3 ...
    >  $ BTW    : Factor w/ 5 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
>  $ WTH1   : Factor w/ 2 levels "0","1": 1 1 2 2 1 1 2 2 1 1 ...
    >  $ WTH2   : Factor w/ 2 levels "0","1": 1 2 1 2 1 2 1 2 1 2 ...
>  $ Z_score: num  -1.06 -0.678 1.194 1.94 -1.06 ...
</code>
BTW (between) is actually a Group ID (we run an experiment 5 times, each time with a different group), and WTH1 and WTH2 (within) are within variables. Z_score is the measurement.
I want to know, is there any effect of BTW on WTH1 and WTH2 (I hope not), but I do not know how to interpret the data of lme?
(Using Anova function I mentioned above, the result is quite straightforward, with the notion '*' and '' etc to determine the significant level, but there is a problem related to 'Assuming Sphericity")
Comment: What does '*some kind of "real" thing*' mean?
Comment: You should probably switch to linear mixed effects models then. Look into package `nlme` and this book: Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer.
Comment: The way you structured your `lme()` call does not seem to include an interaction term between BTW and the WTHs, which is what you would need to see if there is "any effect of BTW on WTH1 and WTH2." I'm not sure how to specify such an interaction in `lme`. It can be done in `lmer`; see the [cheat sheet](http://stats.stackexchange.com/q/13166/28500) for how to specify models for that function. Note that this can take a good deal of care both in specifying the model and in interpreting the results.
Comment: It's not a function of the forum to read your professor's mind!
Comment: Of course, I understood that. Just if there is something opposite with "assuming sphericity" in Anova and it's okay.
Comment: Hi @Roland, is there a resource with R code?
Comment: Hi Roland, I found it. Thank you very much for your answer.
Comment: Hi @Roland, I updated my question. Thanks a lot for your comment. If possible, could you take a look to the question and help me one more time?
Answer: Sphericity is a condition of the data and an assumption of RM-ANOVA. All variances of differences between all possible pairs of groups must be equal.  This is rarely a reasonable assumption with repeated measures.
As @Roland said, one way around this is to use mixed effects (aka multilevel models). Pinheiro and Bates, which he recommends, is good, but may be rather heavy going.  There are lots of good books on these issues.  I like Hedeker and Gibbons.
Comment: Hi Peter, if possible, could you introduce me a resource with R code. It is easier for me.
Comment: I usually use SAS for this sort of model, myself.  But look at the nlme package.  Pinheiro and Bates does have R code, if you want a book. @FrankHarrell 's book Regression Modelling Strategies covers much more than this sort of model, but does have a section on repeated measures and is R based.
Comment: Hi Peter, thanks for your comment, I can run lme now, but the problem is I do not understand the result. I updated my question, so if possible, could you please tell me what does it mean?


How to pivot rows in a table with condition?

Question: I want to pivot data in my database with an SQL script. This is how it looks like in the table.
id  name        state   cpu_usage   memory_usage    datetime
1   machine-2   Running 50.6693     5060099372      2013-11-18 17:00:22.550
2   machine-3   Running 19.8329     14951967776     2013-11-18 17:00:22.550
3   machine-4   Running 24.2103     3309923047      2013-11-18 17:00:22.550
4   machine-2   Running 97.2774     2867303718      2013-11-18 17:01:22.550
5   machine-3   Running 66.2991     11048043786     2013-11-18 17:01:22.550
6   machine-5   Running 26.6446     13362336682     2013-11-18 17:01:22.550
7   machine-2   Running 39.5881     6969468931      2013-11-18 17:02:22.550
8   machine-3   Running 99.0000     9340168327      2013-11-18 17:02:22.550
9   machine-4   Running 85.0968     16154409604     2013-11-18 17:02:22.550

This is how I want the result to look like for CPU usage.
Date                        machine-2   machine-3   machine-4   machine-5
2013-11-18 17:00:22.550     50.6693     19.8329     24.2103     null
2013-11-18 17:01:22.550     97.2774     66.2991     null        26.6446
2013-11-18 17:02:22.550     39.5881     99.0000     85.0968     null

How to do this with SQL?
Answer: There are a few different ways that you can get the result.
You can apply an aggregate function with a CASE expression using conditional logic to create your new columns:
select datetime,
  max(case when name = 'machine-2' then cpu_usage end) machine2,
  max(case when name = 'machine-3' then cpu_usage end) machine3,
  max(case when name = 'machine-4' then cpu_usage end) machine4,
  max(case when name = 'machine-5' then cpu_usage end) machine5
from yourtable
group by datetime;

See SQL Fiddle with Demo
Or you can apply the PIVOT function which will convert your name values into columns:
select datetime,
  [machine-2], [machine-3],
  [machine-4], [machine-5]
from
(
  select datetime, name, cpu_usage
  from yourtable
) d
pivot
(
  max(cpu_usage)
  for name in ([machine-2], [machine-3], [machine-4], [machine-5])
) piv;

See SQL Fiddle with Demo.
The above two versions will work for you if you have a limited number of values for the name columns, but if not then you will need to look at using dynamic sql:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name)
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT datetime,' + @cols + '
            from
            (
              select datetime, name, cpu_usage
              from yourtable
            ) x
            pivot
            (
                max(cpu_usage)
                for name in (' + @cols + ')
            ) p '

execute sp_executesql @query;

See SQL Fiddle with Demo.  All versions give a result:
|                        DATETIME | MACHINE-2 | MACHINE-3 | MACHINE-4 | MACHINE-5 |
|---------------------------------|-----------|-----------|-----------|-----------|
| November, 18 2013 17:00:22+0000 |   50.6693 |   19.8329 |   24.2103 |    (null) |
| November, 18 2013 17:01:22+0000 |   97.2774 |   66.2991 |    (null) |   26.6446 |
| November, 18 2013 17:02:22+0000 |   39.5881 |        99 |   85.0968 |    (null) |

Comment: Thank you for your answer. It's what exactly what I want. I also found that SQL Fiddle is very helpful (I only knew jsfiddle one.)


Pacote para validações por serviço

Question: Estou a desenvolver um projeto de grandes dimensões com Laravel e preciso de validar os meus dados. Inicialmente tinha pensado usar o Ardent, mas este não é compatível/aconselhável para quem usa o padrão repositório.
Por isso vou ter que fazer as validações por serviços.
Aconselham algum pacote especifico?
Comment: Bem-vindo, Miguel. Você tem requisitos mais específicos? Perguntar o que os outros aconselham não funciona bem aqui, pois cada um dará sua opinião e vai ficar difícil eleger uma como correta. Sugiro que leia [Devemos aceitar questões de recomendação](http://meta.pt.stackoverflow.com/questions/57/devemos-aceitar-questoes-de-recomendacao) e [Good subjective, bad subjective](http://meta.pt.stackoverflow.com/questions/486/good-subjective-bad-subjective).
Comment: @bfavaretto o unico requisito é de permitir a validação como serviços e não através de modelos com o Ardent.
Answer: Implementando validação como serviço:
Não conheço um pacote, desconfio que ainda não existe.
Mas há um par de artigos que contêm exatamente o que você quer:
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
http://culttt.com/2014/01/13/advanced-validation-service-laravel-4/
Com a solução apresentada, você especifica as suas regras de validação assim:
<?php namespace App\Service\Validation\Laravel;

use App\Service\Validation\ValidableInterface;

class UserCreateValidator extends LaravelValidator implements ValidableInterface {

  /**
   * Validação para criar um novo User
   *
   * @var array
   */
  protected $rules = array(
    'username' => 'required|min:2',
    'email' => 'required|email',
    'password' => 'required'
  );

}

A classe UserCreateValidator herda a funcionalidade básica da classe AbstractValidator, a funcionalidade específica do Laravel para rodar testes de validação da classe LaravelValidator e por fim cada classe filha finaliza a implementação com as regras especificamente requeridas. A implementação de ValidableInterface assegura que a classe cumpra os requerimentos do contrato.

Pacote para validações por serviço


Add FullText Capability to existing table in MySql

Question:
Possible Duplicate:
MySQL/PHP Search Efficiency

How to Add FullText Capability to the existing table in MySQL.
I've seen adding it directly at the time of table creation as follow.
CREATE TABLE articles (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    title VARCHAR(200),
    body TEXT,
    FULLTEXT (title,body)
);

But how to add FullText Manually after the table is created?
Answer: According to the docs at http://dev.mysql.com/doc/refman/5.0/en/alter-table.html
ALTER TABLE TABLE_NAME ADD [FULLTEXT|SPATIAL] [INDEX|KEY] [index_name]
Comment: Thanks for your effort @SiGanteng
I got better answer from here.http://stackoverflow.com/a/2954062/1518640
Comment: Note you'll need to add the attributes you want full text on in first!
Comment: is it  correct? ALTER TABLE articles ADD [FULLTEXT] [INDEX] [Title]
Comment: @hungrycoder no problem, also, make sure that your table is using MyISAM as its engine.
Comment: yes it is using MyISAM only. But only problem is I need to check whether the FullText Catalog is supported by my hosting provider or not.


how to run postfix by hand

Question: I compiled postfix 2.9.5 with mysql backend.You know postfix daemons are ran with postfix, So i don't know main postfix daemon to run by hand. What's main daemon ?
Answer: I believe it's /usr/sbin/postfix

how to run postfix by hand


running command in loop by properties file Shell script

Question: I want to run git command to to create new branch,
The command is:
git checkout -b branch1.00 branch1.00

Now I want to run this command when instead of "branch1.00" I will have a parameter (lets call it $branch) , this parameter will take it's value from a .properties file (lets call that file  prop.properties) and run this command on all values in this file.
So if the prop.properties file will look like that:
branch=branch1.00
branch=branch2.00
branch=branch3.00
branch=branch4.00

The git command will run 4 times like that:
git checkout -b branch1.00 branch1.00
git checkout -b branch2.00 branch2.00
git checkout -b branch3.00 branch3.00
git checkout -b branch4.00 branch4.00

Any idea how to do that?
Answer: This while loop with do the job:
while IFS='=' read -r _ b; do
   git checkout -b "$b" "$b"
done < prop.properties

If there is no branch= prefix then use:
while read -r b; do
   git checkout -b "$b" "$b"
done < prop.properties

This will run these commands:
git checkout -b branch1.00 branch1.00
git checkout -b branch2.00 branch2.00
git checkout -b branch3.00 branch3.00
git checkout -b branch4.00 branch4.00

Comment: Great!!!
Works!! the only thing I had to change is removing the "branch=" in the beginning of the properties file


Get amount of submatrixes from $a \times b $matrix

Question: I was trying to do the following exercise
Given a grid of size $a \times b$, write a formula able t calculate the total number of rectangles contained in this rectangle. All integer sizes and positions are counted.
Examples:
$3 \times 2$ matrix $\Rightarrow 18$
$4 \times 4$ matrix $\Rightarrow 100$
Here is how the $3\times2$ grid works:
$1$ rectangle of size $3\times 2$:
[][][]
[][][]
$2$ rectangles of size $3\times 1$:
[][][]
$4$ rectangles of size $2\times 1$:
[][]
$2$ rectangles of size $2\times 2$
[][]
[][]
$3$ rectangles of size $1\times 2$:
[]
[]
$6$ rectangles of size $1\times 1$:
[]
As you can see $(1 + 2 + 4 + 2 + 3 + 6) = 18$, and is the solution for the $3\times 2$ grid.
...
Alledgedly, the answer is $\frac{((ab)+a)((ab)+b))}{4}$
I can't understand why, can anybody explain this?
Answer: Yes, although I find it easier to understand it as $\frac{a(a+1)b(b+1)}{4}$.
Every rectangle can be described by selecting two not necessarily distinct columns (the columns the corners are going to occupy) and two not necessarily distinct rows (the rows the corners are going to occupy).
There are $\binom{a}{2}=\frac{a(a-1)}{2}$ ways to select distinct columns and $a$ ways to select only one column. So $\frac{a(a+1)}{2}$ ways in total.
There are $\binom{b}{2}=\frac{b(b-1)}{2}$ ways to select distinct rows and $b$ ways ways to select only one row, so $\frac{b(b+1)}{2}$ in total.
So there are $\frac{a(a+1)}{2}\frac{b(b+1)}{2}=\frac{a(a+1)b(b+1)}{4}=\frac{(ab+a)(ab+b)}{4}$ ways to select the rows and columns of the corners of the rectangle, this uniquely determines each rectangle.


How to model this navigation scenario with efficient Route and ASP.NET Sitemap?

Question: i need to model the following scenario, but I can't get it working with the MvcSitemapProvider (i think my problem also maps directly to the default SiteMapProvider). I want to get the default breadcrumbs control to work properly with my dynamic data.
I have a list of products which are grouped by category which have a parent-category

ParentCategory

Category

Product

I want to be able to use the following url(s):

(1) /Products
(2) /Products/MainCategory
(3) /Products/MainCategory/Category
(4) /Products/MainCategory/Category/Product

Obviously my solution below is not optimal.
The Products node in the Sitemap doesn't have ChildNodes, so they won't show up in my Menu.
I've created an intermediary object which adds the maincategories and categories so they show up in my menu. But this won't fix the problem as other controls (breadcrumbs) just say that I am on /Products.
Should I change my routes or change my sitemap definition? Or maybe something else?

I currently have the following:

2 Routes
1 for /Products, /Products/MainCategory and /Products/MainCategory/Category -> mapping to ProductsController.Index()
1 for /Products/MainCategory/Category/Product -> mapping to ProductsController.Product()
1 entry in the Sitemap
with dynamicParameters defined (MainCategory;Category)

Global.asax Route definition:
    routes.MapRoute( _
        "Product", _
        "Products/{MainCategoryName}/{CategoryName}/{ProductName}", _
        New With {.controller = "Products", .action = "Product"} _
    )

    routes.MapRoute( _
        "Products", _
        "Products/{MainCategoryName}/{CategoryName}", _
        New With {.controller = "Products", .action = "Index", .GroupName = "", .CategoryName = ""} _
    )

I have the following entries in my sitemap:
<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
  <mvcSiteMapNode controller="Home" action="Index" title="Home" description="Homepage">
    <mvcSiteMapNode controller="Products" action="Index" title="Products" description="" isDynamic="true" dynamicParameters="MainCategoryName;CategoryName" />
  </mvcSiteMapNode>
</siteMap>

Answer: I'm currently using a custom SiteMapProvider. I'm still also maintaining custom routes they are in no way related.


Memory problems while selecting many rows

Question: I am retrieving rows from large table (1.8 GB, 20 milions of records) with DataReader.
The SQL Server (2008 R2) consumes a lot of memory and (sometimes) doesn't survive this query.
It is probably holding the whole result in memory and returning the rows from this buffer to client.
The select is quite simple - it just returns all rows from table with simple where condition, date stored in column is smaller than actual date. There are no blobs or strings in columns.
Am I right with my estimation about the cause of memory usage? And what can I do in this situation - I need all rows, the query doesn't have to be fast, but memory efficient.
Thanks
Updated info - select is in stored procedure. Code:
<code>CREATE PROCEDURE [get_current_records]
with recompile
AS
BEGIN

declare @currentDate datetime = getdate()
SELECT
   [id]
  , name
  , description
  , number
  ,[valid_from]
  ,[valid_to]
  from ui_parcela
  where valid_from < @currentDate and (valid_to is null or valid_to > @currentDate )
END
</code>
Comment: What kind of errors do you see?  I can't see why querying a 1gb table should be a problem.
Comment: Is `SQL Server` in the same machine as the client?
Comment: Are you reading all of these rows into memory?
Comment: No, client and server are different machines.
Rows are stored to stream using XmlWriter.
It was the SQL Server that had problems with memory.
Comment: Errors are: There is insufficient memory available in the buffer pool.
Answer: Its important to know what are you doing with those rows?
Are you storing them in the memory , or you can use each row and release them from the memory
So I am suggesting you try using async reader
Comment: But his SQL server is crashing out, not the client machine.
Comment: ohhh then maybe his setting are not correct. http://technet.microsoft.com/en-us/library/ms191144(v=sql.105).aspx
Answer: It sounds like you need to look at your SQL query if the server is running out of memory. Have you Indexed correctly?
Check the SQL execution plan to see what is expensive.
Comment: I will do that tomorrow at work and post the exact select and info about execution plan


Drupal Commerce: How to perform a complex calculation of order's final cost (VATs & discounts)?

Question: Here's is what I want to accomplish:

There are 2 taxes in my country: 6.5% & 23%. Every product has to be matched with 1 of these 2 VATs (I'm currently using a taxonomy vocabulary holding these 2 VAT values instead of using commerce tax module)
A discount should always be available, based on total order's amount, excluding tax e.g. an order's total (with no tax included in base prices) of €0,01-€50,00 awards the customer with a discount to the order's total (including tax) of -5%, from €50,01 to €80,00 gives a discount of -8% etc etc

What I want to accomplish:
- Customer adds products to cart (product prices are displayed excluding tax, ie w/o components) and heads to checkout. According to order's total (addition of products' base prices w/o tax), the appropriate discount will be applied.
- Final Price = (Products' base prices + their appropriate taxes)*Pre-calculated Discount + Shipping Cost
Example:
Shopping cart includes:
- Product 1: €20 base price (6.5% VAT)
- Product 2: €25 base price (23% VAT)
Checkout Process:

Discount pre-calculation: Total base price is €20 + €25 = €45. As a result, the customer should be awarded with a -5% discount (see available discount rates above).
Order's total including products' VATs = (€20 + €20*0.065) + (€25 + €25*0.23) = €21.30 + €30.75 = €52.05
The pre-calculated -5% discount from step 1 is applied: €52.05 - €52.05*0.05 = €49.45 and that's what the customer has to pay for the products in his/her cart.
Order's weight is calculated and a shipping flat rate is applied (I have this functionality already working). As a result, the shipping cost is added to €49.45 and we finally get the sum that the customer will have to pay using one of available payment methods.*

I would appreciate your suggestions on how to make this happen.
Tricky parts:

different products can have different VAT (23% or 6.5%).
The discount has to be calculated by adding all products' base prices (NOT including tax) and THEN applied to line item (including tax) prices.
It would also be nice if VATs & discount were displayed to customer in order's review.
Answer: You can achieve what you're looking for using some module and disabling others. This explanation is based on Drupal Commerce (7.x).

Uninstall standard Commerce Tax module since it leads to weird results with different VAT if you aren't a Rules master as exposed in this issue on drupal.org.
Install Commerce European Union VAT (commerce_eu_vat) choosing the right country: the module has a good written API and you can adapt it for extra-EU countries easily. Now you can assign product by product the right VAT and even assign a default VAT by product type via "manage fields" on product variations administration.

Install Discount (commerce_discount) module. You can set discount per product and per order (your case). Create a new discount, e.g. "My funny discount".
Now you can create your per-order discount. Every time you create a new discount it appears on both Discount page and on Pricing rules. Since VAT is sometimes applied before Discount (in my case it was) then you have to change the Rule weight for your new discount. Go to the Pricing rules administration page, search for "My funny discount" > edit > Settings > Weight and give it a negative weight to apply the discount before the VAT. Note: when you override the discount you cannot save it anymore since you've changed the parent Rule. Just revert the rule to make it editable again and then reapply the weight trick.

Now you have to hide unwanted components from your price on display: to do this install Commerce price by components (commerce_price_components). On your product type > Manage display you can change your price field widget from "Formatted amount" to "Price by components" and check only Discount and Base price, excluding VAT and other components.

Here the result on checkout:

Hope this helps.
Comment: This does NOT work out for prices that include VAT, i.e. reverse VAT calculation. I described the problem in [Reverse calculation messes up price components on discount](https://www.drupal.org/node/2276233) and the solution in [[META] Use order discount with VAT [#2276227] | Drupal.org](https://www.drupal.org/node/2276227).

Any review there is greatly appreciated.


Does negative int number from exception indicates more than just a number?

Question: Simple code indeed :
int number = int.MaxValue;
    number = number+1;
Console.WriteLine(number);

Questions :
1) there's should be overflowException. there isn't. why is that?
2) Does the number -2147483648 indicates something about :

) how many bytes is beyond limit size  ?
) if i see -2147483648  , How can I know ( if there wasnt an exception) - if this number came from exception ? - must I wrap it with Try Catch ?

p.s.  when i wrote :
int number = int.MinValue;
    number = number-1;
Console.WriteLine(--number);

I got  : 2147483647 (still no exception).
Answer:
There's should be overflowException. there isn't. why is that?

By default, C# doesn't do overflow checking. You can enable it for a whole assembly (in the "Advanced" bit of the build tab in VS, or /checked+ from the command line) or for a block/expression using the checked keyword
For the second part of your question, -2147483648 is just int.MinValue - signed integers do that, rolling from a very large positive number to a very large negative number.
For example, if you use sbyte (the signed byte type):
sbyte number = 127; // sbyte.MaxValue
number++;
Console.WriteLine(number); // Prints -128

There's nothing funny going on here - it's just normal 2s complement overflow.
Or using byte (unsigned)
byte number = 255; // byte.MaxValue
number++;
Console.WriteLine(number); // Prints 0

Comment: @RoyiNamir: Gah, sorry - byte is unsigned in C#. You'll need sbyte. Will edit.
Comment: @RoyiNamir: Was editing for that - no, it's not indicating an exception at all. It's just the result of the overflow.
Answer: Wrap it in a checked block to get an exception. Arithmetic overflow is unchecked by default.
Answer:
Does the number -2147483648 indicates something about:

It's the min value.  When you overflow you'll wrap, so maxValue+1 == MinValue, MaxValue + 2 == MinValue + 1, etc.
The same logic applies in the other direction; MinValue - 1 == MaxValue.
Answer: int has a minimal value and a maximal value. If you are overflowing the max value, it simply cycles down to the minimal value.
Example:
int cant have numbers from -10 to 10.
int i = 8; // 8
i++; // 9
i++; // 10
i++; // -10
i++; // -9
i -= 2; // 10
i += 10; // -1
To get overflow exception, use a check block, since it is not checked by default.
checekd
{
    int i = int.MaxValue;
    i++; // throws
}


How to use Oracle sql to put the first date on top and the rest of dates in reverse order?

Question: When I use order by easily to get a query result like this,
name | date
Kev 2018/3/29
Lee 2018/3/28
Mel 2018/3/27
Fiona 2018/3/26
Jason 2018/3/25
but now how can I achieve the following sorting results?
name | date
Jason 2018/3/25
Kev 2018/3/29
Lee 2018/3/28
Mel 2018/3/27
Fiona 2018/3/26
Comment: Your example doesn't match the title. It doesn't put the last row on top, it puts the first one. And the other rows are not in order, they are in descending order. Please edit either the title or the example to make them consistent with each other.
Comment: OK, you edited the post; but the result you "want to achieve" still has the first date on top and the rest of the dates are in reverse order. So the title is wrong? Is it so hard to fix it?
Comment: I am very embarrassed. As a Chinese code farmer, English is really the biggest short board and I always mean nothing.
Answer: min(dt) is the earliest date. min(dt) over () is an analytic function - it computes the min date and it adds it as a "made-up" column to every row in the query. Then, decode will produce null if the first two arguments are equal and dt otherwise. I order by this result, descending, with nulls first - so the earliest date will appear on top, and the other rows are ordered descending by dt.
create table t ( name varchar2(20), dt date );

insert into t
  select 'Jason', to_date('2018/3/25', 'yyyy/mm/dd') from dual union all
  select 'Kev'  , to_date('2018/3/29', 'yyyy/mm/dd') from dual union all
  select 'Lee'  , to_date('2018/3/28', 'yyyy/mm/dd') from dual union all
  select 'Mel'  , to_date('2018/3/27', 'yyyy/mm/dd') from dual union all
  select 'Fiona', to_date('2018/3/26', 'yyyy/mm/dd') from dual
;

commit;

alter session set nls_date_format = 'yyyy/mm/dd';

select   name, dt
from     t
order by decode(dt, min(dt) over (), null, dt) desc nulls first
;

NAME                 DT
-------------------- ----------
Jason                2018/03/25
Kev                  2018/03/29
Lee                  2018/03/28
Mel                  2018/03/27
Fiona                2018/03/26


Does $x^n$ have a limit, where $-1<x<0$ and $n$ approaches infinity?

Question: As the function grow it continues to oscillate at a smaller rate around $0$. Does that justify zero being considered a limit?
Comment: Yes, all $x$ satisfying $-1<x<1$ will follow $x^n \to 0$
Comment: For this kind of problems consider getting back at definition and to work it out.
Comment: To prove a function/sequence tends to $0$, you just have to prove its absolute value tends to $0$. So you can suppose $0<x<1$.
Comment: what about the function not being defined for non-integer values of n?
Answer: You have the correct intuition. To make this rigorous, use the Squeeze Theorem:
Note that $-1 < -\left(|x|^{n}\right) \leq x^n \leq  |x|^{n} < 1\;\forall n \in \mathbb{N}$
From this we see:
$$\lim_{n\to \infty} -\left(|x|^{n}\right) = \lim_{n\to\infty} |x|^{n} = 0 $$
Hence, $x^n \to 0$ in this case.
Answer: $x = \frac{1}{p}$ where $p\in\mathbb{R}^-, p <-1$ thus:
$\lim_{n\to\infty}x^n = \frac{1}{p^n} = 0$
because $p^n$ approaches $+\infty$ or $-\infty$. Either way the limit becomes 0
Comment: The limit varies between $0^+$ or $0^-$. Either way the limit is 0 so it doesn't matter.


Reverse elements of a string array

Question: string[] myString = {"a","b","c","d"}

//Reverse string algorithm here

myString = {"d","c","b","a"}

I have been asked to do so in an interview without the help of any temporary variable or .NET class, string methods, etc to reverse the elements of the same string array. I was told to use basic programming constructs like loops. Since, I am up for another interview today, I am in a hurry to know whether this is actually possible because I could not find a solution to this.
Comment: We're not here to do your job interview for you. At least show some things you've tried.
Comment: @S_F In that case everyone might assume it's homework and it would get downvoted a whole lot more. StackOverflow guidelines dictates that you should show a sufficient attempt at solving the problem oneself before asking here, the lack of this is likely the only reason it was downvoted.
Comment: You were asked to store the values in reverse or update the array?
Comment: I'm pretty sure there would be no downvotes if OP never metioned the job interview...
Comment: @MagnusGrindalBakken We will not be solving this for his interview. It will be for our knowledge or if we have then we can share with him
Comment: @NisargShah Note the second part of my comment. There's nothing wrong with asking for help about school problems, job interviews, or work projects, but you have to show that you've made an attempt.
Comment: For ints (and similar types) you can use the xor trick, but for other types you'll need a temporary variable... Or use the stack as a temporary variable. You could cheat by using a parameter of a function as as temporary variable, but a parameter is still a variable.
Comment: Can you resize array size in basic programming?
Comment: If by any case you can resize array then first double the size of array. Later add values in reverse order and overwrite the first half of array with reversed values. Now resize the array with half size. Thats all...
Comment: @MagnusGrindalBakken I did [this](http://rextester.com/MEX21315) Needless to say it did not work so, I did not post it here.Technically, you would just be answering my previous encounter of the problem. There is no guarantee it will ever be asked later.
Answer: Here you go, no support variables, no .net functions :) But it makes the assumptions that all the strings in the array have length 1 ( as they do in the code you posted).
string[] myString = {"a","b","c","d", "e"};
for(int i = 0; i < myString.Length/2; i++)
{
   myString[i] += myString[myString.Length -1 -i];
   myString[myString.Length -1 -i] = ""+myString[i][0];
   myString[i] = "" + myString[i][1];
}

Comment: That seems like a ridiculous assumption. If they're all length 1, the logical thing to do would be to have a `char[]` instead.
Comment: @Dukeling If we were in the logic domain, you wouldn't be asked not to use .net funcions or accessory variables. I tried to solve the ask just as he presented it.
Comment: Thanks @Save I was asked and therefore, asked for elements of length 1 in a string array. So it works and answers my question.
Comment: The example is just that, an example. The description doesn't mention that we're limited to length 1 strings and it seems like a very strange constraint to put on strings, so my logical assumption is that the example only uses length 1 strings because that's less typing than longer strings. Yes, I'd be a lot happier with a wild-card-based approach.
Answer: Since you cannot use a temporary variable, the best I can think of is appending the strings first and then removing the appended part again:
// append last strings to first strings
for(int i = 0; i < myString.Length / 2; i++)
{
    myString[i] = myString[i] + myString[myString.Length - i - 1];
}

// copy first half to last half
for(int i = myString.Length / 2 + 1; i < myString.Length; i++)
{
    myString[i] = myString[myString.Length - i - 1]
                      .SubString(0,
                              myString[myString.Length - i - 1].Length
                               - myString[i].Length);
}

// remove useless part from first half
for(int i = 0; i < myString.Length / 2; i++)
{
    myString[i] = myString[i].SubString(
                                  myString[myString.Length - i - 1].Length
                                   - myString[i].Length);
}

Stupid approach? Yes. But no additional variables are involved.
Comment: As stated: without the help of any temporary variable or .NET class, string methods.. -> SubString usage ;-(
Comment: @Heslacher that's no .NET, that's the `SubString` that I implicitly implemented myself but just did not show ;)
Comment: @Heuster I don't think `SubString` is implementable without temporary variables :-)
Comment: @xanatos I'm afraid so too. But neither is string concatenation since strings are immutable. The question would make more sense to me for an array of integers (so the XOR trick could be used).
Comment: Is there a specific reason you didn't just put all 3 statements in a single loop?
Comment: @Dukeling stupidity :) I wondered the same after typing, but then I thought: maybe it's more clear this way (probably not)
Answer: string[] myString = {"a","b","c","d"}

for(int = (myString.Length - 1); int >= 0; i--) {
    string rev =  myString[i];
    Console.Write(rev);
}

Comment: While your post might answer the question, please also provide a short explanation what your code actually does and how it solves the initial problem. Don't just drop a couple of poorly formatted lines of code.
Comment: Please provide answers that do not require clarification from the asker.
Comment: I agree with you here. I don't know why everyones makin it so difficult
Answer: The right answer in your interview is "Why would you NOT use the class libraries?"  But then say, "Well if I needed to write a customized method because the libraries don't support the need...".  Then I would show both methods and argue when to use each method.  If they had a problem with this explanation then I wouldn't want to work there anyway.
With Libraries:
string[] myString = {"a","b","c","d"};
List<string> list = myString.ToList();
list.Reverse();
myString = list.ToArray();

Without:
string[] myString = {"a","b","c","d"};
string[] newString = new string[myString.Length];
for (int i = 0, j = myString.Length - 1; i < myString.Length && j >= 0; i++, j--)
{
    newString[j] = myString[i];
}
myString = newString;

Comment: The reason to say "without using libraries" is because *someone had to write that library*. If you are interviewing for a job that involves writing libraries, assuming that the library is already written is a non-starter.
Comment: There's a reason for that. The question states that you can't use a temporary variable, which I'd argue yours does.
Comment: @EricLippert correct, no contest.  But, the specific assignment involved not using libraries available that are highly optimized.  Unless you are removing dependencies, using the library is the correct method, otherwise why ever use a library, right?
Answer: Sorry I posted a wrong answer... here's the verified one:
     int k = len - 1;
    for(int i = 0; i<len/2; i++)
    {
        myString[i] = myString[i]+"."+myString[k--];
    }
    for(int i = len/2; i<len; i++)
    {
        myString[i] = myString[k].substring(0, 1);
        myString[k] = myString[k--].substring(2,3);
    }

However, just consider this a pseudo-code... I did not check for .NET syntax.
Answer: Have you tried this
        string[] myString = { "a", "b", "c", "d","e","f" };

        int _firstcounter = 0;
        int _lastcounter = myString.Length-1;

        while (_firstcounter<=_lastcounter)
        {
            myString[_firstcounter] += myString[_lastcounter];
            myString[_lastcounter] = "" + myString[_firstcounter][0];
            myString[_firstcounter] = "" + myString[_firstcounter][1];

            _firstcounter++;
            _lastcounter--;
        }

Answer: This is not a complete answer, perhaps an idea..
It is possible to swap two numbers by mathematics
swap(a,b)
   a = a + b
   b = a - b
   a = a - b

Initially I was going to suggest this can be done with character ascii values.. Then I noticed the strings.
Is it acceptable then to
swap(str1, str2)
    str1 = str1+str2
    str2 = str1[0]
    str1 = str1[1]

I hope you get the idea
Answer: If the maximum string length is of array is less than 10, then is might be helpful....
string[] myString = { "aaaa", "bbb", "ccccccc", "dddddd", "e", "fffffffff" };
for (int i = 0; i < myString.Length; i++)
{
    myString[i] = myString[i].Length.ToString() + myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
    myString[i] = myString[i] + myString[myString.Length-1-i];
    myString[myString.Length - 1 - i] = myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
     myString[i] = myString[i].Substring(int.Parse(myString[i][0].ToString())+2,int.Parse(myString[i][int.Parse(myString[i][0].ToString())+1].ToString()));
}
for (int i = myString.Length / 2; i < myString.Length; i++)
{
     myString[i] = myString[i].Substring(1, int.Parse(myString[i][0].ToString()));
}

Answer: Try this.
public static class ExtensionMethods
{
    public static IEnumerable<T>  ReverseArray<T>(this T[] source)
    {
        for (int i = source.Length - 1; i >= 0; i--)
        {
            yield return source[i];
        }
    }

    public static T[] EnumerableToArray<T>(this IEnumerable<T> source)
    {
        var array = new T[source.Count()];

        int k = 0;
        foreach (var n in source)
        {
            array[k++] = n;
        }

        return array;
    }
}

Example usage
    public static void Main(string[] args)
    {
        string[] myString = {"a", "b", "c", "d"};

        myString = myString.ReverseArray().EnumerableToArray();
    }

Answer: static void ReverseMyString(string[] myString)
        {
        int start=0, end= myString.Length-1;
        string temp = "";

        while (start < end)
        {
            temp = myString[start];
            myString[start] = myString[end];
            myString[end] = temp;
            start++;
            end--;
        }
    }

Answer: Yes you can do it-
string[] myString = { "a", "b", "c", "d" };
myString  = (from a in myString orderby a descending select a).ToArray();

Comment: this is linq and also .net way of doing it
Answer: You need at least one variable to swap values.
In pseudo code:
for(i : 0..n/2) {
    // swap s[i] and s[n-i]
    String tmp = s[i];
    s[i] = s[n-i];
    s[n-i] = tmp;
}

Comment: You use tmp variable in your solution. You just hide it making the code ugly and less efficient...
Answer: We Can use  Array.Reverse(UrArray);
Comment: cannot convert from 'System.Collections.Generic.List' to 'System.Array'
Answer: Check out Array.Reverse method on MSDN.
Comment: He wants to do it without using any existing methods
Comment: OUt of question. It is from .net
Comment: ah, without .NET classes. Ah well, I'll leave the answer for future reference.
Comment: It will not work and throw: cannot convert from 'System.Collections.Generic.List' to 'System.Array'

Reverse elements of a string array


Real normal matrix which is diagonalizable over $\mathbb{R}$ but not unitary diagonalizable over $\mathbb{R}$.

Question: Let $A$ be a real $n\times n$ matrix. Can $A$ be normal, diagonalizable over $\mathbb{R}$ but not unitary diagonalizable over $\mathbb{R}$ ? By "unitary diagonalizable over $\mathbb{R}$" I mean that there exist a real unitary matrix $P$ such that $P^tAP$ is diagonal.
My attempt: I need to find a non-symmetric real matrix which is normal ?
Comment: https://en.wikipedia.org/wiki/Normal_matrix#Equivalent_definitions
Comment: Thanks, but what I suppose to take from that page?
Comment: It says: "the following are equivalent: 1. A is normal. 2. A is diagonalizable by a unitary matrix.". But I guess this does not readily explain the case over $\mathbb{R}$. I believe it does after some thinking though...
Comment: So you think that such a matrix does not exists?
Comment: indeed, I believe so. See also [this article](https://en.wikipedia.org/wiki/Orthogonal_diagonalization)
Answer: No. If $A$ is normal, it is unitarily diagonalisable over $\mathbb C$. Let $A=UDU^\ast$ be such a diagonalisation. Since $A$ is supposed to be diagonalisable over $\mathbb R$, $D$ is a real diagonal matrix. Therefore $A$ is Hermitian. Yet, $A$ is real. Hence it is real symmetric and unitarily/orthogonally diagonalisable over $\mathbb R$.


Which rule should one use on these two inverse Laplace transforms?

Question: I have an ode $y''-6y'+9y=t^2e^{3t}$, which I solved using the Laplace transform. However, when I come to the end result, which I need to do an inverse transform on, I get something which does not appear to be readily compatible with inverse laplace transform tables.
With I.C. $y(0)=2$, $y'(0)=6$:
$\mathscr{L}^{-1}\{y''\}=s^2Y-y'(0)-y(0)=s^2Y-8$
$\mathscr{L}^{-1}\{y'\}=sY-y(0)=sY-2$
$\mathscr{L}^{-1}\{y\}=Y$
This gives:
$s^2Y-6sY+9Y=t^2e^{3t}-4$
Then I get:
\begin{equation}
Y=\frac{t^2e^{3t}}{s^2-6s+9}-4\frac{1}{s^2-6s+9}
\end{equation}
which gives the following inverse:
\begin{equation}
y(t)=\mathscr{L}^{-1}\{\frac{t^2e^{3t}}{(s-3)^2}\}-4\mathscr{L}^{-1}\{\frac{1}{(s-3)^2}\}
\end{equation}
Using wolfram, this gives $y(t)=e^{6t}t^3-4te^{3t}$, but there are some familiarities here that suggest that a specific rule should be applied? If there is, which rule would that be?
Thanks
Comment: $y(0)=2, y'(0)=6$
Comment: Yes, I did that already. I add it to the question.
Comment: You only Laplace transformed ONE SIDE of the equation. Do both sides. $Y$ should not have $t$ in it at all.
Answer: We have
$$y''-6y'+9y=t^2e^{3t}, y(0) = 2, y'(0) = 6$$
Taking the Laplace Transform
$$(s^2 Y(s) -s y(0) - y'(0)) - 6(s Y(s) -y(0)) + 9 Y(s) = \dfrac{2}{(s-3)^3}$$
Adding the initial conditions
$$(s^2 Y(s) -2s -6) - 6(s Y(s) -2) + 9 Y(s) = \dfrac{2}{(s-3)^3}$$
Grouping terms
$$(s^2 -6s + 9)Y(s) - 2s + 6 = \dfrac{2}{(s-3)^3}$$
Simplifying
$$(s-3)^2 Y(s) = \dfrac{2}{(s-3)^3} + 2 s - 6$$
Solving for $Y(s)$
$$Y(s) = \dfrac{2}{(s-3)^5} + \dfrac{2s}{(s-3)^2} - \dfrac{6}{(s-3)^2}$$
Finding the inverse Laplace transform
$$y(t) = \dfrac{1}{12} e^{3 t} t^4+2 e^{3 t}$$
Comment: I used item 23, for the first and second from https://tutorial.math.lamar.edu/classes/de/laplace_table.aspx. For the middle term, I wrote the partial fraction decomposition $\dfrac{6}{(s-3)^2}+\dfrac{2}{s-3}$ and then used item 23 and item 2. Clear?
Comment: Thanks Moo, I see the error! I forgot that s in front of the transform of the first derivative!
Comment: Thanks, that is noted!
Comment: PS: So which rule did you use to get those transforms?
Comment: Got it! Thanks a lot!


Probability that a green counter was added to a bag, given that the counter chosen was green

Question: There are three colors of counter, red, green and blue.
There are 5 red, 3 green and 2 blue counters already in the bag.
Another counter is added to the bag (completely randomly).
A counter is chosen from the bag.
Given that the counter chosen is green, what's the probability that the counter added to the bag was green?

I have no idea how to approach this. I know very basic probability and combinatorics.
Answer: Let $A$ be the colour of the added counter, and $B$ be the colour of the removed counter, which can be in $\{g,r,b\}$.
You know $\mathsf P(A{=}g) = \mathsf P(A{=}r)= \mathsf P(A{=}b)$, and from the initial number of counters in the bag you can work out $\mathsf P(B{=}g\mid A{=}g), \mathsf P(B{=}g\mid A{=}r), \mathsf P(B{=}g\mid A{=}b)$ , the probabilities that the removed counter is green when given the colour of the added counter.
Then use Bayes' Rule and the Law of Total Probability to obtain what you are looking for: $\mathsf P(A{=}g\mid B{=}g)$, the probability that the added counter was green given that the removed counter was green.


How can i exclude ignore_throttled' param in HighLevelClient

Question: I currently use ElasticSearch in Spring Boot. The ES version is 6.2.2 and an error occurs because an option such as ignore_throttle does not exist. When I check the library version, it is judged that the high level client 7.x version is the problem, but if I change the version to 6.2.2, an unknown error occurs and I just try to use it. Could you possibly delete the parameter?
implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch:2.1.10.RELEASE'
request
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(sourceBuilder);

Answer: Is the version of spring boot you are using > 2.1.5
Comment: If yes, consider using the Java Low Level REST Client

Or downgrade spring boot to 2.1.5


How Configure pgAgent in Ubuntu22.04?

Question: I have installed postgresql, pgAdmin, and pgAgent. However, I can't get pgAgent to work with pgAdmin. It's been 3 days already, and I have no clue what I need to do.
What commands did I use for the installation?
<code>sudo apt install postgresql postgresql-contrib
sudo apt install pgadmin4
sudo apt-get -y install pgagent
</code>
And you can see the extension is installed but not the options to create the job with pgAgent
[1]
I tried to follow the instructions on the official website, but their command is not working.
[2]
And this is the result
[3]
host=localhost...host=127.0.0.1 ....the same result....
Thanks for you attention
[1]: https://i.stack.imgur.com/cpq4A.png
[2]: https://i.stack.imgur.com/EfpjB.png
[3]: https://i.stack.imgur.com/1eHwp.png
Comment: "but their command is not working"  Share Why you think it is "not working", and which documentation you actually used.
Comment: [How to ask a good question](https://stackoverflow.com/help/how-to-ask) does not say you should use _**answer**_ to clarify your question. Someone invented [edit] for that purpose...
Answer: Apologies for the previous post... I didn't realize that Stack Overflow messed up the formatting
Sources used for the installation of pgAdmin.
https://www.pgadmin.org/docs/pgadmin4/development/pgagent_install.html
https://www.youtube.com/watch?v=ne8Jg_lQldQ
What I have understood is that PostgreSQL is a service for managing databases. PgAdmin is a program that allows you to manage the database more easily.
And pgAgent is a plugin that you install to create routines easily. Well, pgAgent runs in the background as a system service.
What I'm looking for is to have that menu that facilitates creating routine tasks.

I believe this is what is failing.
I think after install pgagent with "sudo apt install pgagent" and install de plugin in the database with "CREATE EXTENSION IF NOT EXISTS plpgsql";
You need to create that service or somehow ensure that pgAgent is running as a system service. If that's the case, I have no idea how to do that. I understand that after installing pgAgent with 'sudo apt install pgagent,' the service is automatically created, but you need to specify which database it should connect to.
For that, I believe the command '/path/to/pgagent hostaddr=127.0.0.1 dbname=postgres user=postgres' is used, as mentioned on the official website, so that pgAdmin can use it. However, I'm encountering this error.

I want to understand that if you manage to establish that connection, pgAdmin will have that menu where you can easily create routines.

How Configure pgAgent in Ubuntu22.04?


disable chrome suggestions while entering a form field vale

Question: When i enter some field value in a form in my application. chrome is suggesting some values previously entered. I wanted to disable it. How could i do that. Any help is appreciated?
Comment: Possible duplicate of [How do you disable browser Autocomplete on web form field / input tag?](https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tag)
Answer: It should have same id for autocomplete value, just put
autocomplete="foo" or use a different id so that it doesn't match and it shouldn't be filled


With a WSOD upon deployment of a site, should I first clear the cache, check watchdog logs, or check the Apache logs?

Question: With a WSOD upon deployment of a Drupal 8 site, should I first clear the cache, check watchdog logs, check the Apache logs, or something else?
I read the Drupal WSOD triage information here But it doesn't seem to share which solution should first be done in this situation.
This seems to indicate that it could be with the DB, so would I need to check that first?
I just noticed Fixing white screens step by step. It seems to suggest that I should look at the system (Apache) logs first. Am I interpreting this correctly?
Comment: Yes, first step is to make sure everything is OK with Apache before Drupal can even start and produce its own errors in the watchdog table
Answer: Yes. Because of the variety of possible Drupal stack configurations, it's impossible to say you'll always find your error in an Apache log. However, a WSOD generally means PHP has hit a fatal error and it's configured not to dump sensitive debug info to screen.
If that's the case, you might not even have a working Drupal app to make use of its tools like cache clearing, watchdog, etc., so it's best to find where those PHP errors are dumped so you can get Drupal into a bootstrapped state.
Of course, you should know your stack better than anyone else so a cache clear could eliminate the issue if you know the source of the problem. But if you're unsure, Apache logs are a good first start.
Answer: Assuming that your site and Apache has worked just fine before the deployment, and since this happens during a code update I'd suggest to always clear the caches first.
<code>$ drush cr
</code>
And since data/entities might have changed during the update this then should be followed by database updates.
<code>$ drush -y updb
</code>
Then re-check.
Your environment might simply be configured to suppress on-screen error messages. And you very likely get a hint on what's wrong on the command line when performing Drush commands.
I'd also always have a look at Watchdog then before starting to dig through any other logs.
<code>$ drush ws
</code>


Representing $\sum\limits_{n=1}^\infty a_{n-1}a_nz^n$ in terms of $\sum\limits_{n=0}^\infty a_nz^n$

Question: Let $f(z)=\sum\limits_{n=0}^\infty a_nz^n$ be an analytic function in some open set $D$ with $a_n>0$ for all $n\geq 0$. Then there are various series that can be represented in terms of $f$. For example, we have that $\sum\limits_{n=1}^\infty na_nz^n=zf'(z).$  Is there a way to represent the series $\sum\limits_{n=1}^\infty a_{n-1}a_nz^n$ in terms of $f$?
Answer: Here's what I got: by Cauchy's generalized integral formula,
$$\begin{split}
g(z) &= \sum_{n=1}^\infty a_{n-1}a_n z^n = \sum_{n=1}^\infty \frac{f^{(n-1)}(0)}{(n-1)!} a_n z^n =  \sum_{n=1}^\infty \frac{a_nz^n}{2\pi i} \int_{\circlearrowleft} \frac{f(\zeta)}{\zeta^n}d\zeta \\
&=\frac{1}{2\pi i} \int_\circlearrowleft \left[f\left( \frac z \zeta \right) - f(0) \right] f(\zeta) d\zeta,
\end{split}$$
where $\circlearrowleft$ is a counterclockwise contour circling the origin. The formula makes sense: since $f$ is defined as a Maclaurin series and $D$ is an open set, $D \subseteq B_r(0)$, where $0 < r \leq \infty$ is the radius of convergence, and if $D \neq B_r(0)$, $f$ can be extended to the open ball $B_r(0)$. It suffices to take $\circlearrowleft$ to be any circumference of radius $< 1$. Is this what you wanted?
Comment: +1 Of course the expression in my answer is equivalent to this via a change of variables, and such a complex method is indeed the most natural derivation.
Comment: @Sharkos I also upvoted your answer because I didn't know about Hadamard products! Very interesting!
Comment: Glad it's interesting! Gave a more simple-minded justification of the formula in my answer.
Answer: This is essentially a Hadamard product of $f$ with $zf$: https://en.wikipedia.org/wiki/Generating_function_transformation#Hadamard_products_and_diagonal_generating_functions
It's not a very natural operation, and requires an integral to be expressed in closed form. The expression in the Wikipedia article gives (a bit sloppy with square roots I guess, but never mind!):
$$
(f \odot zf)(z) = \frac{1}{2\pi} \int_0^{2\pi} f(\sqrt{z}e^{it}) f(\sqrt{z}e^{-it}) \sqrt{z}e^{-it} {\rm d}t
$$
or slightly more neatly,
$$
(f \odot zf)(z^2) = \frac{z}{2\pi} \int_0^{2\pi} f(z e^{it}) f( ze^{-it}) e^{-it} {\rm d}t
$$

Example: $f(z) = \exp(z)$ gives
$$\begin{align}
(f \odot zf)(z)
&= \frac{z^{1/2}}{2\pi} \int_0^{2\pi} \exp(\sqrt{z}e^{it}) \exp(\sqrt{z}e^{-it}) e^{-it} {\rm d}t \\
&= \frac{z^{1/2}}{2\pi} \int_0^{2\pi} \exp(2\sqrt{z} \cos t - it){\rm d}t \\
&= z^{1/2} I_1(2\sqrt{z})
\end{align}$$
in terms of a particular Bessel function, which indeed has the series
$$z^{1/2} I_1(2\sqrt{z}) = \sum_{n=1}^\infty \frac{z^n}{n!(n-1)!}$$
This example shows that you don't expect a simple expression (e.g. not involving integrals) for the result.

Edit: Note that the intuition behind the formula
$$(f \odot g)(z) = \frac{1}{2\pi} \int_0^{2\pi} f(\sqrt{z}e^{it}) g(\sqrt{z}e^{-it})  {\rm d}t$$
is that you want a given power of $z^{n}$ in the answer to arise from an equal balance of terms $f_n z^{n/2} \times g_n z^{n/2}$ from $f,g$. Hence you just multiply $f$ and $g$ together, but give the term  $\propto f_n$ a phase factor $e^{i n t}$ and the term $\propto g_n$ a phase factor $e^{-i n t}$ and then look for things which have no overall phase. This is what integrating $\frac{1}{2\pi} \int {\rm d}t$ does.


Web-App : Keeping trace of the version of the application in database?

Question: We are building a webapp which is shipped to several client as a debian package. Each client runs his own server. But the update and support is done by us.
We make regular releases of the product, with a clean version number. Most of the users get an automatic update (by Puppet), some others don't.
We want to keep a trace of the version of the application (in order to allow the user to check the version in an "about" section, and for our support to help the user more accurately).
We plan to store the version of the code and the version of the base in our database, and to keep the info up to date automatically.
Is that a good idea ?
The other alternative we see is a file.
EDIT : The code and database schema are updated together. ( if we update to version x.y.z , both code and database go to x.y.z )
Answer: Using a table to track every change to a schema as described in this post is a good practice that I'd definitely suggest to follow.
For the application, if it is shipped independently of the database (which is not clear to me), I'd embed a file in the package (and thus not use the database to store the version of the web application).
If not and thus if both the application and the database versions are maintained in sync, then I'd just use the information stored in the database.
Answer: As a general rule, I would have both, DB version and application version. The problem here is how "private" is the database. If the database is "private" to the application, and user never modifies the schema then your initial solution is fine. In my experience, databases which accumulate several years of data stop being private, it means that users add a table or two and access data using some reporting tool; from that point on the database is not exclusively used by the application any more.
UPDATE
One more thing to consider is users (application) not being able to connect to the DB and calling for support. For this case it would be better to have version, etc.. stored on file system.
Comment: The database is completely private. User dont even know that the  database exist. He dont have crendential and will never have them.
Answer: I'd put them in both places. Then when running your about function you quickly check that they are both the same, and if they aren't you can display extra information about the version mismatch. If they're the same then you will only need to display one of them.
I've generally found users can do "clever" things like revert databases back to old versions by manually copying directories around "because they can" so defensively dealing with it is always a good idea.
Answer: Assuming there are no compelling reasons to go with one approach or the other, I think I'd go with keeping them in the database.


Relation between Frobenius norm and L2 norm?

Question: Is there any relation between the Frobenius norm of a matrix and L2 norm of the vectors contained in this matrix.
Simply put, is there any difference between minimizing the Frobenius norm of a matrix and minimizing the L2 norm of the individual vectors contained in this matrix ?
Please help me understand this.
Answer: Let $A$ be an $m\times n$ matrix with rows $\boldsymbol{a}_1^T,\dots,\boldsymbol{a}_m^T$. That is
$$A=
\begin{bmatrix}
\rule[.5ex]{1.5em}{0.4pt} & \boldsymbol{a}_1^T &\rule[.5ex]{1.5em}{0.4pt} \\
\rule[.5ex]{1.5em}{0.4pt} &\boldsymbol{a}_2^T& \rule[.5ex]{1.5em}{0.4pt} \\
&\vdots& \\
\rule[.5ex]{1.5em}{0.4pt} & \boldsymbol{a}_m^T &\rule[.5ex]{1.5em}{0.4pt}
\end{bmatrix}$$
The squared Frobenius norm is
$$\|A\|_F^2=Tr(AA^T)=Tr\left(
\begin{bmatrix}
\boldsymbol{a}_1^T\boldsymbol{a}_1 & \boldsymbol{a}_1^T\boldsymbol{a}_2& \dots & \boldsymbol{a}_1^T \boldsymbol{a}_m \\
\vdots & \vdots & \ddots & \vdots\\
\boldsymbol{a}_m^T\boldsymbol{a}_1 & \boldsymbol{a}_m^T\boldsymbol{a}_2& \dots & \boldsymbol{a}_m^T \boldsymbol{a}_m
\end{bmatrix}
\right)=\sum_{i=1}^m\boldsymbol{a}_i^T\boldsymbol{a}_i=\sum_{i=1}^m\|\boldsymbol{a}_i\|_2^2$$
Answer: Consider the following matrix:
$$A=\begin{bmatrix}1 &0\\0&1\end{bmatrix}$$
The Frobenius norm is:
$$||A||_F=\sqrt{1^2+0^2+0^2+1^2}=\sqrt 2$$
But, if you take the individual column vectors' L2 norms and sum them, you'll have:
$$n=\sqrt{1^2+0^2}+\sqrt{1^2+0^2}=2$$
But, if you minimize the squared-norm, then you've equivalence. It's explained in the @OriolB answer.
Comment: Note that the relation I posted in my answer is between the squared Frobenius norm and the squared L2 norm. So $\|A\|_F=\sqrt{\sum_i \|\boldsymbol{a}_i\|_2^2}\neq \sum_i \|\boldsymbol{a}_i\|_2$.
Comment: Yes, I referenced your answer in the last sentence. Do I have any contradictory implications?
Comment: If you want to find a relation, you can apply Jensenś inequality as follows: $\|A\|_F=\sqrt{\sum_i \|\boldsymbol{a}_i\|_2^2}=\sqrt{n}\sqrt{\sum_i \frac{1}{n} \|\boldsymbol{a}_i\|_2^2}\geq \sqrt{n}\sum_i \frac{1}{n} \sqrt{\|\boldsymbol{a}_i\|_2^2}=\frac{1}{\sqrt{n}}\sum_i \|\boldsymbol{a}_i\|_2\geq \sum_i \|\boldsymbol{a}_i\|_2$ since $n\geq 1$. So you have to take this into account.
Answer: Given a matrix $A \in \mathbb{K}^{n \times m}$, the squared Forbenius norm is defined as:
$||A||_F^2 := \sum_i^n \sum_j^m(a_{ij})^2 = Tr(A^TA)$,
observe the similarity to the squared $l_2$ norm for a vector $a \in \mathbb{K}^n$:
$||a||_2^2 := \sum_i^n(a_i)^2 = a^Ta$,
so we can rewrite the Frobenius norm as sum of squared $l_2$ norms of the vectors:
$||A||_F^2 = \sum_j^M ||a_j||_2^2 = \sum_j^M a_j^Ta_j$,
where $a_j \in \mathbb{K}^n$ are the column vectors of $A$. Thus if you minimize the squared norm it is equivalent.
Comment: That means if I am minimizing the squared Frebonius norm,then it is equivalent to minimizing the sum of l2 norm of the vectors Right ? Further, is there difference between minimizing the l2 norm of individual vectors & the sum of l2 norm of all the vectors ?


How can I translate string templates in Metatag module?

Question: I use Metatag module. How can I set different string templates for each site language? Or translate these templates.
Answer: Basic internationalization support can be found in the i18n module:

All default configurations may be translated using the
  Internationalization (i18n) module. The custom strings that are
  assigned to e.g. the "Global: Front page" configuration will show up
  in the Translate Interface admin page
  (admin/config/regional/translate/translate) and may be customized per
  language.

There exists at least 1 ongoing issue in Review still with Views, Panels and other 3rd party contrib modules and the metatags module.


Outer crossvalidation cycle in caret package (R)?

Question: Could somebody provide a nice example code how to best implement an outer crossvalidation cycle using the caret package in R? The package provides a convenient trainControl() argument to ajust the inner crossvalidation. However I would like to embed this into multiple outer crossvalidation cycles to get a more stable estimate of the prediction performance of the estimated models!
Answer: Inner and outer CV are used to perform classifier selection not to get a better prediction on the estimate. To get a better estimate, do a repeated cv. So to perform a 10-repeates 5-fold CV use
trainControl(method = "repeatedcv",number = 5,
             ## repeated ten times
             repeats = 10)

But if what you really want is a nested CV, for example to select between a random forest or a svm) then as far as  know you have to do the outer CV explicitly. What I did for an outer 5-fold, inner 10-fold was:
ntrain=length(ytrain)
train.ext=createFolds(ytrain,k=5,returnTrain=TRUE)
test.ext=lapply(train.ext,function(x) (1:ntrain)[-x])

for (i in 1:5){
    model<-train(Class ~ ., data = training[train.ext[[i]]],
                 trControl=trainControl(method = "cv",number = 10),
                 ...
    ...
    }

Comment: I've never really seen a case where nested CV is worth the effort but I did put in the [caret development list](https://github.com/topepo/caret/issues/70) a few weeks ago. It may take a while.
Comment: This is caret author's blog on nested cv: http://appliedpredictivemodeling.com/blog/2017/9/2/njdc83d01pzysvvlgik02t5qnaljnd
Comment: @Jacques Wainer your statement that repeated cv is preferred to nested cv for getting a better estimate is very interesting - do you have any citation for that? does it refer to robustness, and how is this better addressed in repeated cv than nested cv?


Find range of $f(\sqrt 2)$ for $f(x)=e^{\frac{x^2}{2}}+\int_0^x tf(t)dt$

Question: Let $f:\mathbb{R}\rightarrow\mathbb{R}$ be a continuous function satisfying
$$f(x)=e^{\frac{x^2}{2}}+\int_0^x tf(t)\mathrm{d}t$$
Then which of the following is correct:
(A) $5<f(\sqrt 2)<6$
(B) $2<f(\sqrt 2)<3$
(C) $3<f(\sqrt 2)<4$
(D) $4<f(\sqrt 2)<5$
My attempts so far:
Taking derivative of $f(x)$ we get
$$f'(x)=x.e^{\frac{x^2}{2}}+x.f(x)$$
$$\frac{f'(x)}{x}-e^{\frac{x^2}{2}}=f(x)$$
On solving the differential equation we get $$f(x)=\left(C+\frac{x^2}{2}\right)e^{\frac{x^2}{2}}$$
And putting $x=\sqrt 2$ we get $f(\sqrt 2)=(C+1)e$ but I can't figure out the value of $C$.
Other attempts include writing $f(x)$ in terms of its derivative like above and putting it inside the integral, but upon solving it simply yields $f(x)$.
I also tried finding $f(2)$ and $f(1)$ as $\sqrt 2$ lies between 1 and 2 and tried finding their difference to see if it yields any insight.
$$f(1)= \sqrt e + \int_0^1tf(t)dt $$
$$f(2)= e^2 + \int_0^2tf(t)dt $$
$$ e^2 +\int_0^1tf(t)dt+ \int_1^2tf(t)dt= e^2 +\int_0^1tf(t)dt+ \int_0^1(t-1)f(t-1)dt$$
Subtracting both these equations yields:
$$f(2)-f(1)=e^2- \sqrt e + \int_0^1 (t-1)f(t-1)$$
I am at a loss on how to proceed further with this problem, any hints/ insights would be really appreciated.
Edit:
From comment of @Annebauval $f(0)=C=1$ and putting it in solution of differential equation we get $f(\sqrt 2)=2e \approx 5.43\,$ hence the correct answer is (A) option.
Comment: I'm voting to close this question because it has been answered in the comments.
Comment: $C=f(0)=1.$____
Comment: Thanks a lot @AnneBauval
Comment: @AnneBauval, if you remove your close vote, I will write an answer with a different solution.
Comment: @AnneBauval, please remove your close vote.
Comment: Why would someone want to close a question if it's not even a duplicate.
Comment: I won't but as long as the post is not closed, anybody can write another answer. @Angelo And the OP can even change their choice of which answer they accept.
Answer: $\displaystyle f(x)=e^{\frac{x^2}{2}}+\int_0^x tf(t)\,\mathrm dt\quad$ for any $\,x\in\Bbb R\,.\quad\color{blue}{(*)}$
From $(*)\,,\,$ for $\,x=\sqrt2\,,\,$ we get that
$f\left(\sqrt2\right)=e+\displaystyle\int_0^{\sqrt2}tf(t)\,\mathrm dt\,.\quad\color{blue}{(**)}$
Moreover, it results that
$\begin{align}\displaystyle D\left(e^{-\frac{x^2}2}\int_0^xtf(t)\,\mathrm dt\right)&=e^{-\frac{x^2}2}xf(x)-xe^{-\frac{x^2}2} \int_0^xtf(t)\,\mathrm dt=\\[2pt]
&=xe^{-\frac{x^2}2}\left(f(x)-\int_0^xtf(t)\,\mathrm dt\right)=\\[2pt]
&\underset{\overbrace{\text{ by using }(*)}}{=}xe^{-\frac{x^2}2}e^{\frac{x^2}2}=x=D\left(\dfrac{x^2}2\right).\end{align}$
Consequently ,
$\displaystyle e^{-\frac{x^2}2}\int_0^xtf(t)\,\mathrm dt=\dfrac{x^2}2+c\quad$ for any $\,x\in\Bbb R\,.$
It is obvious that $\,c=0\,,\,$ so we get that
$\displaystyle\int_0^xtf(t)\,\mathrm dt=\dfrac{x^2}2e^{\frac{x^2}2}\quad$ for any $\,x\in\Bbb R\,.$
In particular, for $\,x=\sqrt2\,,\,$ it results that
$\displaystyle\int_0^{\sqrt2}tf(t)\,\mathrm dt=e\,.\qquad\color{blue}{(*\!*\!*)}$
From $\,(**)\,$ and $\,(*\!*\!*)\,,\,$ it follows that
$f\left(\sqrt2\right)=2e\in\big]5,6\big[\,.$
Answer: Pluggign $x=0$ in the first equation:
$$f(x)=e^{\frac{x^2}{2}}+\int_0^x tf(t)dt\ \implies\ f(0)=e^{\frac{0^2}{2}}+\int_0^0 tf(t)dt=e^0=1$$
Now plugging $x=0$ in the second equation you found for $f(x)$ we get:
$$f(x)=(C+\frac{x^2}{2})e^{\frac{x^2}{2}}\ \implies\ \ f(0)=(C+\frac{0^2}{2})e^{\frac{0^2}{2}} =Ce^0=C $$
Therefore, combining the results we get:
$$f(0)=1,\ f(0)=C\ \implies \ C=1$$
Therefore your function is
$$f(x)=(1+\frac{x^2}{2})e^{\frac{x^2}{2}}$$
and you can easily plug $\sqrt{2}$ in.


Detecting structural breaks in multivariate time series data

Question: I have a dataset of daily sales data (day 1 to day 365) with a number of factors influencing sales. I would like to identify structural breaks in sales data to group them in a sensible manner (day 1 to 60, day 61 to 200, etc) based on a) only univariate time series excluding features b) including features. The groupings should be meaningful, so not a black box model!
I would like to this analysis in R as I don't have SAS or STATA or Python at work place. We have a total of 3000 stores globally, so need an approach that is scalable. We only plan to do this exercise once every 6 months, so not too concerned about time it takes to run.
Comment: Relevant keywords: "impulse indicator saturation" and "step indicator saturation". These are new approaches that generally have high power, so probably better than the Chow test.
Comment: Hi Richard----why?
Answer: Why do you say that you have multivariate data when you then say you want "only univariate"? That's confusing. Please rephrase or explain more clearly.
You will need to test for changes in parameters and also variance. You will want to use the Chow test ("strucchange" package in R) to do an $F$-test to see if the model has changed. You will also want to consider the Tsay test ("tsa" package) if the variance has changed. These will flag when change is occurring.  There are also level shifts, changes in trend and seasonal pulses (i.e. Wednesday's are high and become low) that you might want to also consider.
I would point you to Autobox (but you are restricted to R -- I am affiliated with Autobox).
Comment: Thanks and sorry for the confusion, I wanted to understand how one would approach this with univariate v/s multivariate series. At present we have only univariate data but will start receiving multivariate data towards end of next year. I will look into R packages you suggest. thanks.
Comment: It doesn't look like strucchange allows for multivariate....


Sobolev inequality cannot hold for all compactly supported smooth functions

Question: I am on a course on Sobolev Spaces and we had this as an exercise:
Let $1\leq p<n$ and $q< p^*$, where $p^*=(pn)/(n-p)$. Show that
$||u||_{L^q(\mathbb{R}^n)}\leq C(q,p,n)||\nabla u||_{L^p(\mathbb{R}^n)}$
cannot hold for all $u\in C_0^\infty(\mathbb{R}^n).$
We were given a hint that if we take some $u\in C_0^\infty(\mathbb{R}^n)$ and then scale the variable inside, then we could show this. But I am at a loss, and don't know how to use the hint.
Comment: You mean that q is *strictly* smaller than $p^\star$, right?
Comment: Yes, I had a typo, thank you :)
Answer: Hint: For fixed $u \in C_c^\infty$, consider $u_t$ defined by $u_t(x) = u(tx)$ for $t>0$. Then express the norms of $u_t$ in the Sobolev inequality by scaled versions of the norms of $u$.
Comment: On the left I get the same norm? And on the right I get t times everything? I don't see where this leads?
Comment: Now let $t\to 0$ or $t\to \infty$.
Comment: So now if $t\to 0$ and the norm of u is positive (say 1) then the inequality doesn't work. But why do we assume that $q≤p^*$? I don't understand why the same conclusion would not surface with $p^*$.
Comment: The parameters do not play a role, as the right hand side is $\|\nabla u\|_{L^p}$ and not $\|u\|_{W^{1,p}}$. The inequality is false on unbounded domains regardless of parameters $p,q,n$.


How to convert imperial to metric units?

Question: This is more of a general question of both code and math. I'm not at all good at math, and I'm still learning how to apply math in programming.
Let's say, I have an object of data that has the amount, the measurement, and the type, such as feet or lb.
const data = {
  0: {
    'type': 'imperial',
    'unit': 'ft',
    'amount': 3
  },
  1: {
    'type': 'imperial',
    'unit': 'lb',
    'amount': 5
  },
  2: {
    'type': 'imperial',
    'unit': 'mph',
    'amount': 7
  }
}

And I need to go through this data and convert each according to the type (assuming type is what it's called)
Object.keys(data).map(key => {
    convert(data[key]['amount'], data[key]['type'], data[key]['unit'])
})

And the function converts this:
const convert = (amount, type, unit) => {
   const calc = // ???
   return calc;
}

My question is, how do I convert depending on the type of measurement? I know that 1 foot is 0.3048 meters, and if I needed to convert 5 feet to meters, I'd do 5*0.3048.
However, how can I apply this in code, with a list of imperial and metric units and how would I add this to the convert function?
Comment: As a first step, you could do `if (type == "imperial") { ... }` and in there `if (unit == "feet") return amount * 0.3048;`
Comment: Maybe you need to know which unit to convert into as well, for example mph becomes m/s or km/h?
Comment: Yes, I can understand how to convert with something like https://www.mathsisfun.com/metric-imperial-conversion-charts.html just not sure how to apply it in code...
Comment: @ChrisG I probably need to do this for about 10 measurements. How would this look if the units were stored in it's own object and I'd go through each one?

I also need to convert from metric to imperial as well via click event...
Answer: You can have a converter Object with functions to convert and labels to display, here's an example ( adjust the values and units to your needs ) :

const data = {
  0: {
    type: "imperial",
    unit: "ft",
    amount: 3
  },
  1: {
    type: "imperial",
    unit: "lb",
    amount: 5
  },
  2: {
    type: "imperial",
    unit: "mph",
    amount: 7
  }
};

const converter = {
  imperialToMetric: {
    ft: val => val * 0.3048,
    lb: val => val * 0.453592,
    mph: val => val * 1.60934,
    labels: {
      ft: "meters",
      lb: "Kg",
      mph: "kmh"
    }
  },
  metric: {
    // reverse the above
  }
};

const result = Object.values(data).map(({ amount, type, unit }) => ({
  amount: converter.imperialToMetric[unit](amount),
  unit: converter.imperialToMetric.labels[unit],
  type: "metric"
}));

console.log(result);
Comment: When you say reverse, do you mean divide instead of multiply?
Comment: How would I convert _only once_ of an object and store it? Not really related to the question but I'm curious how I'd do it in this case.
Comment: not necessarily, you can check the table of conversion ( but doing a quick match, yes you can divide instead of multiply ) , to convert only once, you can do `const result = {
  amount: converter.imperialToMetric[data[0].unit](data[0].amount),
  unit: converter.imperialToMetric.labels[data[0].unit],
  typ: "metric"
};`


Does a sack count as a Tackle For Loss, and/or a Tackle?

Question: I like to look at player statistics, and I always see the Tackle stat, the Sack stat, and sometimes the Tackle For Loss stat. Is there some overlap in the stats so that a Sack counts as a Tackle?
ie) A player has 7 sacks in one season, and 81 tackles, and 23 tackles for loss.
Is there overlap so that they actually had 74 tackles and seven of them were counted as sacks, and they had 16 tackles for loss, but again, seven of them were counted by sacks. Does anybody know if there is overlap, and some stats are have duplicates, or do they not count a sack as a TFL or a tackle?
Comment: A sack is not necessarily a tackle for loss, since it can happen on the LoS as well.
Comment: Do you know which one is more consistent, to be double counted or to not be?
Answer: Sacks and Tackles for Loss are both subsets of Tackles. Whether or not Sacks can be recorded as Tackles for Loss seems to vary based on who is reporting. For example:
This ESPN Box Score lists Dante Fowler as having 1 sack and 1 TFL. However, the Pro-Football Reference for the same game gives him 1 sack and 0 TFL. It's clear that PFR records TFLs as separate from sacks, but ESPN lists sacks as a subset of TFLs.
So, to answer your question by using your example, a player with 7 sacks in one season, and 81 tackles, and 23 tackles for loss had 81 total tackles, 7 of which were sacks. 23 of his 81 tackles were for loss, and that MAY be including the 7 sacks or not, depending on who is recording the stats.
Comment: Is a strip sack considered a tackle, even if the quarterback is still standing at the end of it?


Not Supported exception in the download of file with c#

Question: I'd like to download a file in my ASP.NET application. I used this snippet:
try
{
    string s = fichier.GetFichierUrlById(_id);
    Response.ContentType = "application/" + Path.GetExtension(s);
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + s);
    Response.TransmitFile(Server.MapPath("~/Downloads/"+s));
    Response.End();
}
catch { }

In this example, I have the file setup.exe, and I get an exception like The format of the given path is not supported.
What is the cause of this exception? How can I fix the code?
Answer: Check the value of S, and hence, the return value of "Server.MapPath("~/Downloads/"+s).
You might have some invalid characters in S which blow things out maybe?
Answer: TransmitFile would assume that there is a physical file in the downloads sub folder.
If that is not the case, then you'll need to do something like write the data into the output stream yourself.


How the sum of 2 random variables is also a random variable...

Question: Say I have two random variables $X$ and $Y$ defined on a probability space ($\Omega,\mathbb{F},\mathbb{P}$).
To prove $X+Y$ is also a random variable, I need $\{\omega:(X+Y)(\omega)\le x\}\in \mathbb{F},\ \forall x\in \mathbb{R}.$
For positive random variables, I can simply write this set as an intersection of two sets, $\{\omega:X(\omega)\le x\}$ and $\{\omega:Y(\omega)\le x\}$, and invoke the property of the sigma algebra.
Now, how do I extend this to arbitrary-valued random variables? Or is there an intersection that is irrespective of the value of the RVs?
Answer: For all $x \in \mathbb{R}$ you have
$$ \{\omega \in \Omega \::\: (X+Y)(\omega) < x \}
=  \bigcup_{q \in \mathbb{Q}} \{\omega \in \Omega \::\: X(\omega) < x-q, Y(\omega) < q  \} $$
a countable union of sets of the form
$$\{\omega \in \Omega \::\: X(\omega) < x-q\} \cap \{\omega \in \Omega \::\: Y(\omega) < q\} \in \mathbb{F}$$
and we conclude $\{\omega \in \Omega \::\: (X+Y)(\omega) < x \} \in \mathbb{F}$
for all $x \in \mathbb{R}$, which proves $X+Y$ to be a random variable.
Please note, that in general
$$ \{\omega \in \Omega \::\: (X+Y)(\omega) \leq x \} \neq \{\omega \in \Omega \::\: X(\omega) \leq x\} \cap \{\omega \in \Omega \::\: Y(\omega) \leq x\}, $$
even if $X$ and $Y$ are assumed positive as there could be an $\omega \in \Omega$ with $X(\omega) = Y(\omega) = x >0$ and then $\omega$ would only be contained in the second one of these sets.

EDIT (suggested by Didier Piau):
Using the result above you also have
$$\{\omega \in \Omega \::\: (X+Y)(\omega) \leq x \} = \bigcap_{n \in \mathbb{N}} \{\omega \in \Omega \::\: (X+Y)(\omega) < x +\frac{1}{n} \} \in \mathbb{F}.$$
Comment: The OP seems to prefer $\{X+Y\leqslant x\}$ to $\{X+Y\lt x\}$. You might want to adapt your (excellent) solution to this setting.
Comment: I think it's clear that the RHS is contained in the LHS. For the other inclusion let $\omega \in \Omega$ with $(X+Y)(\omega) < x$, then you have $\varepsilon > 0$ with
$(X+Y)(\omega) \leq x - \varepsilon$. Now you find a $q \in \mathbb{Q}$ with $q-\frac{\varepsilon}{2} \leq Y(\omega) \leq q$ (because $\mathbb{Q}$ is dense, as you suspected) and this shows $X(\omega) + q \leq (X+Y)(\omega) + \frac{\varepsilon}{2} < x $
which shows that $\omega$ is contained in the RHS.
Comment: What does ω, Ω, q and F mean?
Comment: @AlvaroMorales: I am not completely sure, I understand what you are asking. As specified by the OP, $(\Omega,\mathbb{F},\mathbb{P})$ is a probability space, so $\Omega$ is a set, $\mathbb{F}$ is a $\sigma$-algebra consisting of subsets of $\Omega$ and $\mathbb{P}$ is a probability measure on $\mathbb{F}$.
Comment: @MatthiasKlupsch, thanks. I'm taking master's courses in stats so I'm having many doubts.