Matching A General Pattern In One String To Another

Question: I have a list of poker hands stored in an array in this format:
$hands = ['AsQdTc9h', 'AsQsTd9d' ...]
I also have a search string that is 4 characters and uses the letters xyzw. For example, search string could look like:
$searchString = 'xyxy';
$searchString = 'xyzw';
$searchString = 'yzyw';

The entire purpose of the search string is to identify a desired pattern for the lowercase characters in the hand.
So if the searchString is xyzw, that is just a way of saying 'only select hands where none of the lowercase letters are equal.' If the search string is xyxy, that is a way of saying 'only select hands where the first and the third lowercase letters are equal and the second and fourth lowercase letters are equal.
In other words, the lowercase letters must match the pattern of the search string. How can I implement this in PHP?
Comment: so that means in `AsQsTd9d` the lowercase letters are `ssdd` and pattern is `xxyy` ?
Comment: @Abolix Exactly. And I think this goes without saying, but `xxyy` should also match if the lowercase letters were `ddhh`, `sshh`, `ccdd`, etc.
Answer: $MyString = 'AsQdTc9h';
$MyString = preg_replace('/[^a-z]/', '', $MyString); // Get only the lowercase characters
// $MyString : sdch

$LetterArray = str_split($MyString);
$LetterArray = array_count_values($LetterArray);

$ReplaceList = ['x', 'y', 'z', 'w'];
$i = 0;
foreach ($LetterArray as $Letter => $result) {
    $MyString = str_replace($Letter, $ReplaceList[$i], $MyString);
    $i++;
}
echo $MyString; // expected output : xyzw

i want to explain the code so you can understand it , first we got all the lowercase characters using regex . then we turned the 4-character words to a array and then we counted how many of the characters are the same .
then we replaced the results to xyzw .
Answer: Although this seems like a pattern matching task, due to the very limited length of the strings a pseudo-brute-force checking might be the easiest.
function pokerMatch(string $hand, string $pattern): bool
{
    $hand = preg_replace('/[^a-z]/', '', $hand);

    for ($i = 0; $i < strlen($hand); $i++) {
        for ($j = $i+1; $j < strlen($hand); $j++) {
            if ($pattern[$i] === $pattern[$j] && $hand[$i] !== $hand[$j]) {
                return false;
            }
            if ($pattern[$i] !== $pattern[$j] && $hand[$i] === $hand[$j]) {
                return false;
            }
        }
    }
    return true;
}

Basically what this does, it goes over pattern string, takes each pair of characters and checks:

if the letters in pattern positions i and j are equals then so must be the characters in the hand string;
if the letters in pattern positions i and j are different then so must be the characters in the hand string;

If any of these doesn't hold - the pattern doesn't match
If after checking all pairs we found no mismatches - then it's a match.
Usage:
var_dump(pokerMatch('AsQdTc9h', 'xyzw')); // => bool(true)
var_dump(pokerMatch('AsQdTc9h', 'xyzz')); // => bool(false)
var_dump(pokerMatch('AsQsTc9c', 'xxyy')); // => bool(true)
var_dump(pokerMatch('AsQsTc9c', 'zzww')); // => bool(true) (it's agnostic to exact letters)

Answer: You can solve this by iterating over each hand and search string, keeping a record of which suit matches which search letter, and checking that they are always consistent:
$hands = ['AsQdTc9h', 'AsQsTd9d', 'AsKh9s9d'];
$searchStrings = ['xyxy', 'xyzw', 'yzyw', 'ppqq'];

function match_hand($hand, $search) {
    $h = preg_replace('/[^a-z]/', '', $hand);
    $matches = array();
    for ($i = 0; $i < strlen($search); $i++) {
        $s = $search[$i];
        // have we seen this search letter before?
        if (isset($matches[$s])) {
            // does it match the previous value? if not, it's an error
            if ($matches[$s] != $h[$i]) return false;
        }
        else {
            // haven't seen this search letter before, so this hand letter should not be in the matches array yet
            if (in_array($h[$i], $matches)) return false;
        }
        $matches[$s] = $h[$i];
    }
    return true;
}

foreach ($hands as $hand) {
    foreach ($searchStrings as $search) {
        if (match_hand($hand, $search)) {
            echo "hand $hand matches pattern $search\n";
        }
    }
}

Output:
hand AsQdTc9h matches pattern xyzw
hand AsQsTd9d matches pattern ppqq
hand AsKh9s9d matches pattern yzyw

Demo on 3v4l.org


How do I configure mplayer to use a default edl file name?

Question: I want to configure mplayer to look for an edl when playing a video. Specifically, I want it to use "show.edl" when playing "show.mp4", assuming both are in the same directory. Very similar to how it looks for subtitles.
I can add a default edl in the config file by adding the following:
edl=default.edl
And this will look for the file "default.edl" IN THE CURRENT DIRECTORY, rather than in the directory where the media file is. And it isn't named after the media file either, and thus even if it did look in the right place, I'd have one single edl file for every media file in that directory.
Not really what I wanted.
So, is there a way, in the "~/.mplayer/config" file, to specify the edl relative to the input file name?
Mplayer's config file format doesn't seem to support any sort of replacement syntax. So there's no way to do this?
Answer: MPlayer does not have a native method to specify strings in the config file relative to the input file name. So there's no native way to deal with this.
There's a variety of approaches you could use to get around that. Writing a wrapper around mplayer to parse out the input file and add an "-edl=" parameter is fairly general, but will fail on playlists, and I'm sure lots of other edge cases. The most general solution would of course be to add the functionality to mplayer's config parser (m_parse.c, iirc.)
The simplest, though, is to (ab)use media-specific configuration files.
pros:

Doesn't require recompiling mplayer!
Well defined and limited failure modes. I.E. the ways it fails and when it fails are easily understood, and there aren't hidden "oops, didn't expect that" behaviors hidden anywhere.
Construction and updating of the edl files is easily automated.

cons:

Fails if you move the media around, as the config files need to full path to the edl file  to function correctly.
Requires you have a ".conf" file as well as an EDL file, which adds clutter to the file system.
Malicious config files in the media directory may be a security issue. (Though if you're allowing general upload of media files, you probably have bigger problems. mplayer is not at all a security-hardened codebase, nor generally are the codecs it uses.)

To make this work:

Add "use-filedir-conf=yes" to "/etc/mplayer.conf" or "~/.mplayer/config". This is required, as looking in the media directory for config files is turned off by default,
For each file "clip.mp4" which has an edl "clip.edl" in the same directory, create a file "clip.mp4.conf" which contains the single line "edl=/path/to/clip.edl". The complete path is required.
Enjoy!

Automatic creation and updating of the media-specific .conf files is left as an exercise for the student.


How to connect domain clients to workgroup WSUS server

Question: We have a small domain that sits on the same net as a single workgroup host with WSUS server.
Is it possible to  get the clients to connect to the workgroup host WSUS server?
The WSUS has IIS7 and is running on Windows Server 2008 R2.

On the WSUS server, am I supposed to set 'User group policy or registry' for clients, or update services console?
With 'User group policy or registry' chosen, I used this tool (http://wsusworkgroup.codeplex.com/) to set the registry to workgroupWSUS
The WSUS server is accessible (tested with) "workgroupWSUS/iuident.cab" in the browser
wauaclt.exe /detectnow is failing contact the WSUS server.
The WSUS is not showing any status reports from client computers.

Any assistance or confirmation that this is possible would be highly appreciated.
Comment: To clarify, you modified the Windows Update group policy to make domain clients point to this WSUS server, right?
Comment: @Nathan C I did not actually modify the group policy, so far I have only set registry settings on the clients via the linked application in my post. I am quite new to domain and network setups - Do I have to go and modify the group policy on the domain controller, or are the registry settings an alternative?
Comment: Um, put the WSUS server on the domain?
Comment: If you set the registry policy manually on the clients, you have to restart the Automatic Updates (wuauserv) service on them for it to take effect. Then try a wuauclt /detectnow. The WSUS server does not have to be on the domain.
Comment: @DanBig Unfortunately I can't put the WSUS on the domain.
Answer: The registry setting isn't the proper way to do this. You want a GPO with the WSUS settings on it. See this for details: http://technet.microsoft.com/en-us/library/cc720539(v=ws.10).aspx
The interesting bits are under Administrative Templates, expand Windows Components, and then click Windows Update.
Obviously, apply the GPO using your domain controller.
Comment: Thanks Nathan, I will give this a try and report/accept if I manage.


How to prove that the $L^p$ spaces are infinite dimensional

Question: It is well-known that (given a measure space $(S,\mathcal A,\mu)$ and $1\le p\le\infty$) the Banach space $L^p(S,\mathcal A,\mu)$ has infinite dimension.
Is there an easy way to proof this statement (or a suitable reference (preferably a book) where I can find this result)?
Comment: if $\mathcal{A}$ is finite, you can't prove it. Otherwise consider indicator functions of all measurable sets
Comment: You can find necessary and sufficient conditions for finite-dimensionality [here](http://math.stackexchange.com/q/151015/5363) (in case $\mu$ is totally finite --- remember that $L^p \subset L^1$ under this assumption). @Norbert: it also depends on the measure...
Comment: You are also in trouble if $\mu = 0$.
Answer: As Norbert mentioned, this is simply not true if $S$ is finite.
In general, suppose you can find a collection of countably infinite pairwise disjoint measurable sets $\{ A_n:n\in \mathbb{N}\}$, each with finite positive measure.  Then, the collection $\{ 1_{A_n}:n\in \mathbb{N}\}$ is an infinite linearly independent set contained in $L^p$.  Why?  First of all, the fact that each $A_k$ has finite measure guarantees that $1_{A_k}$ is an element of $L^p$.  As for linear independence, suppose we have some finite linear combination of these functions that is equal to $0$:
$$
a_11_{A_{n_1}}+\cdots +a_m1_{A_{n_m}}=0.
$$
Now, multiply this equation by $1_{A_{n_k}}$ and integrate.  You will find that
$$
a_k\mu (A_{n_k})=0,
$$
and hence, because $\mu (A_{n_k})>0$, we have that $a_k=0$, which proves linear independence.
Answer: Since $l^{p}$ embeds isomorphically into $L^{p}$,and it's easy to check that $l^{p}$ is infinitive dimensional.


TypeScript - waiting for nested for loops to complete

Question: I have two for loops, one nested inside the other. The first loop makes an API call. It will execute for how ever many IDs are selected by the user. I do not have the ability pass more than one ID at a time to the API. The nested loop will run for each object returned by the API and add the data to an array. My end goal is to have all data in a single array, and to pass that array to a child component using @Input(). I have researched and attempted to do this using a Promise, but something is still not quite right. I would like ngOnChanges() in the child component to only execute once all of the data has been returned - aka both for loops have completed execution. This is what I have done:
Parent Component:
  getData() {
    let temp: MyObjectType[] = [];
    let allDataToSend: MyObjectType[] = [];

    return new Promise<MyObjectType[]>((resolve, reject) => {

      for (let i = 0; i < this.userIdSelections.length; i++) {
        this.dataService.getData(this.userIdSelections[i])
          .subscribe(results => temp = results,
            error => {
              this.getRequestResult = <any>error;
            },
            () => {

                for (let j = 0; j < temp.length; j++) {
                  allDataToSend.push({
                    Property1: temp[j].Property1,
                    Property2: temp[j].Property2,
                    Property3: temp[j].Property3,
                    Property4: temp[j].Property4,
                  });

              }
            }
          );
      }
      resolve(allDataToSend);
    });
  }

  finalResults() {
    this.getData().then(response => {
      this.FinalObjectSendToChild = response;
    })
  }

Parent Template:
<button mat-flat-button color="primary" (click)="finalResults()">Search</button>

<app-child [finalData]="FinalObjectSendToChild"></app-child>

Child Component:
export class ChildComponent implements OnChanges {
  @Input() finalData: MyObjectType[];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  public tableColumns = ['Property1', 'Property2', 'Property3', 'Property4'];
  public tableData: any

  constructor() { }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.finalData) this.createTable();
  }

  createTable() {
    console.log(this.finalData); // this will show all of the data the way I would expect
    console.log(this.finalData.length); // however, this always returns 0
    // the table created is blank...
    this.tableData = new MatTableDataSource(this.finalData);
    this.tableData.sort = this.sort;
    this.tableData.paginator = this.paginator;
  }

Answer: You can use Promise.All:

(...)
for (let i = 0; i < this.userIdSelections.length; i++) {
  arrayPromises.push(this.dataService.getData(this.userIdSelections[i]).toPromise());
}

Promise.all(arrayPromises).then((values) => {
  const allDataToSend = [];
  for(let value of values) {
    for (let j = 0; j < value.length; j++) {
        allDataToSend.push({
          Property1: value[j].Property1,
          Property2: value[j].Property2,
          Property3: value[j].Property3,
          Property4: value[j].Property4,
        });
    }
  }
  resolve(allDataToSend);
});
(...)
Comment: I just needed to change "for(let value in values)" to "for(let value of values)" and it worked great.


How to publish webpack on Vite properly

Question: Im trying to publish locally a webpack on Vite to test micro front ends, but when I run my host app, it doesn't find the remoteEntry.js, and thats because when I try to access my remoteEntry.js, it doesn't exist. Does anyone know why?
This is my vite.conf on the remote
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// https://vitejs.dev/config/

// vite.config.js
import federation from "@originjs/vite-plugin-federation";
export default defineConfig({
  server: {
    port: 8080,
  },
  plugins: [
    vue(),
    federation({
      name: "myLib",
      filename: "remoteEntry.js",
      // Modules to expose
      exposes: {
        "./Counter": "./src/components/Counter.vue",
      },
      remotes: {},
      shared: ["vue"],
    }),
  ],
});

And this is the config on the remote side:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import federation from "@originjs/vite-plugin-federation";

export default defineConfig({
  server: {
    port: 8081,
  },
  plugins: [
    vue(),
    federation({
      name: "myApp",
      remotes: {
        myLib: "http://localhost:8080/assets/remoteEntry.js",
      },
      shared: ["vue"],
    }),
  ],
});

When i try to access my dependencies on the host side, this error pops on the console:
Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:8080/assets/remoteEntry.js
Thank you very much
Comment: I have the same problem, could you find a solution?
Comment: Nope, still waiting haha
Answer: The remoteEntry.js file is not built if you are starting your remote server by running the vite command. To get around this you can run vite preview to launch a development server using the actual bundle.
The docs mention this briefly here: https://github.com/originjs/vite-plugin-federation#vite-dev-mode
They suggest you run vite build --watch if you want your changes to hot update. You can also specify a development build by adding the --mode=development argument.
Answer: I'm having a similar issue, I fixed like custom domain. you can add hosts domain and run your code. example
For Windows
C:\Windows\System32\drivers\etc\hosts
add below
127.0.0.1 client1.test.com

and you can change in host vite.config.ts localhost to client1.test.com
now it will work
Answer: I'm having a similar issue, but I'm using nx in addition to vite. My problem is that vite build will generate remoteEntry.js in the dist directory, but it doesn't run the remote server (as mentioned in the docs). But, while vite preview does start a server for the remote, and it serves out of the dist directory, it triggers a build again, but in dev mode, which doesn't seem to use the vite-plugin-federation plugin...because it overwrites the dist directory with the same set of files I see when running in dev mode (i.e. it doesn't produce remoteEntry.js). This may be an nx thing, as nx preview defaults to building with the development configuration. If I update nx's project.json to use the production configuration, it does produce remoteEntry.js and serves the project successfully.
So, pdro_99, first check your dist directory while running in preview mode, and see if there is actually a remoteEntry.js. Second, try running vite preview in production mode, to see if that'll produce the module federation files.

How to publish webpack on Vite properly


How to safely remove drush via pear and then install via composer?

Question: I have drush 5 installed on my VPS running CentOS 6. Drush was installed using PEAR.
Can I just remove the drush directory and the simlinks and then install drush 7 using composer?
I have been searching for a way to uninstall drush, but all I get are tutorials to install it.
Answer: Uninstalling Drush using Pear
If Drush has been installed using Pear, it can be removed using the following command.
pear uninstall drush/drush

Installing Drush via Composer
For the most current install instructions, refer to the Drush GitHub page.
1) Add Composer's global bin directory to the system PATH (recommended):
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
source $HOME/.bashrc

2) Install Drush
composer global require drush/drush

Answer: Drush doesn't really have any components that need to be "uninstalled".  If the drush binary is somewhere on your PATH, then it's installed.  If you just go ahead and install Drush 7 via composer, and insure that the newer Drush appears first in your PATH, then you can even leave Drush 5 on your system with no ill effects.  You might even want to make a 'drush5' alias as a fallback, in case -- although personally, I run Drush 6 and Drush 7 on my system.  I use Drush 7 for most things.


Economizar espaço, SVG, Base64 ou imagens normais?

Question: Criei esta pergunta com intuito de esclarecer dúvidas que acabei desenvolvendo com passar dos meses em relação a imagens e espaço.
Enquanto acesso sites, tanto em meu celular ou meu computador normal, eu tenho observado que imagens em SVG ou codificadas usando base64 são carregadas mais rapidamente em relação a imagens normais1, percebo isso principalmente quando minha internet está lenta.
Desde então carrego essa dúvida na minha cabeça, qual é o mais vantajoso de usar em relação a espaço de armazenamento (em benefício do servidor) e que ao mesmo tempo tenha o carregamento mais rápido (em benefício do usuário final).
Em meus projetos que usam bastante imagens, tais como uma rede social, que carrega imagens de avatares etc, eu uso como alternativa estes passos para tentar ajudar o servidor sem atrapalhar o resultado final:

Quando a imagem é "upada", ele reduz ao tamanho (medidas x,y) que eu determino e diminui a qualidade para não ocupar espaço em meu servidor.
Para exibir ela ao usuário final, dentro do <img eu faço a imagem passar por um thumb que corta a imagem de acordo com minha necessidade, sem perder a qualidade original, com redimensionamento automático.

Creio que as respostas a esta pergunta irão ajudar bastante não só a mim, mas como ao público no geral e futuros web sites, assim ajudando todo mundo.

1 Imagens normais: .png, .gif, .jpeg etc..
Comment: Uma pergunta interessante e relacionada no SOen http://stackoverflow.com/questions/1124149/is-embedding-background-image-data-into-css-as-base64-good-or-bad-practice
Comment: @user3163662 Não entendi "colocar mais carga em pouco espaço". base64 é para representação de dados binários (uma imagem, por exemplo) como texto; é mais amigável e usa menos bytes do que representar com os caracteres "0" e "1". Então pode fazer sentido suas imagens serem codificadas para base64 para trafegarem em um xml, ou em um json, ou para serem salvas em um css, mas não faz sentido você armazenar imagens no servidor em base64 - isso inclusive aumentaria o espaço ocupado por elas (talvez para economizar processamento na hora de enviar para o client, mas nunca ouvi falar deste uso).
Comment: base64 não economiza espaço de armazenamento de imagens; ele economiza espaço quando uma imagem precisa ser representada como texto (em um Json, CSS...). Veja, 8 bits de uma imagem representado como texto: `01001101`, ocupa 8 acaracteres, ou seja, no mínimo 64 bits. Agora, estes mesmos bits representados em base64: `T`, ou seja, 1 caracter, ocupando apenas os mesmos 8 bits que a representação binária original da imagem.
Comment: @Caffé entao ele so tras utilidade pra "quando uma imagem precisa ser representada como texto (em um Json, CSS...)".. Pelo que falou sobre os bytes ele apenas coloca mais carga em pouco espaco.
Answer: Imagens SVG são imagens vetoriais enquanto que imagens png, jpg e etc. são imagens matriciais.
Uma imagem SVG nada mais é que um arquivo de texto com um XML descrevendo arcos, posições, gradientes, preenchimentos e etc. Experimente abrir num editor de textos como o Vim/Gedit (Linux) ou Notepad/Notepad++ (Windows).
Assim elas são muito menores do que os outros tipos de arquivos que descrevem a imagem bit a bit como é o caso das imagens matriciais, mesmo com a compressão que os vários tipos de imagem têm.
A diferença é que SVG são desenhos, não fotos. E mesmo que alguns mais complexos cheguem a parecer bem reais, nunca serão fotos.
A vantagem do SVG é que, por ser vetorial, nunca perde resolução, nos maiores e menores tamanhos.
Já uma imagem matricial, com alguns zooms, já aparece aquele "quadriculado" típico que indica o limite de resolução dela. Se a aplicação que você quer dar são ícones, SVG ocupará menos espaço, mas não será possível utilizá-lo para fotos.
Comment: Bacana! Se eu não aprender mais nada hoje, já saio satisfeito pela explicação sobre SVG.
Comment: Boa resposta, dei apenas uma ajeitada nela ;)


Deploying Angular 2 app to Azure

Question: I'm trying to set up a continuous integration deployment process using github and an webapp on MS Azure. The Angular app is set up using Angular CLI. I'd like the web to be deployed to the azure webapp when I do a push to my github-repo.
What I've done so far:
-Angular app setup and running. Code pushed to a github-repo.
-I've created custom deployment-scripts with KUDU (.deployment / deploy.cmd)
-Webapp created in azure and its binded to github
My problem is that the build is triggered when pushing the code to github but the Angular-app doesn't seem to be built. Instead the \dist-folder contains a copy of the source code-folder:

My deploy.cmd file looks like this:
<code>@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

:: ----------------------
:: KUDU Deployment Script
:: Version: 1.0.15
:: ----------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error
)

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

IF NOT DEFINED KUDU_SYNC_CMD (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)
goto Deployment

:: Utility Functions
:: -----------------

:SelectNodeVersion

IF DEFINED KUDU_SELECT_NODE_VERSION_CMD (
  :: The following are done only on Windows Azure Websites environment
  call %KUDU_SELECT_NODE_VERSION_CMD% "%DEPLOYMENT_SOURCE%" "%DEPLOYMENT_TARGET%" "%DEPLOYMENT_TEMP%"
  IF !ERRORLEVEL! NEQ 0 goto error

  IF EXIST "%DEPLOYMENT_TEMP%\__nodeVersion.tmp" (
    SET /p NODE_EXE=<"%DEPLOYMENT_TEMP%\__nodeVersion.tmp"
    IF !ERRORLEVEL! NEQ 0 goto error
  )

  IF EXIST "%DEPLOYMENT_TEMP%\__npmVersion.tmp" (
    SET /p NPM_JS_PATH=<"%DEPLOYMENT_TEMP%\__npmVersion.tmp"
    IF !ERRORLEVEL! NEQ 0 goto error
  )

  IF NOT DEFINED NODE_EXE (
    SET NODE_EXE=node
  )

  SET NPM_CMD="!NODE_EXE!" "!NPM_JS_PATH!"
) ELSE (
  SET NPM_CMD=npm
  SET NODE_EXE=node
)

goto :EOF

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------

:Deployment
echo Handling node.js deployment.

:: 1. KuduSync
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_SOURCE%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
  IF !ERRORLEVEL! NEQ 0 goto error
)

:: 2. Select node version
call :SelectNodeVersion

:: 3. Install npm packages
IF EXIST "%DEPLOYMENT_TARGET%\package.json" (
  pushd "%DEPLOYMENT_TARGET%"
  call :ExecuteCmd !NPM_CMD! install ::--production
  IF !ERRORLEVEL! NEQ 0 goto error
  popd
)

echo Handling Angular build
  ::4. Build ng app
 IF EXIST "%DEPLOYMENT_TARGET%\package.json" (
      pushd "%DEPLOYMENT_TARGET%"
      call :ExecuteCmd "!NODE_EXE!" ./node_modules/@angular/cli/bin/ng build --prod --env=prod --aot
      :: the next line is optional to fix 404 error see section #8
      call :ExecuteCmd cp "%DEPLOYMENT_TARGET%"/web.config "%DEPLOYMENT_TARGET%"/dist/
      IF !ERRORLEVEL! NEQ 0 goto error
      popd
    )

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.
</code>
Answer: Ok, so I found the problem :) A typo in the deploy.cmd file. Changed:
<code>:: 3. Install npm packages
IF EXIST "%DEPLOYMENT_TARGET%\package.json" (
  pushd "%DEPLOYMENT_TARGET%"
  call :ExecuteCmd !NPM_CMD! install ::--production
  IF !ERRORLEVEL! NEQ 0 goto error
  popd
)
</code>
to:
<code>:: 3. Install npm packages
IF EXIST "%DEPLOYMENT_TARGET%\package.json" (
  pushd "%DEPLOYMENT_TARGET%"
  call :ExecuteCmd !NPM_CMD! install
  IF !ERRORLEVEL! NEQ 0 goto error
  popd
)
</code>
And everything works like a charm :D

Deploying Angular 2 app to Azure


FacesException: DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled

Question: I am trying to learn PF so I started with displaying datatable first and navigating to next page on rowClick passing parameters, but got stuck with the following error. I found similar problem for that question but no luck yet. I hope somebody will help me out.
I am getting following error:
DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled.

Caused by:
javax.faces.FacesException - DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled.

my Page:
 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<h:head>
<title>Primefaces 3.1</title>

</h:head>
<h:body>
    <h:form id="form">

  <f:facet name="header">
                                <h:outputText styleClass="outputText" value="Model"></h:outputText>
                            </f:facet>
                            <h:outputText styleClass="outputText"
                                value="#{var.model}"></h:outputText>

                            <f:facet name="header">
                                <h:outputText styleClass="outputText" value="Color"></h:outputText>
                            </f:facet>
                            <h:outputText styleClass="outputText"
                                value="#{var.randomColor}"></h:outputText>

        </h:form>
</h:body>

my bean Classes:
@ManagedBean
@ViewScoped
public class TableBean extends ListDataModel<Car> implements SelectableDataModel<Car>{

    private List<Car> cars;
    private Car car;

    public List<Car> getCars() {

        cars = new ArrayList<Car>();
        Car car1 = new Car();
        car1.setModel("BMW");
        car1.setRandomColor("Black");
        cars.add(car1);
        Car car2 = new Car();
        car2.setModel("Audi");
        car2.setRandomColor("White");
        cars.add(car2);

        return cars;
    }

    public String onRowSelect(){
        System.out.println("Row Click!!!");
        return "otherpage";//Does this nav works???if not how???
    }

    public Car getCar() {
        return car;
    }

    @Override
    public Car getRowData(String pArg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object getRowKey(Car pArg0) {
        // TODO Auto-generated method stub
        return null;
    }
    }

OtherBean:
public class Car{

    private String model;
    private String randomColor;

    public String getRandomColor() {
        return randomColor;
    }
    public void setRandomColor(String pRandomColor) {
        randomColor = pRandomColor;
    }

    public String getModel() {
        return model;
    }
    public void setModel(String pModel) {
        model = pModel;
    }

}

Answer: The #{tableBean.cars} must implement SelectableDataModel if you don't specify the rowKey attribute on the
.
You have however implemented it on the #{tableBean} instead. This is not right. You can find correct examples in the PrimeFaces showcase. Basically, your TableBean class must look like this according to the showcase code example:
@ManagedBean
@ViewScoped
public class TableBean implements Serializable {

    private List<Car> cars;
    private Car car;
    private CarDataModel carsModel;

    public TableBean() {
        cars = new ArrayList<Car>();
        // Populate cars here and thus NOT in the getter method!
        carsModel = new CarDataModel(cars);
    }

    // ...
}

Where the CarDataModel look like this (again, just copied from PrimeFaces showcase code example):
public class CarDataModel extends ListDataModel<Car> implements SelectableDataModel<Car> {

    public CarDataModel() {
    }

    public CarDataModel(List<Car> data) {
        super(data);
    }

    @Override
    public Car getRowData(String rowKey) {
        List<Car> cars = (List<Car>) getWrappedData();

        for(Car car : cars) {
            if(car.getModel().equals(rowKey))
                return car;
        }

        return null;
    }

    @Override
    public Object getRowKey(Car car) {
        return car.getModel();
    }

}

Finally use #{tableBean.carsModel} instead of #{tableBean.cars} as value of
. Exactly as in the showcase example.

Another, easier, way is to just specify the rowKey attribute on the
.

This way you don't need the whole SelectableDataModel. You only need to ensure that it's never null and always unique across the rows. See also DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled, but I have already defined rowKey.
Comment: Note that you may still get the same error even though you may have defined a rowKey attribute **if** the said attribute returns null (e.g. it's not initialized).
Comment: Thanks for the comment, BalusC, I have couple of questions, what is the use of rowKey? Is it for the unique value for the column of the table being displayed? What if I have lets say 2 primary key in the same table. Another question is, What do you mean by if I use rowKey I dont have to implement CarDataModel, can you explain little bit...and also can you put some light on what selection attribute does in .
Comment: The `rowKey` basically tells PrimeFaces what the unique identifier is of the row. The `selection` basically tells PrimeFaces where it has to get/set the references of selected rows. The point of `SelectableDataModel` is to be able to identify unique rows based on other criteria than what is already available by the row object itself (for which you would need `rowKey`).
Comment: What we do if there are 2 primary keys, what we do in such scenario?
Comment: Either use a composite key or create a `SelectableDataModel`.
Comment: For a unique object identity `rowKey="#{car.hashCode()}"` would be ok? Depends on your `hashCode()` and `equals()` implementation of course, but if not overwritten it is unique for each instance.
Comment: @opfau: hashcode doesn't per definition represent identity of the class' instance (multiple different instances can have same hashcode, you see, `int` has a hard limit in available values), but equals does (and does not force a limit anywhere).
Comment: Indeed that's not a good idea even the `hashCode()` implementation depends on the JVM.
Answer: Ensure to set the rowKey parameter in the bean method that populates the "value=.." of the datatable. Mine returned this error because the rowKey was null.
Answer: It worked for my project using a composite key for rowkey e.g.: rowKey="#{course.getCompositeKey()
Since I didn't have a compositeKey variable I simply created one in my Course Class (in your case the Car Class). The 2 primary keys are strings so I just said this.compositeKey=this.courseNumber+this.product--you just use whatever 2 primary keys are in your Car class instead of courseNumber and product.
Answer: Youd on't have to implement the datamodal in your managedbean, just  specify in the proprety of the datatable   the   "rowkey"    like this:   rowkey="{mbean.atribute1}"
-- atribute1 must be diplayed in the data table column.
Must
Comment: The rowkey param is *not* required to be displayed as a column in the data table.


Question in derivation of formulae for sum to $n $ terms of a series

Question: I have been learning that the sum of the squares of the first $n $ natural numbers is given by $$\Sigma= \frac {1}{6} n (n+1)(2n+1) $$ while the sum of the cubes of the first  $n $ natural numbers is given by: $$\left[ \dfrac {n (n+1)}{2} \right] ^2$$ I know that these can be verified by induction process, but can anyone explain how these were derived for the first time, and how similar formulae are derived? In derivation, one cannot use mathematical induction, so which process is used to derive such formulae?
Simply said, can anyone show how these formulae are derived, and not verified?
Comment: I'm not sure if this is what your looking for, but one answer is that taking the sum of the first $n$ squares is an approximation for the area under $x^2$, so it makes some sense that the answer looks like $n^3$.
Comment: I've edited the question. Please see the last part.
Comment: You could try finite differences: you wish to fit a quadratic to the sequence $(1, 5, 14, 30, \ldots )$. Take second differences and try to find the formula.
Answer: You can use: $\sum_{k=0}^{n} k^{3} = \sum_{k=0}^{n} (k+1)^{3}- (n+1)^{3}$, expand the sum and see that o term cubic cancel and you have a sum in function of $\sum k$. You can use this metod for sum of $k^{4}$ ... etc.
Answer: $\sum_\limits{i=1}^n i^k$
One way to do this is to assume that there exists a polynomial in terms of $n$ that equals the series.
And then $p(n+1) - p(n) = (n+1)^k$ and $p(1)= 1$ allows you to solve for the coefficients.
This is basically the same algebra of the induction proof.
An alternative is to construct a telescoping series.  e.g.
$\sum_\limits{i=1}^n i^{3}-(i-1)^{3} = n^3$
Multiplying it out gives.
$\sum_\limits{i=1}^n (3i^2 - 3i +1) = n^3$
$\sum_\limits{i=1}^n i^2 = $$\frac 13 n^3 +  \sum_\limits{i=1}^n i - \frac 13 \sum_\limits{i=1}^n 1\\
\frac 13 n^3 +  \frac 12(n)(n+1) - \frac 13 n\\$
And then there are some elegant "proof without words" proofs.  Which again give nice poofs that these series sum to what they claim to sum to, but are probably not the best starting points.


If i apt-get install ksh does it replace the default shell or only install it as an interpreter?

Question: I'm getting the error:
bash: ./fw_utils: /bin/ksh: bad interpreter: No such file or directory
If i apt-get install ksh does it replace the default show or only install it as an interpreter?
If it does install it as the default how do I switch the default back to bash?
Answer: I just checked it on my Debian box and it does not change the default shell for existing or newly added users. Existing user's shells are stored in /etc/passwd and can be changed with the chsh command. The default shell for new users is stored (in Debian) in in /etc/adduser.conf. Apt getting ksh did not alter either of these.
Comment: It does, however, add it to `/etc/shells` so it is ready to be used as a shell.


Java system.load() in a while loop

Question: int d = 0;

while( d < 5 ) {
    System.load(PATH-OF-THE-DLL-IN-HERE.DLL(returned_by_another_function_as_string));
    d++;
}

Trying to load a msgbox DLL multiple times. The above code works fine but i have 2 questions on it. 1) Why System.load() loads it only once and then exits? 2) Why the JAR is still running until i close the msgbox?
Any way to avoid those issues? For example, to load the same msgbox DLL 5-6 times with system.load?
Comment: A DLL is a library, with some functions stored in it. You don't need to load it multiple times. Load it one time, and call 5 times the same function
Comment: Why do you want to load a DLL multiple times? What are you trying to accomplish?
Comment: I'm trying to accomplish the DLL execution more than once by using system.load(). No funcy projects.
Comment: I know what a DLL is :) i wrote the DLL i'm calling. I just want to call it multiple times.
Comment: So call it multiple times. That doesn't mean you have to load it multiple times. Java won't let you do that, and neither will the operating system. Subsequent loads just increment usage counts.
Answer:
1) Why System.load() loads it only once and then exits?

Because that's the way it should work, it doesn't have sense loading the same library more than once (why would you want to have the same program instructions more than once spending memory?) System.load() calls Runtime.getRuntime().load0() internally, which calls ClassLoader.loadLibrary0(), which validates wether the library has already been loaded, if so, then just return.

2) Why the JAR is still running until I close the msgbox?

because the native code hasn't finish its execution. The JVM won't finish until all its non-daemon threads have finished.
I'm just guessing, but I think you're showing that msgbox int the dll's entry point function. If that's the case, instead of this you should show your msgbox in a native function that you can call multiple times so you can have your 5 msgboxes.

Java system.load() in a while loop


PowerPoint command like insert slide or apply theme equivalent on Office javascript API

Question: I'm developing a PowerPoint add-in and in future, it will be publish in Office Store. But it is VSTO project (C# and winforms) which could not be publish. Based on my search, it must be Office Web Add-in project (manifest xml and web pages).
I'm trying to convert my development from VSTO to Office Web Add-in but some of functionalities like open presentation, insert slide and apply theme aren't found on the Office.js.
Is there equivalent functions in Office.js? or other way?
Hopefully someone share their ideas about it. Thanks in Advance.
Comment: Check the section devoted to Office Javascript:  http://stackoverflow.com/questions/tagged/office-js
Comment: I checked it. So far, maybe Microsoft is currently working the API for PowerPoint. Thanks a lot Steve.
Comment: Yes, the javascript API is a work in progress, especially so for PPT, which is one of the last Office apps to get this technology.
Answer: This is currently no way to execute these actions (insert slide, apply theme, open document) in PowerPoint using Web Add-ins. PowerPoint currently only leverages a limited set of APIs.


URL field in Webforms

Question: I see only e-mail and textfield, but no URL.
How can I add to my form URL field with the validation rules for URL? e.g.
http://somesite.com

or
somesite.com

or
www.somesite.com

?
Answer: Well if you have tons of time you could implement a component type... but because that is unlikely you should just add a validation hook and a textfield to the webform. You could do a valid_url($form_state['values'][[your_field_name']); in your validation hook.
Someone asked this question on d.o previously here. You can find all sorts of examples on "things you may need to do special with a webform" here.
Another possible solution would be to install the Webform Validation module, add a regex validation to your field, and steal a known usable url validation regex like drupal has.
Comment: Any idea why this is not one of the default options (textfield, e-mail, date...) in the list of Webform option for fields? I mean you need to add URl in a form a lot of times. The question like e.g. "What is your website URL?" seems to be in the forms imho often. Or?
Comment: Because someone hasn't implemented a webform link component, or you and myself cannot find one. See here http://drupal.org/node/1660144
Comment: Anyway thanks, I will try webform validation and let you know if it works.
Answer: There is a module called webform_link that could also help you.

This module verifies that a valid URL is entered and displays the
  result as a link.

URL field in Webforms


Prove that $xRy \iff 5 |(x+4y)$ is an equivalence relation

Question:
Prove that $xRy \iff 5 |(x+4y)$ is an equivalence relation.

Reflexive: $xRx$, since $x+4x = 5x$, which is a multiple of $5$.
Transitive: Suppose $xRy$ and $yRz$. Then $$x+4y=5k_1,\quad y+4z = 5k_2.$$
After adding the two and some algebraic manipulation we obtain $$x+4z = 5(k_1+k_2-y)$$ thus $xRz$.
Symmetric: Suppose $xRy$. I need to show that $yRx$. I am having trouble showing this, however. Can anyone please help me?
Comment: Hint: What is $(x+4y)+(y+4x)$?
Answer: Note that
$$
x+4y = x + (5-1)y = 5y + (x-y),
$$
so $xRy \iff 5|(x-y)$. I assume you're working in $\Bbb Z$, all integers — positive, negative and $0$. If $n|m$ then $n|(-m)$, so if $5|(x-y)$ then $5|(y-x)$.
Answer: We will assume $xRy$. So, this means that there is some integer $k$ such that $x+4y = 5k$. This implies that we can write $x = 5k - 4y$.
This means that $4x + y = 4(5k - 4y) + y = 20k - 15y = 5(4k-3y).$
Hence $4x+y = 5(4k-3y),$ which is clearly divisible by $5.$ We conclude $yRx.$


EC2 Classic Link - Determine Classic IP Range

Question: So, I am working to migrate from EC2 Classic to VPC (yeah, I know, long time in coming and this was an inherited platform).
I have created a VPC and when I go to turn on Classic Link, I get the following error:
The CIDR range of vpc-[id_here] overlaps with the Classic IP space

I looked and was not able to find a way to determine which IP Range(s) Classic uses. Is there a way to find out so I can make my VPC's not stomp all over it?
Thanks!
Answer: 10.0.0.0/8 as documented here.
Comment: Thanks, but a little more detail would be nice:

"VPCs that are in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges can be enabled for ClassicLink only if they do not have any existing static routes in route tables in the 10.0.0.0/8 IP address range, excluding the local routes that were automatically added when the VPC was created. Similarly, if you've enabled a VPC for ClassicLink, you may not be able to add any more specific routes to your route tables within the 10.0.0.0/8 IP address range."
Answer: As in the comment above:

"VPCs that are in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges can be enabled for ClassicLink


How to use ExifTool by Phil Harvey to adjust all photos in a folder by 1 second for the first file, 2 seconds for second, etc

Question: I'm a photographer by trade, not a programmer. I'm having trouble understanding the instructions on exiftool.org for how to adjust the time. I want to adjust the first photo up by one second, the second photo up by two seconds, third photo by three seconds, etc...
It's a long story, but all the photos in one particular album all show as if they were captured at the exact same second. Their filenames are in order, but I need their capture time to be different or else Apple Photos will display them in random order.
Below is what I've already got.
number=1
capture_date="2022:10:21 15:43:${number} +01:00"

for photo in /Users/zed/Desktop/Louvre/*
    do exiftool -xmp:dateTimeOriginal=$capture_date $photo
    declare -i number+=1
done

Comment: You do not want to loop exiftool.  Instead, you should use exiftool's built in batch capability.  Exiftool's biggest performance hit is the startup time and looping once for each file will extend the processing time tremendously.  See [Common Mistake #3](https://exiftool.org/mistakes.html#M3).
Comment: In what shell? E.g., `for p in *.png; do echo $number; ((number=$number+1)); done` will inc the number in bash and zsh. The `capture_date` will need to be rebuilt on each iteration; I'd just put it inline w/ the `exiftool` command.
Comment: @DaveNewton I was attempting to write it in bash.
Comment: Do you mean you want to adjust by 1, 2, 3 seconds relative to their existing time? Or you want to adjust them to be 1s later relative to the previous image? If the first two images were taken 10s apart, they'll end up 11s apart with the former and 1s apart with the latter.
Comment: See [this Photo.StackExchange answer](https://photo.stackexchange.com/a/60403/37960)
Answer: Using this methodology you'll want something close to this:
number=1

for p in /Users/Dave/Desktop/*.png; do
  newTime="2022:10:21 15:43:${number}"
  exiftool -AllDates="$newTime" -DateTimeOriginal="$newTime" "$p"
  ((number=$number+1))
done

You'll want to test this with a subset of copies.

-AllDates wasn't setting DateTimeOriginal for some of my images (from a specific app) so I set both. The filename is quoted because I had images w/ spaces in the filename.
AFAICT exiftool can do this "internally" without needing a shell script at all, e.g., see https://exiftool.org/forum/index.php?topic=7682.0 and similar, but I don't have a convenient set of photos to test on (and never used exiftool, but may in the future, so thanks :)


cannot connect to postfix on 587

Question: I spent a lot of time searching for answers on related posts here, but to no avail. So that's why I am asking this question here.

I have: Debian 8, Postfix, Dovecot
I can send and receive emails with roundcube.
I can receive emails with thunderbird.
I cannot send emails with thunderbird.
Thunderbird says it connects to the server, but it times out because there is no response from the server.
I disabled my firewall.
I am not sure what to fill out in the server
name field.
The emails I am trying to send end up in the concepts box on the server

I followed https://workaround.org/ispmail/jessie
This is my current config.
config_directory = /etc/postfix
inet_interfaces = all
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
milter_default_action = accept
milter_protocol = 2
mydestination = server.example.com, localhost.example.com, localhost
myhostname = server.example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
non_smtpd_milters = local:/opendkim/opendkim.sock
policyd-spf_time_limit = 3600
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_sasl_auth_enable = yes
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_milters = local:/opendkim/opendkim.sock
smtpd_recipient_restrictions = reject_unauth_destination, check_policy_service unix:private/policyd-spf, permit_sasl_authenticated, permit_mynetworks
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/.ssl/mail_example_com_bundle.crt
smtpd_tls_key_file = /etc/.ssl/mail_example_com.key
smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_transport = lmtp:unix:private/dovecot-lmtp
root@server:/etc/dovecot/conf.d# clear
root@server:/etc/dovecot/conf.d# postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
inet_interfaces = all
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
milter_default_action = accept
milter_protocol = 2
mydestination = server.example.com, localhost.example.com, localhost
myhostname = server.example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
non_smtpd_milters = local:/opendkim/opendkim.sock
policyd-spf_time_limit = 3600
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_sasl_auth_enable = yes
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_milters = local:/opendkim/opendkim.sock
smtpd_recipient_restrictions = reject_unauth_destination, check_policy_service unix:private/policyd-spf, permit_sasl_authenticated, permit_mynetworks
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/.ssl/mail_example_com_bundle.crt
smtpd_tls_key_file = /etc/.ssl/mail_example_com.key
smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_transport = lmtp:unix:private/dovecot-lmtp

postconf | grep smtpd_sasl_auth_enable:
smtpd_sasl_auth_enable = yes

postconf | grep smtp_sasl_auth_enable:
smtp_sasl_auth_enable = yes

when I connect using telnet to port 25 I get the following response from ehlo
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN

AUTH is not enabled. Why?
When I try connect using telnet on 587 I see a blank screen.
I have no clue. Hope someone here does.
Thanks a lot.
Comment: look for error messages in /var/log/mail.log
Comment: that is a good suggestion. it got me this: fatal: invalid "-o smtp_sasl_auth_enable" option value: missing '=' after attribute name.. I got spaces there... this solved the issue indeed
Comment: I can successfully connect, but still not send. Relay access denied. So I guess something else needs tweeking as well. @cstamas Also still not getting AUTH in my telnet when I connect to 587.
Answer: You need to tell to postfix to listen to the submission port. Look in master.cf, usually under /etc/postfix, and uncomment the line:
submission inet n       -       -       -       -       smtpd

Also, check the firewall(s) settings to be sure the port 587 is reachable from your client.
Comment: That's right. I already have this in the master.cf: \n `submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtp_sasl_auth_enable = yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject`
Comment: also for your reference I include the scan of ports: PORT     STATE SERVICE
21/tcp   open  ftp
22/tcp   open  ssh
25/tcp   open  smtp
80/tcp   open  http
110/tcp  open  pop3
111/tcp  open  rpcbind
143/tcp  open  imap
443/tcp  open  https
465/tcp  open  smtps
587/tcp  open  submission
993/tcp  open  imaps
995/tcp  open  pop3s
8080/tcp open  http-proxy
Comment: I am having a new situation: I can now connect, but mails are not sent, most likely because of: `postfix/smtp[4793]: fatal: specify a password table via the 'smtp_sasl_password_maps' configuration parameter
`
Comment: finally I had to remove: `smtp_sasl_auth_enable = yes
` from the main.cf. It works fine now. Thank you all!
Answer: For submission this is something you should have in master.cf
submission inet n       -       -       -       -       smtpd
 -o syslog_name=postfix/submission
 -o smtpd_tls_security_level=encrypt
 -o smtpd_sasl_auth_enable=yes
 -o smtpd_client_restrictions=permit_sasl_authenticated,reject
 -o milter_macro_daemon_name=ORIGINATING

Answer: @cstamas ' suggestion was a good one. I noticed having spaces around the = in smtp_sasl_auth_enable = yes that should be  smtp_sasl_auth_enable=yes then the first problem is solved.
after that I got an error 'Relay access denied', which was solved by adding:
  -o smtpd_recipient_restrictions=permit_sasl_authenticated

in the /etc/postfix/master.cf
Then I also had an error in the client configuration. I should use a server name that has a valid certificate installed, so the client can verify the servers identity.
Comment: also see my other answer below. There is a reason this is the debian default configuration file. e.g: it does enable authentication for the submission port only and ensures tls encryption.

cannot connect to postfix on 587


Longest Version 4 GUID

Question: What is the longest (printed length) version 4 GUID/UUID when displayed in a non-fixed-width font? (obviously in a monospace font all guids look the same length)
For instance, I want to size a table cell that will hold a GUID, and I want it to be slightly larger than the largest possible value.
Answer: After a lot of testing of which character shows up the longest, I discovered that:
<code>dddddddd-dddd-4ddd-bddd-dddddddddddd
</code>
Shows up the longest in both lowercase and uppercase.
The long answer is that it depends on the font, but in most "normal" fonts (such as Arial, Helvetica, Calibri, etc.), D tends to be the longest character (or a very close second) in both upper and lower cases.

Longest Version 4 GUID


Passar data de JSP para Servlet

Question: Tenho um Datepicker bootstrap conforme abaixo, e tenho um botão que deve passar a data selecionada no datepicker para o Servlet que vai utilizar esta data como parâmetro para uma busca no mysql. Como posso passar esta data para o Servlet? Já tentei com vários exemplos que encontrei na web,mas sem sucesso.
Botão:

Datepicker:

                    <input type='text' class="form-control" id="d"/>

Comment: Você quer passar via AJAX?
Comment: Sim via ajax...
Comment: Você já deve ter criado o servlet, então basta que você envie a informação desejada para a url do servlet.

Lá no servlet você pode usar um request.getParameter
Comment: Sim já tenho o Servlet, mas não consigo passar esses parâmetro da data para ele.
Comment: Como está aquela função que você colocou ali no onclick?
Comment: Coloquei a função ali....
Answer: function UpdateGrafico(){

   document.getElementById("loading").style.display = "block";
       var queryObject="";
       var queryObjectLen="";
       var processed_json = new Array();
       var processed_temp = new Array();
    $j(function () {

                //---------------------

      $j.ajax({
     data: "",
     dataType: 'json',
     url: './GetValores',
     type: 'POST',
     success: function(data){

          queryObject = eval('(' + JSON.stringify(data) + ')');
          queryObjectLen = queryObject.jsonArray.length;

   for(var i=0; i < queryObjectLen;i++){

                    var corrente = queryObject.jsonArray[i].valorCorrente;
                    var id = +new Date(queryObject.jsonArray[i].pk);
                    var tmp = queryObject.jsonArray[i].temp;

                    processed_json.push([id, corrente]);
                    processed_temp.push([id,tmp]);

                }

                //alert(ini);
                //alert(fim);
               if(queryObjectLen === 0){
                    alert("Sem dados para o período pesquisado!");
                }

                //---------------------
                     Highcharts.setOptions({global: { useUTC: false } });
                    // draw chart

                    $j('#container').highcharts({

                    chart: {
                        type: "spline",
                        zoomType: 'x',
                        backgroundColor: '#d8f5ac'
                    },
                    title: {
                        text: "Current data"
                    },
                    xAxis: {
                        type: 'datetime',
                        // max :ini /** Date in timestamp for the end the day */,
                        // min : fim/** Date in timestamp for the beginning the day */,
                        //categories: 'datetime',

                        allowDecimals: true,
                        tickInterval: 3600 * 1000,
                        dateTimeLabelFormats: {
            day: '%d/%b '

        },

                        title: {
                            text: null
                        }

                    },
                    yAxis: {
                        title: {
                            text: "Value (A)"
                        }
                    },
                    plotOptions: {
            series: {
                turboThreshold: 0, //libera para plotar mais de 1000 pontos no chart

            }
        },

                    series: [{
                    name: 'Valor de corrente',
                        data: processed_json,
                        color: '#FF0000'
                    },{
                        name: 'Temperatura',
                        data: processed_temp
                    }

            ]

                });
             document.getElementById("loading").style.display = "none";//oculta div de loading
           //----------
            },

     error: function() {

       alert("Ocorreu um erro na requisição ajax");
     }
   });
           //----------

        });
    }

Passar data de JSP para Servlet


Find the fundamental error in the proof

Question: The proof provided has a "fundamental error" in it, but I can't figure out what the error is.

Statement: For all non-negative integers $n$, $n$ is even.
Proof: Let $P(n)$ be the open sentence: $n$ is even.
Base Case: We show that $P(0)$ is true. Since $0=2(0)$, then 0 is even and the statement is true for $n=0$
Inductive Hypothesis: We assume the $P(i)$ is true for $0\leq i\leq k$. That is, $i$ is even for all $i$ in the range $0 \leq i \leq k$ for some $k \in \mathbb Z$ for $k \geq 0$.
Inductive Conclusion: We show that $P(k+1)$ is true. Conside $k+1$. Since $k+1 = k-1+2$ and since $0 \leq k-1 \leq k$, the by the inductive hypothesis, $k-1$ is even and 2 is even. The sum of two even numbers is even, and thus $k+1$ is even as required.

Obviously this is not true, and I have an idea as to the error, but I'm not 100% sure. I think it has something to do with the fact that they are using the strong induction method in the hypothesis, but have only provided 1 base case. Other than that, I can't see anything wrong with the actual proof method (but the proof is obviously wrong).
Comment: The error here is that you are assuming that $P(i)$ is true for all $0 \leq i \leq k$, and by the inductive step $k+1$ you are using that it is true not 'only' for $k$, which is the previous one, but for $k-1$, which is $2$ steps below. Hence, if you actually wanted to prove that this is true for all $k$, you should include in your base case $k=1$, which is obviously not true.
Comment: To show $P(1)=P(0+1)$ we write $1=-1+2.$ But we have not shown that $-1$ is even. Indeed, it isn't. Here is where the proof fails.
Comment: The Induction Step proof is wrong: we have that $P(0)$ holds but clearly $P(1)$ does not. Thus, it is **not** true that $P(k) \to P(k+1)$ holds for every $k$.
Comment: For $k=0$ the "calculation" based on $k-1$ will fail, because $k-1=-1$.
Answer: The problem is going from 0 to 1.
See if you can figure out why.
Answer: Let us rewrite the inductive step instantiated for $k=0$:

Inductive Conclusion: We show that $P(1)$ is true. Conside $1$. Since $1 = -1+2$ and since $0 \leq -1 \leq 0$, the by the inductive hypothesis, $-1$ is even and 2 is even. The sum of two even numbers is even, and thus $1$ is even as required.
Comment: What do you mean by $0\le -1\le 0?$
Comment: @mfl: I don't mean anything, I just made a formal substitution. Are you aware of the goal ?

Find the fundamental error in the proof


Apachesolr searching is not working with cck field

Question: I am working in Drupal 6 website with apachesolr. I have added a cck field (text field) in a content type.
When I am searching the value of textfield, apachesolr showing empty result.
The field is indexed properly into apachesolr index.
How can I implement apachesolr searching for cck text field?
Answer: Once you add a CCK field then the CCK will not by default get indexed. You have to delete all the existing index and have to re-index all items. This is because, CCK fields are properties of all the documents (nodes) that goes to the SOLR index.
Once all the items are index then you can find those by sis_cck_field_* names where sis_* is a type of dynamic field provided by SOLR itself. You can find the CCK index status in admin/reports/apachesolr/index page or in SOLR admin (http://127.0.0.1:8983/solr/admin/schema.jsp) page.
EDIT -- 1
As mentioned, the field is indexed properly then try to search by the value of the CCK field in Apache Solr's admin search (http://localhost:8983/solr/admin/form.jsp). If you see the search results appear as per your desire then there may be a permission issue. If your field is called "field_example" then in permission page check whether "view field_example" is checked for desired roles.
Edit -- 2
In that case I think the cck field is not at all being indexed. I had the same problem once with CCk fields that stores "multiple" values. In that case what I had to do is to create a new field in SOLR index and index the item again. This may solve your problem but may not be a proper way. However you will find this way is excepted in Drupal also in this link.
You have 2 ways to achieve this.

Append the item in the body field in time of content indexing hook.
Add a new dynamic field to the document object while indexing and fetch the field while searching.

For the 1st one,
function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  $document->body .= ' '. $node->field_MY_CCK_FIELD[0]['view'];
}

For the 2nd one,
function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  // For multiple values.
  foreach ($array as $value) {
    $document->setMultiValue('sm_multiple_value', $value);
  }
  // For text field.
  $document->addField('ts_element_name', $value);
}

And while searching,
function MYMODULE_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',ts_element_name'; //Add the field name to the select query.
}

Comment: Field is indexed properly into apache solr.
Comment: An edit added to the answer, check and let me know Jayendra.
Comment: I have checked solr admin and use select query and found that there is no data for field but its showing field in `admin/reports/apachesolr`.
Comment: I see, have a look at the edit #2. Hope this will be helpful for you.


Testing data for Same Shape

Question: I want to run a Mann-Whitney test on  2 arbitrary sets of data but I read that one of the assumptions of the Mann-Whitney test is that the data is the same shape. How can I test if the 2 sets of data are the same shape?
I'm automating a test on Python so a link to a relevant python package would help. I would also like to know if there is no straightforward way of doing this thanks.
Comment: Look at a QQ plot of the datasets.
Answer: The test does not require the assumption that the data has the same shape. Without any assumptions, Mann-Whitney tests if the distribution of $X$ and $Y$ are the same:
$$H_0: F_x = F_y, H_1:F_x \neq F_y. $$
In order to test equality of medians the following assumption is required.
There is only a shift location between the two distributions, $F_X(x) = F_Y(x + \delta)$ under $H_1$.
To check for this assumption you can look at the difference between the quantiles they should all be around $\delta$, it can be done visually using qq-plot.
If the assumption does not hold, the test is no longer valid (p-value under the null will be stochastically smaller than uniform).
Example:
We compare two samples sampled from Normal distribution $X \sim N(0, 1)$ and $Y \sim N(0, 10^2)$, at each iteration we apply the Mann-Whitney test and save the p-value. Finally, we inspect the p-value distribution.
<code>pvals <- rep(NA, 1000)
for (i in 1:1000) {
  x <- rnorm(30, 0, 1)
  y <- rnorm(30, 0, 10)

  pvals[i] <- wilcox.test(x, y)$p.value
}

qqplot(pvals, qunif(ppoints(500)), type = 'l')
abline(a = 0, b = 1, col = 'red', lwd = 2)
</code>

As can be seen the two distribution are different, but have the same median. IF the we test equality of medians the test is not valid, however if we are testing equality of distributions it is. However, it has very low power in this specific scenario. It is better used to detect differences between distribution where one is stochastically larger / smaller than the other.

Testing data for Same Shape


Standard deviation for weighted sum of normal distributions

Question: I have 2 normally distributed random variable $H_0$ and $H_1$, which are combined to give the weighted distribution $H$ as follows:
$H_0 \sim N(\mu_0, \sigma_0)$
$H_1 \sim N(\mu_1, \sigma_1)$
$$f_H = p * f_1(x) + (1-p) * f_0(x),$$
where $H$ has pdf $f_H$ and $H_1$ and $H_0$ have pdfs $f_1$ and $f_0$ respectively.
The mean value $\mu$ of the combined distribution $H$ is:
$\mu = p * \mu_1 + (1-p) * \mu_0$
Now, what is the standard deviation $\sigma$ of $H$?
Is there a simple formula for $\sigma$, in terms of $p, \mu_0, \sigma_0, \mu_1, \sigma_1$?
Comment: See the relevant part of the [mixture distribution page](https://en.wikipedia.org/wiki/Mixture_distribution#Moments) at wikipedia; also can be found here on CV, e.g. [here](http://stats.stackexchange.com/questions/128912/possible-to-morph-a-bimodal-distribution-into-a-normal-distribution-slowly/129007#129007)
Answer: (I am assuming $H_1$ and $H_0$ are independent)
Let $f_H = pf_1 + (1-p)f_0$, where $f_1$ and $f_0$ are pdfs of $H_1$ and $H_0$. Then the random variable $H$ is the mixture of two normal distributions. For the mean of $H$
$$E(H) = \int x\left(pf_1(x) + (1-p)f_0(x) \right) dx = p\mu_1 + (1-p)\mu_0. $$
Similarly for the second moment of H
\begin{align*}
E(H^2)& = \int x^2 \left(pf_1(x) + (1-p)f_0(x) \right) dx\\
& = pE(H_1^2) + (1-p)E(H_0^2)\\
& = p(\sigma_1^2 + \mu_1^2) + (1-p)(\sigma_0^2 + \mu_0^2)
\end{align*}
Finally,
\begin{align*}
Var(H) & = E(H^2) - [E(H)]^2\\
& = p(\sigma_1^2 + \mu_1^2) + (1-p)(\sigma_0^2 + \mu_0^2) - \left[p\mu_1 + (1-p)\mu_0 \right]^2\\
& = \left[p\sigma_1^2 + (1-p)\sigma_0^2\right] + [p\mu_1^2 + (1-p)\mu_0^2]- \left[p\mu_1 + (1-p)\mu_0 \right]^2\\
& = p\sigma^2_1+(1−p)\sigma^2_0+p(1−p)(\mu_1−\mu_0)^2
\end{align*}
Taking the square root of $Var(H)$, you get the standard deviation.
Comment: I have fixed the solution now.
Comment: Yes, I believe you are correct.
Comment: But why does $\sigma$ not depend on $\mu_0$ and $\mu_1$, and the difference between them?  Surely $\sigma$ will be greater if the two means are further apart, no?
Comment: @Kelvin you are adding two normally distributed (independent) random variables, which is different from a mixture of Normally distributed random variables.
Comment: For example, if $\mu_0$ and $\mu_1$ were very different, but $\sigma_0$ and $\sigma_1$ were both zero, the combined standard deviation $\sigma$ would not be zero, would it?  Something is not right here...
Comment: @Kelvin I may have misread your question, then. It seems like you are talking about a mixture of two normal distributions.
Comment: OK, thanks @Greenparker, then I guess I am looking for a weighted mixture rather than a weighted sum.  Sorry if that was not clear, I wasn't aware there was a difference.  But my formula for the weighted mean is still correct, right?
Comment: Perhaps I should substitute $\phi$ for $N$ in the question to clarify?
Comment: @Greenparker - thank you.  Am I right that your formula for variance simplifies to: $[p\sigma_1^2+(1-p)\sigma_0^2+p(1-p)(\mu_1-\mu_0)^2]$?
Comment: OK, thanks.  Perhaps you could add this for reference to the end of your answer, and I'll accept as correct.
Comment: I left it unsolved, since I wasn't sure if this was a homework problem or not. I think my answer is complete as it stands.
Answer: Let $Z$ denote a Bernoulli random variable with parameter $p$. Then, the random variable $H$ can be thought of as having conditional density
$N(\mu_i, \sigma_i^2)$ according as $Z$ equals $i$, $i=0,1$, and thus
unconditional density
$$f_H(x) = pf_{H_1}(x) + (1-p)f_{H_0}(x).$$
The unconditional mean is thus the weighted sum of conditional means, viz.
$$\mu_H = p\mu_1 + (1-p)\mu_0$$
while the unconditional (or total) variance is given by the total variance formula:

mean of the conditional variance plus the variance of the conditional mean

The first quantity is clearly $p\sigma_1^2 + (1-p)\sigma_0^2$. On the
other hand, the conditional mean takes on value $\mu_1$ and $\mu_0$with
probabilities $p$ and $1-p$ respectively  and thus has variance
\begin{align}p\mu_1^2 + (1-p)\mu_0^2 - \left(p\mu_1 + (1-p)\mu_0\right)^2
&= (p-p^2)\mu_1^2 + (1-p-(1-p)^2)\mu_0^2 -2p(1-p)\mu_0\mu_1\\
&= p(1-p)(\mu_1-\mu_0)^2
\end{align}
Adding these two quantities together, we have that
$$\sigma_H^2 = p\sigma_1^2 + (1-p)\sigma_0^2
+ p(1-p)(\mu_1-\mu_0)^2$$
as in Greenparker's answer.


Spring3, JAXB2, Java6, NamespacePrefixMapper questions

Question: I built a simple Spring3, Hibernate3/(JPA2), RESTful service, hosted on Tomcat6, that uses JAXB2 to marshal the results.  (It uses annotated pojos.) I needed to use specific namespace prefixes, so I wrote a custom com.sun.xml.bind.marshaller.NamespacePrefixMapper.  I included the JAXB2 RI jars with my application and everything worked fine.
Then someone said that's great, we need to host it under WebLogic 11g (10.3.3) too.  No problem, I created the special weblogic deployment descriptors to prefer the application jars, renamed my persistence.xml, and wrapped the WAR in an EAR with the JPA2 jars.  It worked great, almost.
Unfortunately, our WebLogic server runs a custom security realm that also uses JAXB and causes conflicts with my application.  So I dropped the JAXB jars from the app and it runs fine in WebLogic. Of course it no longer runs under Tomcat unless I add the JAXB jars to Tomcat.  I'd like to avoid that.
So my questions... I've read quite a few posts on stackoverflow that contain a lot of opinions/disagreements regarding the use of the sun "internal" JAXB2 implementation vs. packaging the RI with your app.  Is there not yet a clean solution to this problem?  Does my stack support another way to custom map my namespace prefixes without including the JAXB2 RI?  Can I safely use the Java6 "internal" JAXB NamespacePrefixMapper, or will that come and go with various Java releases?  Does Spring3 offer another solution?  What's the true story on the Java6 JAXB2 implementation?  Is it only there for Sun's (Oracle's) internal use?
Thanks.
Comment: @skaffman:  Thanks, but I can't see http://www.func.nl/community/knowledgebase/customize-namespace-prefix-when-marshalling-jaxb from work.  (It's blocked.)  Can you give me the gist?  Does it avoid the NamespacePrefixMapper altogether?
Comment: JAXB 2.1 is included with JDK 6 since JDK 6 Update 4.  If the application server is running JDK 6, why do you need to add the JAXB2 RI jars to your application?
Comment: @Chin: When you use the RI, you can also safely use the `com.sun.xml` classes that come with it, like `NamespacePrefixMapper`. If you use the built-in Java6 JAXB, you have to use the `com.sun.xml.internal` packages, which is highly inadvisable.
Comment: @John: See the accepted answer to this question for a possible solution: http://stackoverflow.com/questions/1982977/is-it-possible-to-customize-the-namespace-prefix-that-jaxb-uses-when-marshalling
Comment: http://stackoverflow.com/questions/2326107/what-happened-to-jaxbs-namespaceprefixmapper-in-jdk6u18/2326480#2326480
Comment: @John: Ok, I've parroted it as an answer.
Comment: @Bozho:  Thanks. It's been nearly a year since you wrote: "there is no better way to do this, and this is an essential feature."  I hoped that by now, someone at "Sun" would have sorted this out.
Answer: As mentioned in the comments, I'll summarise what is mentioned in http://www.func.nl/community/knowledgebase/customize-namespace-prefix-when-marshalling-jaxb.
Note: I haven't tried this myself, so it may not work.
Essentially, you configure the JAXB marshaller to use an XMLStreamWriter when marshalling, and you configure that to map prefixes, e.g.
XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
xmlStreamWriter.setPrefix("func", "http://www.func.nl");

JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = context.createMarshaller();

marshaller.marshal(object, xmlStreamWriter);

The idea is that if JAXB hasn't been given a prefix mapper, then it'll leave it up to the XMLStreamWriter to handle the prefixes, and by doing the above, you're telling it how to do it.
Again: I'm just repeating the content from the website that's blocked from your network, so I take no credit for it being right, and no blame for it being wrong.
Comment: Thanks skaffman.  I hadn't tried the XMLStreamWriter.  It requires a lot more code than just "return myPojo;", but if it avoids including the JAXB2 RI or using "internal" packages it would at least let the same application run in both Tomcat and WebLogic.  I'd still like to know the answers to my questions.
Comment: @John: It was worth a try. It's not really a big problem, though, since namespace prefixes shouldn't matter. Cosmetics aside, anything that requires a specific prefix is kinda broken.
Comment: I tried this solution, but ran into some problems because it prevents the marshaller from defining the namespaces and prefixes in the opening document element.  So I got a friend to open the link and email me the contents of the entire post, and this solution also requires rolling a custom marshaller too.  (My friend hasn't sent the code to me yet.)  I really don't think this is what the creators had in mind.  But thank you so much for your efforts.
Comment: Does anyone from "Sun" or SpringSource ever participate in this forum?  This is a remarkable problem.  So far, I have a small collection of workaround hacks, but no proper solution.  Perhaps I can include the JAXB2 RI in my app, but somehow not cause a conflict with my security realm in WebLogic.
Comment: I completely agree that the prefixes should be completely arbitrary... in theory.  In practice unfortunately, they are not.  In my case, the difference between ns1, ns2,... and rdf, georss, etc... is the difference between IE, Firefox, and my client seeing an ordinary XML document and seeing an RSS feed.  Again, I appreciate the lead.
Answer: The EclipseLink JAXB (MOXy) will use the namespace prefixes as declared in the @XmlSchema annotation.
For more information see:

How to customize namespace prefixes on Jersey(JAX-WS)
Define Spring JAXB namespaces without using NamespacePrefixMapper


React How to get the current ref data by assigning values in the loop?

Question: Hooks for beginners. Thank you
How can I write to get the offsettop of each click
import React, { useRef } from 'react';
const node = useRef<HTMLDivElement>(null);
{Array.from({ length: 10 }).map((item, i) => (

 {
        // Every click is the value of the last item, not the value of the current click
        console.log(node.current?.offsetTop);
      }}
    >
      1111{i}

))}

Thank you thank you!!!
Comment: The current development environment is typescript react
Answer: you can access the offset like this
console.log(event.target.offsetTop);

Comment: I tried
But the vscode hint
Property 'offsettop' does not exist on type 'EventTarget'.

thank
Answer: const ele = event.target as HTMLElement;
console.log(ele.offsetTop);

Using type assertion solves the problem.
Thank you very much

React How to get the current ref data by assigning values in the loop？


Markov Chain with 7 sided polygon and 2 balls

Question: 7 men stand at the vertices of a 7-sided polygon and play a game with 2 balls. Initially (at time 0), the men at vertices A and D hold a ball each. The game ends when any man receives the two balls simultaneously. Before the game ends, and at times 1,2,..., any man holding exactly 1 ball throws it to his clockwise neighbour with probability a (where 0 < a < 1), or to his anti-clockwise neighbour with probability b (1 - a). All such actions are independent. The game can be modelled as a Markov chain by defining state k, k = 0,1,2,3, as the distance between the 2 balls, measured in number of sides covered by the shorter route around the polygon.

 The diagram is as shown:

(a) What is the transition probability matrix?
(b) Find all the classes of the Markov chain. Is there any closed class? Is there any recurrent class? State your reasons briefly.
(c) Find the expected number of times the 2 balls are held by two men who are neighbours of each other.

Attempt:

I have been working on this problem for hours and still cannot solve it.
I understand that part (a) requires me to compute the individual probability in the transition matrix. I got
$\begin{bmatrix}1 & 0 & 0 & 0\\0 & a^2 + b^2 + ab & 0 & ab
\\ab & 0 & a^2 + b^2 & ab\\0 & ab & ab & a^2 + b^2\end{bmatrix}$

Not sure if I got it correct, as I traced the states based on the diagram shown. The first row is all 0 because we do not want to throw any more balls in that state (game ends).
 For part (b), I believe that there are no closed or recurrent classes as since all states, one way or the other, are accessible from each other...
 For part (c), I am confused with the question, and would really appreciate any help.

Thanks guys!
Comment: sorry but what do you mean by when _k_ = 0, we should not throw any more balls from that state? because when _k_ = 0, i thought we can still return to state 0 when the balls move in the same direction
Comment: You are missing one $ab$ in each of the first two rows. The sum must equal $a^2+2ab+b^2=1$. Also, as the game ends when $k=0$ you may want to not throw any more balls from that state.
Comment: ahh yes, thanks @HagenvonEitzen I forgot to check that the row sums equate to 1
Comment: @HagenvonEitzen I get it now, thanks for your help!
Answer: (This answer solves the original version of the question, where $0$ is not an absorbing state. Later on, the transition matrix was modified, and $p(0,0)$ put to $1$. This modification was both unnecessary in the context of the actual mathematical question asked and inappropriate in a Q&A context since an answer was already posted at the time.)
There is only one communicating class since the path $0\to2\to3\to1\to3\to2\to0$ has positive probability and joins $0$ to $0$ passing through every state. Hence the Markov chain is irreducible. The unique class $\{0,1,2,3\}$ is obviously closed and recurrent. This is not asked but note that some loops $x\to x$ have positive probability hence the Markov chain is also aperiodic.
The Markov chain starts at $3$ and stops when hitting $0$. To compute the expected number of visits of $1$, define $n_x$ as the expected number of visits of $1$ before hitting $0$ starting at $x$. Then the usual one-step recursion reads $n_3=p(3,1)(1+n_1)+p(3,2)n_2+p(3,3)n_3$, $n_2=p(2,2)n_2+p(2,3)n_3$, and $n_1=p(1,1)(1+n_1)+p(1,3)n_3$, where each $p(x,y)$ denotes the transition probability from $x$ to $y$.
This $3\times3$ Cramér system yields $(n_1,n_2,n_3)$, and in particular $n_3$ the expected number of visits of $1$ before hitting $0$ when the Markov chain starts at $3$. (This value might be $n_3=2/(ab)$.)
Comment: Thanks @Did for your help. Since the game ends when k = 0, why do we still consider the path from 0 to 0? (the first row in the probability matrix would all consist of 0 then?)
Comment: The new matrix in your question is not a transition matrix. You could keep the old one and simply consider the process before the hitting time $T_0$ of $0$. Or consider that the transition $0\to0$ has probability $1$. Note that anyway, no $p(0,x)$ enters the computation of $n_3$.
Comment: `The first row is all 0` Not anymore, it seems.
Comment: thanks @Did for reminding that the transition probability matrix shouldn't have all 0s in the first row since row sums must equate to one. Regarding part (c), pardon me, but i still do not quite comprehend your methodology...
Comment: OK. Unless you explain what you fail to grasp, I can add nothing to this quite standard approach.
Comment: I understand the recursion bit about N3 = P31(1+N1) + P32(N2) + P33(N3), also for N2 and N1 (by taking conditional expectation). However, I am quite confused about the Cramer system, could you further explain this part please?
Comment: Forget Cramer. You have 3 linear equations with 3 unknowns, in general this allows to compute the 3 unknowns (and here this is so), in particular n3 that you want.
Comment: i see. how about the transition matrix, given that P(0,0) is 1, does that mean that there are 2 classes, {0} and {1,2,3}, instead of {0,1,2,3}?
Comment: See addition to my post.


Cover background image is not scaling properly?

Question: I'm trying to figure out exactly why my webkit cover background isn't scaling properly on some pages on my site.
The URL is http://www.finestgc.com/.  On the homepage, you can see that the cover background image is scaling properly, the issue lies on the other pages, such as: http://www.finestgc.com/general.html where you can see the image is scaling entirely too big.
Could a CSS/HTML expert help me determine the reason this is occurring?  Any suggestions would be appreciated.
Comment: That's because your other page is much bigger.
Comment: Why would it relate to the vertical height of the fixed width div?
Comment: That's the way that background-size:cover works which is applied to your body.
Comment: Gotcha. Is there any other way to do what I need, then?
Comment: I suppose one answer is have one very large image that could be used on even the largest of your pages. It would look normal on the largest and be scaled down on the smaller ones. Aside from that, perhaps background-size:cover isn't what you really want.
Answer: In your CSS file, change this:
body
{
    background: url('images/blueprint.png') #222 no-repeat;
    ....
}

to:
body
{
    background: url('images/blueprint.png') #222 no-repeat fixed;
    ...
}

Answer: In your second page http://www.finestgc.com/general.html
In CSS on body add this code

background-attachment:fixed;


Excluding part of a npm package from a claudia.js build

Question: I'm currently using claudia.js to deploy serverless functions to AWS Lambda. However, due to size limitations I run into the following error:

RequestEntityTooLargeException: Request must be smaller than 69905067 bytes for the CreateFunction operation

To resolve this, I'm trying to exclude a subfolder of a npm package as it's not needed, but I'm unsure how to do this during the claudia build process.
Specifically, I'd want to exclude an example subfolder > node_modules/packet/subfolder/*
I've messed around with various configurations of .gitignore and .npmignore but with little success. Any help would be amazing!
Answer: Instead of doing that you can simply use --use-s3-bucket option with Claudia.js and 50mb limit will be increased to 250mb (uncompressed).
Try running the following command:
claudia update --use-s3-bucket BUCKET_NAME --region YOUR_REGION
Where BUCKET_NAME is a name of the deployment helper bucket in the same region (YOUR_REGION).


Aging/oldify a dataset of pictures

Question: Old Photo Restoration via Deep Latent Space Translation (https://paperswithcode.com/paper/old-photo-restoration-via-deep-latent-space)
My team and I are interested in reproducing their work. However, the dataset is not provided to us. We need several hundred photos and people on them. We found the following dataset IMDB-WIKI – 500k+ face images with age and gender labels.

What is the best way to oldify that type of picture?
EDIT
Here is a way to "oldify" the pictures. Using OpenCV, I can convert these images to black and white (gray scaled) and then merge/ blend these images with different old pictures textures. For that see
Adding (blending) two images using OpenCV
. This technique seems well, but hard to apply to a large set of pictures. I would like to obtain something similar to above pictures.
Comment: Can you plese define *oldify*?
Comment: @kjetilbhalvorsen By oldify, I mean degrade a photo to look old. You can find some examples of picture in the article or directly in the question. It is hard to say, I would add stripes, old colors (e.g. white, black, gray), stains, etc.
Comment: OK, I thought maybe you meant making *the people in the photo* look old!
Comment: @kjetilbhalvorsen What do you suggest?
Answer: According to the paper, you can't.
Quoted directly from the paper:
"The
degradation process of old photos is rather complex, and
there exists no degradation model that can realistically
render the old photo artifact."
"No matter for unstructured or structured degradation,
though the above learning-based methods can achieve remarkable results, they are all trained on the synthetic data.
Therefore, their performance on the real dataset highly relies
on synthetic data quality. For real old images, since they
are often seriously degraded by a mixture of unknown
degradation, the underlying degradation process is much
more difficult to be accurately characterized. In other words,
the network trained on synthetic data only, will suffer from
the domain gap problem and perform badly on real old
photos"
"However, these
methods still rely on supervised learning from synthetic
data and hence cannot generalize to real photos."
"Old photos contain far more complex degradation that is hard to be modeled realistically and there always exists a domain gap between synthetic and real photos. As such, the network usually cannot generalize well to real photos by purely learning from synthetic data."
If this paper is to be believed, there is no known way to "oldify" a picture which will faithfully represent degradation in real photographs. A model trained on synthetic data may not apply well to real data.
Answer: I cannot comment on others' answers, so forgive me if it somewhat repeats what others said, but the paper does highlight a way to "oldify" the pictures, although they admit the process is impossible to recreate artificially.
Read section 4.2 (Data Generation) from the paper:

Unstructured Degradation
We  use  the  following  operations to simulate the unstructured degradation. >Specifically,

Gaussian white noise withσ∈(5,50).

Gaussian blur with kernel sizek⊂ {3,5,7}and stan-dard deviationσ∈(1.0,5.0);

JPEG compression whose quality level in the range of(40,100);

Color jitter which randomly shifts the RGB color chan-nels by(−20,20);

Box blur to mimic the lens defocus.

I have tried it myself, and the results are not too bad, but they hardly apply to pictures taken with actual film.
Here's an example:

Aging/oldify a dataset of pictures


input id reserved word

Question: I was about to answer a question here and found my self struggling with what seemed to be an easy thing to understand.
Consider this HTML:

<input type="text" id="width" value="foo" />
<input type="button" value="width.value" onclick="console.log(width.value)"/>
<input type="button" value="window.width.value" onclick="console.log(window.width.value)"/>

We have an input with an id of width and two buttons that has an onClick event that all it does is logging the input's value. The different between them is that one input accessing the input's id as a variable directly width.value and the other one is doing it via window.width.value.
The amazing part here is that only the window.width.value works and the other one returns undefined.
I've looked up javascript reserved key words but couldn't find anything about width, By the way it is the same with the height key word as well.
What am i missing?
Comment: This is all about scope. In your `width.value` you're accessing the button's width-attribute. `width.value == this.width.value` in this case.
Comment: Just about to say what @FrederikHansen said, your basically forgetting that INPUT's have attributes too,.. like width & height..
Answer: The onclick method is being called on the button objects.  Therefore, unless you specify that you want the window's width property, it will be shadowed by the button object's width property.  In this case, the button's width doesn't have a value property.
Comment: i can't believe i forgot about that! :)

input id reserved word


Validar um campo date em javascript para enviar para api no servidor

Question: Galera, bom dia.
Estou com um erro muito chato, estou tentando fazer um put de um formulário em vue.js, porém, quando envio as informações para o servidor que e em java, está quebrando uma exceção de data;
[2m[nio-8080-exec-2][0;39m [36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Invalid JSON input: Cannot deserialize value of type `java.util.Date` from String "27-02-2014": not a valid representation (error: Failed to parse Date value '27-02-2014': Cannot parse date "27-02-2014": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"));
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "27-02-2014": not a valid representation
(error: Failed to parse Date value '27-02-2014':
Cannot parse date "27-02-2014": not compatible with any of standard forms
("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

at [Source: (PushbackInputStream); line: 1, column: 22] (through reference chain: ServidorRecadastramentoRequest["dataExpedicaoCTPS"]).

Tentei formata os campos na tela das seguintes maneiras:
formatDate(value) {
  if (value) {
    return moment(String(value)).format('DD/MM/YYYY')
  }
},

formatDate1(value) {
  if (value){
    return moment("2014-02-27T10:00:00").format('DD-MM-YYYY')
  }
},

Answer: Na mensagem de erro está a resposta:
Cannot parse date "27-02-2014": not compatible with any of standard forms
("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

Seu código está enviando a data no formato DD-MM-YYYY mas o servidor espera o formato americano: yyyy-MM-dd.
Comment: SIm, eu já tinha percebido o erro, já tentei arrumar dentro do servidor na classe java, e também no service do pagina, estou deixando passar alguma coisa
Comment: Faça um log no javascript para ver se a formatação está sendo feita da forma esperada por você.


The number of retracts of $G\ltimes \mathbb{Z}$

Question: I asked here that: does  $\mathbb{Z}\oplus G$, where $G$ is a finite abelian group, has only finitely many retracts? The answer was yes. Now I've tried to prove that the number of retracts of $\mathbb{Z}\rtimes G$ is also finite, where $G$ is a finite group. My try is based on the argument of here. My question is that does the argument still holds for $\mathbb{Z}\ltimes G$?
What I've tried: The  notation $+$ is used for the  group action of all groups throughout this argument.  Let $G$ be a finite group with identity element $e$ and $H$ be an arbitrary retract of $G\ltimes \mathbb{Z}$. Then there exists a normal subgroup $N$ of $G\ltimes \mathbb{Z}$ such that $G\ltimes \mathbb{Z}=H\ltimes N$.  Write each element of $G\ltimes \mathbb{Z}$ as $(g,z)$. We show that either $H$ or $N$ must be of the form $J \ltimes \{ 0\}$, where $J$ is a subgroup of $G$. In fact, if  $(g_1,m)\in H$ and $(g_2,n)\in N$ where $m\neq0$ and $n\neq0$, then $(e,mn|G|)=n|G|(g_1,m)=m|G|(g_2,n)\in H\cap N$ which is a contradiction.

First, let's suppose $H=J \ltimes \{ 0\}$. Writing $N\cap(G\ltimes \{ 0\})$ in the form $F \ltimes \{ 0\}$, we have that $G$ is the semidirect product of  $F$ and $J$, i.e. $G=J\ltimes F$.

Now, we assume that $N=J \ltimes \{ 0\}$.  Since all elements of $N$ have the second coordinate as being $0$, and since $(e,1)=h+n$ for some $h\in H$ and $n\in N$, such a value of $h$ must have the second coordinate as being $1$. Thus  $H$ must have at least one element of the form $(g,1)$. Also, for such a choice of $g$, we have that $H$ is the semidirect product of $\langle (g,1)\rangle$ and $F' \ltimes \{ 0\}$, where $F' \ltimes \{ 0\}=H\cap(G\ltimes \{ 0\})$. Hence,  $G\ltimes \mathbb{Z}$ has only finitely many retracts.
Answer: Recall that a retract of $G$ I mean a subgroup $H$ of $G$ such that there exists a normal subgroup $N$ with $G=N\rtimes H$.
If $G$ is infinite dihedral, then every subgroup of order 2 is a retract. And there are infinitely many. However, there are only two conjugacy classes.
In general, let $G$ be virtually cyclic. Then its finite subgroups have bounded order. So its infinite retracts have finite bounded index. Since there are finitely many subgroups of given index, we deduce there are finitely many retracts of finite index (this actually applies in every finitely generated group with a maximal finite subgroup "finite radical").
In a virtually cyclic group, infinite index subgroups are finite. So we have to count finite retracts.
By a result of Wall, $G$ is either finite-by-cyclic or finite-by-dihedral. If $G$ is finite-by-cyclic, then it has finitely many finite subgroups.
Now suppose that $G$ is finite-by-dihedral. Let $W$ be its finite radical. Then maximal finite subgroups of $G$ have index 2 over $W$, and there are two conjugacy classes of such subgroups, and each has finitely many subgroups. Hence there are finitely many retracts up to conjugacy (but possibly infinitely many).
Comment: Thanks very much for your great explanation. By what you said, the infinite dihedral group $D_{\infty}$ has infinitely many retracts. Now by the fact that $D_{\infty}= \mathbb{Z}\rtimes \mathbb{Z}_2$, we conclude that my argument in "what I've tried" is wrong. Right?
Comment: Therefore, $\mathbb{Z} \rtimes G$ may have infinitely many retracts. But what about $G\ltimes \mathbb{Z}$? Why my argument is wrong?
Comment: @M.Ramana you should indeed choose $C_2\ltimes\mathbf{Z}$ with the nontrivial action and check the argument line-by-line. At least you know that you get other retracts by taking $\mathbf{Z}$-conjugates of $C_2$.
Comment: But as I wrote, $\mathbf{Z}\ltimes W$ for $W$ finite has finitely many retracts.
Comment: Yes, got it. I'll do it. Thank you so much for your help.
Comment: I was wondering if you could tell me is my argument right for Z⋉G when G is finite?
Comment: @M.Ramana it's already written in the post (finite-by-cyclic case)...
Comment: By your words, we divide all retracts of a finite-by-cylclic group into two classes: finite retracts, and infinite ones.  Since $G$ has finitely many finite subgroups, so the first class has finitely many elements. But I don't understand these facts "Then its finite subgroups have bounded order. So its infinite retracts have finite bounded index. Since there are finitely many subgroups of given index, we deduce there are finitely many retracts of finite index". Could you please explain a little more about that? Thanks in advance.
Comment: No. 1) I divide cyclic-by-finite groups into finite-by-cyclic and finite-by-dihedral groups (regardless of considering retracts). In the first case $G$ has finitely many finite subgroups, we are done. In the second case, $G$ has infinitely many finite subgroups but finitely up to conjugacy.
Comment: Yes, got it. I appreciate that. Dear @YCor , can I ask two more questions? I really want to figure it out. Why the finite subgroups of a virtually cyclic group have bounded order? And how can we conclude that its infinite retracts have finite bounded index?