Diferença entre std::cout e cout?

Question: Em C++ porque alguns usam std::cout e outros usam apenas cout é apenas o que o programador achar melhor?
Comment: Para utilizar apenas `cout` você precisa utilizar o namespace: `using namespace std;`. Os recursos da biblioteca padrão do C ++ são declarados dentro do espaço de nome `std`. Leia mais em [C++ Standard Library](https://en.wikipedia.org/wiki/C%2B%2B_Standard_Library) e [Name visibility](http://www.cplusplus.com/doc/tutorial/namespaces/).
Answer: std::cout é o nome completo do objeto, incluindo o "nome de família" dele, o sobrenome. Muita gente gosta de usar assim, eliminando qualquer ambiguidade.
Outros preferem usar só o nome do objeto para ficar mais curto. É um jeito mais informal de uso. Para ser possível é preciso indicar antes qual família vai usar. A principal do C++ é justamente a std. Então fazendo:
using namespace std;

Coloquei no GitHub para referência futura.
dispensa o uso do sobrenome em cada objeto do código que pertença à família std.
Veja mais em Por que não é uma boa prática usarmos namespace "std" em C++? para entender as vantagens e desvantagens dele. Mas na essência é gosto.
Um exemplo.
Answer: Em C++ todos nomes definidos no escopo global pertencem a um namespace.
Um nome está no escopo global quando é declarado fora de uma função e de uma classe. Por exemplo

#include <iostream>

int a = 1;

int main()
{
    int b = 2;
    std::cout << "a=" << a << " b=" << b << "\n";
    {
       int c = 3;
       std::cout << "a=" << a << " b=" << b << " c=" << c << "\n";
    }
}

No exemplo acima, a variável aestá no escopo global (dizemos que é uma "variável global"), e as variáveis b e c estão em um escopo local (dizemos que são "variáveis locais"). A variável local b está no escopo da função main, e a variável local c está no escopo do bloco aberto pela chave { anterior, e fechado pela chave } que vem em seguida.
Pois bem, tudo isso foi para dizer que todos os nomes que estão no escopo global pertencem a um namespace. Um namespace, como o nome diz, é um "espaço de nomes", ou um "conjunto de nomes".
Quando um nome no escopo global não pertence explicitamente a um namespace, então automaticamente o nome pertence ao namespace global. Portanto, no exemplo acima, a variável global a pertence ao namespace global.
Para indicar que um nome no escopo global pertence a um namespace, precisamos dar o nome do namespace a que este nome pertence.

#include <iostream>

int a = 1;

namespace x
{
   int a = 2;
};

int main()
{
    int b = 3;
    std::cout << "a=" << a << " b=" << b << "\n";
    {
       int c = 3;
       std::cout << "a=" << a << " b=" << b << " c=" << c << "\n";
    }

    std::cout << "a=" << a << " x::a=" << x::a << "\n";
}

No exemplo acima temos duas variaveis a globais: uma que pertence ao namespace global (inicializada com 1) e uma que pertence ao namespace x (inicializada com 2).
Note que para referenciar a variável a que pertence ao namespace x precisamos fazer isso explicitamente, através da notação x::a.
Existem duas maneiras de simplificar a codificação e não ficar repetindo o nome do namespace. As duas maneiras se utilizam da diretiva using.
A primeira maneira simplifica a referência a apenas um nome do namespace. No exemplo acima, logo após declarar o namespace x utilizaríamos a diretiva using x::a;. Desta maneira, poderíamos referenciar a variável x::a apenas escrevendo a. Entretanto no exemplo acima isto não vai funcionar, pois vai criar conflito com a variável a (inicializada com 1) pertencente ao namespace global!
No exemplo seguinte a variável x::y é referenciada desta maneira simplificada.

#include <iostream>

int a = 1;

namespace x
{
   int a = 2;
   int y = 2;
};
using x::y;

int main()
{
    int b = 3;
    std::cout << "a=" << a << " b=" << b << "\n";
    {
       int c = 3;
       std::cout << "a=" << a << " b=" << b << " c=" << c << "\n";
    }

    std::cout << "a=" << a << " x::a=" << x::a << "\n";
    std::cout << "x::y=" << y << "\n";
}

A outra maneira de simplificar o acesso a variáveis pertencentes a um namespace é utilizando a diretiva "using namespace". Desta maneira todos os nomes pertencentes ao namespace podem ser referenciados sem precisar colocar explicitamente o nome do namespace.
O exemplo abaixo ilustra o uso de using namespace (note o namespace z).

   #include <iostream>

   int a = 1;

    namespace x
    {
       int a = 2;
       int y = 2;
    };
    using x::y;

    namespace z
    {
      int aa = 1;
      int bb = 2;
    };
    using namespace z;

    int main()
    {
        int b = 3;
        std::cout << "a=" << a << " b=" << b << "\n";
        {
           int c = 3;
           std::cout << "a=" << a << " b=" << b << " c=" << c << "\n";
        }

        std::cout << "a=" << a << " x::a=" << x::a << "\n";
        std::cout << "x::y=" << y << "\n";
        std::cout << "z::aa=" << aa << " z::bb=" << bb << "\n";
    }

Ok, e o que tudo isso tem a ver com std::cout ? A resposta é: todas as classes e objetos globais da biblioteca padrão da linguagem C++ estão declarados dentro do namespace std.
Assim, para referenciarmos uma classe ou um objeto da biblioteca padrão C++ precisamos especificar que pertencem ao namespace std.
Então, podemos utilizar uma das 3 maneiras descritas acima: especificar explicitamente o namespace (como em std::cout), ou utilizar uma dretiva para cada nome em std (using std::cout), ou utilizar uma única diretiva para todos os nomes em std (using namespace std).
A 3ª maneira, using namespace std, não é aconselhada, pois libera o acesso a todos os nomes do namespace std, dando margem a potenciais conflitos.
Entretanto, é aceitável a utilização de using namespace std em pequenos programas, programas exemplo, programas teste, etc, é tudo uma questão de "bom senso".
Para completar, podemos fazer referência explícita a uma variável no namespace global através da notação ::. Por exemplo, ::a é uma referência ao nome a declarado no namespace global.
(Edit. Faltou ainda falar sobre namespace anônimo, mas isto fica para a próxima.)

Diferença entre std::cout e cout?


Get typed object keys in Typescript

Question: I have this situation:
const data: Record<string, string> = {
    a: '110px',
    b: '160px',
};

interface Props {
    d?: keyof typeof data[];
}

const t = (d: Props) => 'hi' + d;

t(['a']) // here should be allowed only data keys (a and b)

I want to restrict the t() arguments only to data object keys. I tried as above but I get TS error:

Type 'string[]' has no properties in common with type 'Props'.(2559)

How to achieve this?
NOTE: I need to do this dynamically reading the keys of the object.
Demo: link
Comment: Not possible without sacrificing `keyof` or the index signature.
Comment: @caTS, so why my example is not working?
Comment: *"i need to do this dynamycly reading the keys of the object"* Define "dynamically." Do you mean "handles it if I change the code defining `data`" (possible) or "handles it at runtime" (not possible with TypeScript, which is compile-time only).
Comment: @Asking You defined the props wrong. It should be `({ d }: Props) =>`.
Comment: What is `Props` doing / for? You seem to be passing an array of keys, but `Props` defines a non-array object type.
Comment: @T.J.Crowder, i need to restrict the function argument to `data` object keys.
Comment: @Asking - That doesn't answer my question.
Comment: @T.J.Crowder, with `keyof typeof data[]` i want to restrict the argument function to [a], [b], [a,b]
Answer: Two answers for you:

If by "dynamically" you mean at runtime, no, that's not possible with TypeScript. TypeScript only works with compile-time information.

If by "dynamically" you mean it works even if you change the object literal that creates data, you can do it with (keyof typeof data)[] and allowing TypeScript to infer the type of data (by removing the type annotation on it):
const data = { // <== Note no `Record<string, string>` on this
    a: '110px',
    b: '160px',
};

const t = (d: (keyof typeof data)[]) => 'hi' + d;
t(["a", "b"]); // <=== Works as expected
t(["x"]); // <=== Error as desired

Playground link
If you change the object literal defining data so that it (now) has a c property, the definition of t doesn't have to change (playground), it picks that up.
As captain-yossarian from Ukraine pointed out in a comment, starting with TypeScript 4.9, if you want to make sure that you can't accidentally add an entry to data that doesn't have a string value (or even a more specific one, more in a minute), you can use the new satisfies operator. That lets you enforce a limitation on the object's properties without broadening its type, like this:
const data = {
    a: '110px',
    b: '160px',
} satisfies Record<string, string>;
//^^^^^^^^^−−−−−− new TypeScript 4.9 operator

const t = (d: (keyof typeof data)[]) => 'hi' + d;
t(["a", "b"]); // <=== Works as expected
t(["x"]); // <=== Error as desired

When you do that, if you try to add c: 42 to data, you'll get an error from TypeScript (link) because that would mean that data's type didn't satisfy the constraint Record<string, string>. But unlike as, it won't narrow the type of data, so our keyof typeof data still sees only data's actual property names as a union ("a" | "b"), not just string.
As he also pointed out, if you want to make sure all of your values in data are in the form <number>px, you can use a template literal type like Record<string, `${number}px`> with satisfies (link).
Comment: Btw, if you still want to make sure that `data` should be assignable to `Record` you can use `satisfies`. See [here](https://tsplay.dev/NdYLXm). Also, since values are `${number}px`, we can make Record type more safer: `Record`
Comment: @captain-yossarianfromUkraine - (FYI: The trick to having backticks in comment code is using three backticks at the beginning and end of it instead of just one.)
Comment: Left an example with comments [here](https://tsplay.dev/Nr4alW)
Comment: @captain-yossarianfromUkraine - Ah, I see what you mean, I just didn't get your point at first. Also: How did I miss that "Nightly" option on the drop-down?!
Comment: That said, if #2 is the answer, I'm sure there's a previous question we should point this question at...
Comment: @captain-yossarianfromUkraine - It already satisfies `Record`, doesn't it? At least, I can assign to one. (But not, oddly, ```Record```.) https://tsplay.dev/N7ypDW I can't wait to play with `satisfies`, seems like a great addition.
Comment: Yes, it satisfies, but when you use `satisfies` you will provide an extra restriction for `data` object. For instance, you can add another one key/value pair : `c:42` and you will not get an error (without `satisfies`)

Get typed object keys in Typescript


Code for group programatically fields on edit form similar to Flexifield

Question: I am looking how programmatically to group fields on edit form similar to Flexifield.  The idea is group in the edit form some fields unlimited.  I want to group the fields like as shown in the next link:
http://blog.merge.nl/2009/08/05/multiple-fieldsets-cck-multigroup
I have tried the Flexifield module but has a lot of errors and poor support.
I am working with drupal 6.x.
Thanks very much!!.
Answer: Have you tried the first link on that page? To the dev version of CCK? I just had to do this very thing this morning. The dev version of CCK has an additional module included with it called multigroup. You create a new field of the multigroup type, then add all the fields you want to include in it. Set the number of repeats on the multigroup to unlimited, and you (or your users) can then add as many groups as necessary.
Comment: Actually I cannot to implement this option because the version is in dev, however is a great option, works fine for me and I hope that soon the version is available for production. do you know if only the dev version has this feature?  thanks.
Comment: Yes, it's only in the dev version for now. But the dev version has been out for a long time, and it's pretty stable.
Comment: It's good to know it.  It's a great alternative.  The flexifield module is poorly supported.  I tried the dev version of CCK and works for me.  Thanks again.


How can git be installed on CENTOS 5.5?

Question: How can I install git on CENTOS 5.5 machine?
I tried to install it from yum but got following msg.
root@host [~]# sudo yum install git
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * addons: centos.mirrors.tds.net
 * base: mirror.ubiquityservers.com
 * extras: mirrors.serveraxis.net
 * updates: pubmirrors.reflected.net
addons                                                   |  951 B     00:00
base                                                     | 2.1 kB     00:00
extras                                                   | 2.1 kB     00:00
updates                                                  | 1.9 kB     00:00
Excluding Packages in global exclude list
Finished
Setting up Install Process
No package git available.
Nothing to do
root@host [~]#

Comment: On later versions of CentOS, using the standard 'yum install git' seems to work just fine.
Comment: yum install git-core also works.
Answer: If you are using CentOS the built in yum repositories don't seem to have git included and as such, you will need to add an additional repository to the system. For my servers I found that the Webtatic repository seems to be reasonably up to date and the installation for git will then be as follows:
# Add the repository
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm

# Install the latest version of git
yum install --enablerepo=webtatic git-all

To work around Missing Dependency: perl(Git) errors:
yum install --enablerepo=webtatic --disableexcludes=main  git-all

Comment: This also includes GUI tools and a lot of dependencies. You can use `yum install git` to get only the base install.
Comment: I only needed the last line. Where `yum install git` didn't work, `yum install --disableexcludes=main  git-all` did. Thanks.
Comment: I didn't want to make the commitment of adding a new repo, so I just web-browsed to [http://repo.webtatic.com/yum/centos/5/](http://repo.webtatic.com/yum/centos/5/) and cherry-picked the RPM files I needed.
Comment: This is really good but the dl.fedoraproject.org version may be a better option for some (for me, I had an odd conflict with a perl SVN integration tool with this package so had to use the Fedora version instead).
Comment: just a comment to say thanks for a great answer - this really helped
Comment: @coure2011 - Seems like I can get to it through my browser, what sort of error exactly are you getting?
Comment: Here's the link to webtatic's instructions: http://www.webtatic.com/packages/git17/
Comment: I get this error summary when following that instruciton: http://elsonsolano.com/screenshot/2012-07-18_1555.png
Comment: @ElsonSolano: Note the the x86_64 and i386 descriptors on the packages. You're trying to install mismatching architectures (looks like 64-bit on a 32-bit environment). I would check your Webtatic configuration if that's the repo you're using.
Comment: Same here, I only needed `yum install --disableexcludes=main git-all`
Comment: This should be the selected answer
Comment: Confirmed, the second line does the job.
Comment: Link is now dead.
Answer: From source? From the repos? The easiest way is to use the repos: sudo yum install git should do it. It may first be necessary to set up an additional repo such as EPEL first if git is not provided by the main repos.
If you want to install from source, you can try these instructions. If you have yum-utils installed it's actually easier than that, too**:
sudo yum build-dep git
wget http://kernel.org/pub/software/scm/git/<latest-git-source>.tar.gz
tar -xvjf <latest-git>.tar.gz
cd <git>
make (possibly a ./configure before this)
sudo make install

**Substitute the portions enclosed in <> with the paths you need. Exact procedure may vary slightly as I have not compiled git from source, personally (there may be a configure script, for example). If you have no idea what I'm talking about, then you may want to just install from the repo as per my first suggestion.
Comment: I tried to install it from yum but it says "No package git available"
Comment: @Prakash: It looks like git is not in the standard CentOS repositories. You can either install from source or set up the EPEL repo on your machine: https://fedoraproject.org/wiki/EPEL. Also, you may want to consider asking this question on Superuser/Serverfault if you need more help.
Comment: `sudo yum install epel-release` and `sudo yum install git` work great on Red Hat as well.  (RHEL).
Comment: @Rimian: I know that link manages to install git and gitweb too, but its focus is on gitosis, which is unmaintained and completely superseded by gitolite.
Comment: @Jess Very useful, simple answer. Thanks. Suggest you post this as an answer, because it was direct and not complicated.
Comment: It will even give an error when you try to git init. Now how will I uninstall this one?!
Comment: @ElsonSolano: `yum remove git`. See CentOS's [yum documentation](http://www.centos.org/docs/5/html/yum/) for additional information.
Comment: ***`make (possibly a ./configure before this)`*** - Are you kidding me??? Do you know how many things can go wrong due to PCRE, cURL, OpenSSL and other dependent library problems. Git silently swallows its configuration errors. Your first clone will fail for no apparent reason. After suffering a number of "build Git from sources", I'm now looking for a package-managed version.
Answer: Just:
sudo rpm -Uvh https://archives.fedoraproject.org/pub/archive/epel/5/i386/epel-release-5-4.noarch.rpm
sudo yum install git-core

Comment: Note that that "download.fedora.redhat.com" is now "dl.fedoraproject.org" but this still works.
Comment: This answer is much better than building from source.   It's much easier to manage packages on a continuing basis with yum.
Comment: Worked fine (Centos 5.9)
Comment: In addition to the 2 commands above, I had to execute "sudo yum install git" to get git binary. I am on centOS 5.9
Answer: I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.
Here is the method which works for me (when installing version 1.7.8):
    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
    tar -xzvf ./git-1.7.8.tar.gz
    cd ./git-1.7.8
    ./configure
    make
    make install

You may want to download a different version from here:
http://code.google.com/p/git-core/downloads/list
Comment: I had the same trouble and had to use this approach too. For searchability, here are some of the errors I ran into when trying to install via webtatic or EPEL package approach: "Missing Dependency: perl(Error) is needed by package git-184.108.40.206-1.w5.x86_64 (webtatic)", "Missing Dependency: perl-Git = 22.214.171.124-1.w5 is needed by package git-126.96.36.199-1.w5.x86_64 (webtatic)". No errors when installing using the method specified in this answer.
Comment: isn't there a reliable way of configuring something from source as a package?
Comment: Do you mean to create a new package? I guess you can always do so, yes: http://stackoverflow.com/questions/880227/what-is-the-minimum-i-have-to-do-to-create-an-rpm-file
Comment: I did this using downloading version 1.7.12 and it could not git clone a https url saying that https is not supported. it tried another answer from user SCL using dl.fedoraproject.org as per the comment on that answer and it worked well.
Answer: For installing git

install last epel-release

rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm

Install git from repository

yum install git
Comment: Git 1.8 is kind of old. The script below provides 2.12, which is the latest as of this writing.
Answer: I'm sure this question is about to die now that RHEL 5 is nearing end of life, but the answer seems to have gotten a lot simpler now:
sudo yum install epel-release
sudo yum install git

worked for me on a fresh install of CentOS 5.11.
Answer: yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel gcc
wget http://git-core.googlecode.com/files/git-188.8.131.52.tar.gz
tar zxvf git-126.96.36.199.tar.gz
cd git-22.214.171.124
./configure
make
make install

Answer: OK, there is more to it than that, you need zlib.  zlib is part of CentOS, but you need the development form to get zlib.h ... notice that the yum name of zlib development
is quite different possibly than for apt-get on ubuntu/debian, what follows actually works
with my CentOS version

in particular, you do ./configure on git, then try make, and the first build fails with missing zlib.h

I used a two-step procedure to resolve this
a) Got RPMFORGE for my version of CentOS

See:
www.centos.org/modules/newbb/viewtopic.php?topic_id=18506&forum=38
and this:
wiki.centos.org/AdditionalResources/Repositories/RPMForge

In my case [as root, or with sudo]
$ wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
$ rpm -K rpmforge-release-0.5.2-2.el5.rf.*.rpm
$ rpm -i rpmforge-release-0.5.2-2.el5.rf.*.rpm
## Note: the RPM for rpmforge is small (like 12.3K) but don't let that fool
## you; it augments yum the next time you use yum
## [this is the name that YUM found] (still root or sudo)
$ yum install zlib-devel.x86_64
## and finally in the source directory for git (still root or sudo):
$ ./configure (this worked before, but I ran it again to be sure)
$ make
$ make install

(this install put it by default in /usr/local/bin/git ... not my favorite choice, but OK for the default)... and git works fine!
Comment: git is in rpmforge, so all you have to do is add rpmforge to your list of repositories and install: http://dag.wieers.com/rpm/FAQ.php#B => add rpmforge => yum install git-all (that's it)
Comment: You can format your answer using Markdown rather than using HTML directly. It's easier to edit for others.
Comment: ^ This seems like by far the best soluion
Answer: It looks like the repos for CentOS 5 are disappearing. Most of the ones mentioned in this question are no longer online, don't seem to have Git, or have a really old version of Git. Below is the script I use to build OpenSSL, IDN2, PCRE, cURL and Git from sources. Both the git:// and https:// protocols will be available for cloning.
Over time the names of the archives will need to be updates. For example, as of this writing, openssl-1.0.2k.tar.gz is the latest available in the 1.0.2 family.
Dale Anderson's answer using RHEL repos looks good at the moment, but its a fairly old version. Red Hat provides Git version 1.8, while the script below builds 2.12 from sources.

#!/usr/bin/env bash

# OpenSSL installs into lib64/, while cURL installs into lib/
INSTALL_ROOT=/usr/local
INSTALL_LIB32="$INSTALL_ROOT/lib"
INSTALL_LIB64="$INSTALL_ROOT/lib64"

OPENSSL_TAR=openssl-1.0.2k.tar.gz
OPENSSL_DIR=openssl-1.0.2k

ZLIB_TAR=zlib-1.2.11.tar.gz
ZLIB_DIR=zlib-1.2.11

UNISTR_TAR=libunistring-0.9.7.tar.gz
UNISTR_DIR=libunistring-0.9.7

IDN2_TAR=libidn2-0.16.tar.gz
IDN2_DIR=libidn2-0.16

PCRE_TAR=pcre2-10.23.tar.gz
PCRE_DIR=pcre2-10.23

CURL_TAR=curl-7.53.1.tar.gz
CURL_DIR=curl-7.53.1

GIT_TAR=v2.12.2.tar.gz
GIT_DIR=git-2.12.2

###############################################################################

# I don't like doing this, but...
read -s -p "Please enter password for sudo: " SUDO_PASSWWORD

###############################################################################

echo
echo "********** zLib **********"

wget "http://www.zlib.net/$ZLIB_TAR" -O "$ZLIB_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$ZLIB_DIR" &>/dev/null
tar -xzf "$ZLIB_TAR"
cd "$ZLIB_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** Unistring **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.gnu.org/gnu/libunistring/$UNISTR_TAR" --no-check-certificate -O "$UNISTR_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$UNISTR_DIR" &>/dev/null
tar -xzf "$UNISTR_TAR"
cd "$UNISTR_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** IDN **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://alpha.gnu.org/gnu/libidn/$IDN2_TAR" --no-check-certificate -O "$IDN2_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$IDN2_DIR" &>/dev/null
tar -xzf "$IDN2_TAR"
cd "$IDN2_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** OpenSSL **********"

wget "https://www.openssl.org/source/$OPENSSL_TAR" -O "$OPENSSL_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$OPENSSL_DIR" &>/dev/null
tar -xzf "$OPENSSL_TAR"
cd "$OPENSSL_DIR"

# OpenSSL and enable-ec_nistp_64_gcc_12 option
IS_X86_64=$(uname -m 2>&1 | egrep -i -c "(amd64|x86_64)")

CONFIG=./config
CONFIG_FLAGS=(no-ssl2 no-ssl3 no-comp shared "-Wl,-rpath,$INSTALL_LIB64" --prefix="$INSTALL_ROOT" --openssldir="$INSTALL_ROOT")
if [[ "$IS_X86_64" -eq "1" ]]; then
    CONFIG_FLAGS+=("enable-ec_nistp_64_gcc_128")
fi

"$CONFIG" "${CONFIG_FLAGS[@]}"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make depend
make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install_sw

cd ..

###############################################################################

echo
echo "********** PCRE **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.pcre.org/pub/pcre//$PCRE_TAR" --no-check-certificate -O "$PCRE_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$PCRE_DIR" &>/dev/null
tar -xzf "$PCRE_TAR"
cd "$PCRE_DIR"

make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
    LIBS="-lidn2 -lz -ldl -lpthread" ./configure --enable-shared --enable-pcre2-8 --enable-pcre2-16 --enable-pcre2-32 \
    --enable-unicode-properties --enable-pcregrep-libz --prefix="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make all -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** cURL **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://curl.haxx.se/download/$CURL_TAR" --no-check-certificate -O "$CURL_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$CURL_DIR" &>/dev/null
tar -xzf "$CURL_TAR"
cd "$CURL_DIR"

CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
    LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" \
    ./configure --enable-shared --with-ssl="$INSTALL_ROOT" --with-libidn2="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** Git **********"

wget "https://github.com/git/git/archive/$GIT_TAR" -O "$GIT_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$GIT_DIR" &>/dev/null
tar -xzf "$GIT_TAR"
cd "$GIT_DIR"

make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64,-rpath,$INSTALL_LIB32 -L$INSTALL_LIB64 -L$INSTALL_LIB32" \
    LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" ./configure --with-openssl --with-curl --with-libpcre --prefix="$INSTALL_ROOT"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make all -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

MAKE=make
MAKE_FLAGS=(install)
if [[ ! -z `which asciidoc 2>/dev/null | grep -v 'no asciidoc'` ]]; then
    if [[ ! -z `which xmlto 2>/dev/null | grep -v 'no xmlto'` ]]; then
        MAKE_FLAGS+=("install-doc" "install-html" "install-info")
    fi
fi

echo "$SUDO_PASSWWORD" | sudo -S "$MAKE" "${MAKE_FLAGS[@]}"

cd ..

###############################################################################

echo
echo "********** Cleanup **********"

rm -rf "$OPENSSL_TAR  $OPENSSL_DIR  $UNISTR_TAR  $UNISTR_DIR  $CURL_TAR  $CURL_DIR"
rm -rf "$PCRE_TAR $PCRE_DIR $ZLIB_TAR $ZLIB_DIR $IDN2_TAR $IDN2_DIR $GIT_TAR $GIT_DIR"

[[ "$0" = "$BASH_SOURCE" ]] && exit 0 || return 0

Answer: Just updating this for 2017 and later, as CentOS 5 has reached EOL and the URL for EPEL has changed:
sudo rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo yum install git

This gets you git 220.127.116.11
Comment: This the one that finally worked for me in December 2019
Answer: Just installed git using the following instructions:

Install EPEL V5
#rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm
Install Git
# yum install git git-daemon
Check
# git --version
git version 126.96.36.199
Optionally install Git GUI
# yum install git-gui

For i386 substitute x86_64 by i386 in the URL at step #1.
#rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/i386/epel-release-5-4.noarch.rpm
Answer: This worked for me on CentOS:

Install dependencies:
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel

Get Git
cd /usr/local/src
wget http://code.google.com/p/git-core/downloads/detail?name=git-126.96.36.199.tar.gz
tar xvzf git-220.127.116.11.tar.gz
cd git-188.8.131.52

Build Git
./configure
make
make install

Comment: How is it different from existing answers?
Comment: I believe you need to configure Git with `--with-openssl` and `--with-curl` to get the HTTPS helpers. Otherwise, a `git clone https://github.com/...` will fail.
Answer: Edit /etc/yum.repos.d/Centos* so that all lines that have enabled = 0 instead have enabled = 1.
Answer: yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel

Get the required version of GIT from https://www.kernel.org/pub/software/scm/git/

wget https://www.kernel.org/pub/software/scm/git/{version.gz}

tar -xzvf git-version.gz

cd git-version

./configure

make

make install

How can git be installed on CENTOS 5.5?


Kafka Streams: Dynamically Configure RocksDb

Question: I want to tune performance of Kafka Streams, and for that I have to play with RocksDb configuration values.
I see I can use the StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG to set the configuration for RocksDB. Like shown here.
But I would like a way to configure it dynamically from configuration (in order to change the thresholds without having to compile and deploy all my code.
Is there an option to somehow give concrete implementation instance instead of a class name? (This will allow to set the thresholds, for example, using a properties file)
Answer: Well, You can pass the configuration parameters from the properties file at the runtime and set the ClassName in the StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG.  This way, you won't have to recompile and redeploy your code again and again. Instead at runtime, you will be able to pass different-2 properties value.
Example : You can implement the CustomRockDBConfig as below:
public class CustomRocksDBConfig implements RocksDBConfigSetter {

    public static long blockCacheSize = 50*1024*1024L;
    public static long blockSize = 4096L;
    public static boolean cacheIndexAndFilterBlock = false;

    public static Logger log = Logger.getLogger(CustomRocksDBConfig.class);

    @Override
    public void setConfig(String storeName, Options options, Map<String, Object> configs) {

        BlockBasedTableConfig tableConfig = new BlockBasedTableConfig();
        // Reducing default block cache size
        tableConfig.setBlockCacheSize(blockCacheSize);
        // Increasing the block size as default block size is only 4KB
        tableConfig.setBlockSize(blockSize);
        // Index and Filter block
        tableConfig.setCacheIndexAndFilterBlocks(cacheIndexAndFilterBlock);

        options.setTableFormatConfig(tableConfig);
        options.setMaxWriteBufferNumber(2);

    }

}

While setting the StreamsConfig properties, add below properties.
CustomRocksDBConfig.blockCacheSize = properties.get("blockCacheSize");
CustomRocksDBConfig.blockSize = properties.get("blockSize");
CustomRocksDBConfig.cacheIndexAndFilterBlock = properties.get("cacheIndexAndFilterBlock");
properties.put(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG, CustomRocksDBConfig.class);

No need to recompile the code! It will always read the values from the runtime properties file.
Comment: Good idea! Thanks!


Programando com sons para android

Question: Quero programar sons no Android mas não estou conseguindo. Tentei a API java sound mas o Android studio não reconhece. Quero utilizar MIDI também. Sei que tem o pacote android.media.midi mas ele só funciona pra versões do android acima da 23. Quero uma solução para todas as versões. Alguém pode me ajudar?

Muito obrigado a todos pela atenção.
O código do que eu quero fazer segue abaixo:
<code>    ShortMessage myMsg = new ShortMessage();
    // Play the note Middle C (60) moderately loud
    // (velocity = 93)on channel 4 (zero-based).

    myMsg.setMessage(ShortMessage.NOTE_ON, 4, 60, 93);
    Synthesizer synth = null;
    synth = MidiSystem.getSynthesizer();
    Receiver synthRcvr = null;
    synthRcvr = synth.getReceiver();
    synthRcvr.send(myMsg, -1); // -1 means no time stamp
</code>
Ou seja, quero editar messagens MIDI.
O que eu não entendo é por que o Android Studio não reconhece a API Java Sound (que eu estou utilizando). Alguém sabe?
Oi Márcio Oliveira. Sobre a library que você postou acho que esta incompleta. Não tem, por exemplo, o file ShortMessage.java.
Comment: Veja se é isto que procura: [Como tocar um som usando o Mediaplayer?](https://pt.stackoverflow.com/q/97263/2541) e [Como reproduzir som em android](https://pt.stackoverflow.com/q/94187/2541)
Comment: @suiça, pode postar o que ja tentou fazer ?
Comment: Você quer reproduzir arquivos *mid* ou quer usar/controlar dispositivos *midi* ligados a um dispositivo Android?
Comment: Se especificar melhor o que precisa, talvez eu possa te ajudar a criar sinteticamente os áudios que precisa sem a necessidade de uso de lib, mas "programar sons para android" é muito vago :-(
Answer: A classe MediaPlayer reproduz MIDI sem problemas pois o formato MIDI é suportado nativamente pelo Android conforme documentação oficial:
https://developer.android.com/guide/topics/media/media-formats.html
Eis um exemplo simples com MediaPlayer (coloque um arquivo midi na pasta "res/raw"):
<code>MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.midi_sound);
mediaPlayer.start();

//Se quiser pausar
mediaPlayer.pause()

// Se quiser avançar para os primeiros 30 segundos
mediaPlayer.seekTo(30000);
</code>
Se quiser fazer coisas mais avançadas como editar os MIDI's, usar periféricos, etc, só conheço a classe android.media.midi mesmo que foi introduzida apenas na API 23 (Marshmallow). Pode dar uma olhada nessa library aqui, mas nunca usei:
https://android-arsenal.com/details/1/1988

Programando com sons para android


Should I wait for ajax to complete to redirect a page?

Question: I know how to wait for ajax to complete, but if I'm going to redirect a page after some ajax calls are fired off, should I wait for them to complete before the redirect?  Does it matter?
Comment: I guess that depends if you need to do some errorhandling around the status code returned by the ajax call. If you redirect before it finishes how would you know it went through correctly?
Answer: If you're confident that the ajax call will be successful, then once the ajax call has occurred, redirecting won't affect it as far as your server is concerned. But don't forget, the client could lose their connection or a number of errors could occur, so you should probably wait to make sure the calls were successful. Another thing to consider is whether or not your ajax calls will affect whatever page you're going to redirect to. In that case DEFINITELY wait before redirecting. You won't want your user to get redirected to a broken page because their connection was slow or your server had a hiccup.
Comment: Is ajax a good way to count page views? Won't count users with JS switched off.
Comment: True true. An ajax call that counts page views for example can just be fired off an forgotten.
Comment: Only about 2% of users have javascript disabled:  http://stackoverflow.com/questions/9478737/browser-statistics-on-javascript-disabled.  So really it depends on how accurate you want to be... I usually just ignore those people personally.
Answer: I recommend waiting and handling possible errors that might occur.
You gain safe connection, error spotting, better software, by doing the whole process synchronously, making the redirection coming in the end.
You might spend 0.1 second more of execution but who cares?
Comment: Not true, it the process what I want to do from ajax is something what goes for 20secs. So cares.
Comment: Been a while since I made this comment. What I should have been clear on, and I was basically implying the same thing as the accepted answer, is that if you can absolutely guarantee that the execution will be successful then sure, you can redirect, but there's a chance that the connection will simply get lost or an exception will come up that you want to be able to handle.
Answer: I would argue that Ajax followed by a redirect is not a good use case for Ajax.
Instead I would recommend doing a regular server request and then take care of all operations on the server before redirecting to your final destination.
This will make for a simpler pattern and a lot less network traffic.
I recommend to use Ajax in cases where you want to avoid reloading the page. However in your scenario, you are planning on leaving the page as soon as your operations have completed, so why not avoid the back and forth that Ajax will give you.


Hypergeometric simulation, picking all at once by shuffling once gives wrong result

Question: I'm simulating the model where there are N marbles, out of which K marbles are good. We pick n marbles out of N marbles and are asked for the probability that exactly k out of the n picked ones are good.
I did this two ways: In both I generated an array containing K 'true' values and N-K 'false' values. But in the first method I shuffled this array and picked the n first values and counted how many of these are 'true'. In the second method I picked an index at random and removed that element from the array, looping this n times (and of course counting the 'true' elements I got).
The resulting distribution should be HyperGeometric(N, K, n). The first method gave me wrong results whereas the second gave the correct result. Why isn't it OK to pick the n first elements of the shuffled array or what else am I doing wrong? Here's my Javascript code:
function pickGoodsTest(N, K, n) {
    var origArr = generateArr(N, i=> i<K);
    shuffle(origArr);
    var goods = 0;
    for (let i=0; i<n; i++) if(origArr[i]) goods++;
    return goods;
}

function pickGoodsTest2(N, K, n) {
    var origArr = generateArr(N, i=> i<K);
    var goods = 0;
    for (let i=0; i<n; i++) {
        let rndInd = randInt(0, origArr.length-1);
        let wasGood = origArr.splice(rndInd, 1)[0];
        if (wasGood) goods++;
    }
    return goods;
}

//helper functions:

function generateArr(len, indFunc) {
    var ret = [];
    for (let i=0; i<len; i++) {
        ret.push(indFunc(i));
    }
    return ret;
}

function randInt(a, b){return a+Math.floor( Math.random()*(b-a+1) );}

function shuffle(arr) {
    let arrLen = arr.length;
    for (let i=0; i<arrLen; i++) {
        let temp = arr[i];
        let rndInd = randInt(0, arrLen-1);
        arr[i] = arr[rndInd];
        arr[rndInd] = temp;
    }
}

These are plots of the the outcomes with values N=10, K=6, n=5 (simulated 500000 times):

The yellow dot is the value of the hypergeometric pmf.
Answer: The way you shuffle the array is biased, I would suggest to use Fisher-Yates shuffle instead:
function shuffle(arr) {
    let arrLen = arr.length;
    for (let i=0; i<arrLen; i++) {
        let temp = arr[i];
        let rndInd = randInt(0, i);
        arr[i] = arr[rndInd];
        arr[rndInd] = temp;
    }
}

Comment: Thanks! I have always been using the former way of shuffling without thinking if it is biased. Fisher-Yates shuffle produces the correct outcome (as expected, since it is unbiased as Wikipedia says).
Answer: The code below proves that your shuffle mechanism is wrong. Code is shuffling an array of size 3 in all possible outcome of random and collects statistics of chance for a number to be in the specific position.
import java.util.Arrays;

public class TestShuffle {
    public static void main(String[] args) {
        int[][] stat = new int[3][3];

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    int[] y = {0, 1, 2};
                    swap(y, 0, i);
                    swap(y, 1, j);
                    swap(y, 2, k);

                    stat[0][y[0]]++;
                    stat[1][y[1]]++;
                    stat[2][y[2]]++;
                }
            }
        }

        System.out.println(Arrays.deepToString(stat));
    }

    private static void swap(int[] y, int i, int k) {
        int tmp = y[i];
        y[i] = y[k];
        y[k] = tmp;
    }
}

Output is
[[9, 10, 8], [9, 8, 10], [9, 9, 9]]

This means that the chance for the number "1" to be in the position 0 is greater than 1/3. It is 10/27.


Why won't my module table populate

Question: I have a page that is supposed to output a table of values from my database. I am logged in as an admin and another page I created works just fine, outputting a form for data to be entered into the database. I have the following lines of code pertaining to the new page..
function achievementList_menu() {
$items = array();
$items['achievementList/list'] = array(
    'title' => 'Achievement List',
    'description' => 'A list of all of my achievements',
    'page callback' => 'achievementList_generate_table',
    'access arguments' => array('access content'),
);
return $items;
}

and
EDIT:
function achievementList_generate_table() {
$header = array('ID', 'Name', 'Description', 'Points');
$rows = array();
$results = db_query("SELECT * FROM {achievements}");

foreach ($results as $row){
    $rows[] = $row;
}

return theme('table', array('header' => $header), array('rows' => $rows) );
}

The headers render fine but the $rows array does not. Any idea why?
Comment: Looks like you're trying to use Drupal 6 code in a Drupal 7 site. Check out the docs for [`theme()`](https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme/7) and [this](http://drupal.stackexchange.com/questions/98213/theme-table-from-drupal-6-to-drupal-7)
Answer: I can see a few problems at first glance:
'access callback' => TRUE, will mean everyone gets access no matter what and make 'access arguments' redundant.
The default access callback is user_access, which would accept your access arguments of array('access content'). So to use that just omit the access callback line.
$items['achievementList/list'] = array( is a strange path.
Generally best to keep it all lower case but that's not a requirement.
'page arguments' => array(1), will be passing in the string "list" to your achievementList_generate_table() function, but there is no point passing in a parameter that never changes and you arent actually using it, so just array() is fine for those arguments.
For more information I recommend reading all of the documentation for hook_menu().
The real problem though would be that your callback function is not returning anything for some reason.
(as per Clive's comment) I'm going to assume you are using Drupal 7.
In which case your call to the theme() function is incorrect.
In drupal 7 all variables going into the theme function should be in an array, so your line should look like this:
return theme('table', array('header' => $header, 'rows' => $rows));

Why won't my module table populate


How to implement a two-way binding in a ForEach statement with nested views with Swift?

Question: I've implemented a two-way binding in a Foreach statement that seems to work properly:
struct ContentView: View {
    @ObservedObject var dataManager: ContentViewModel
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false){
            HStack(spacing: 20){
                ForEach($dataManager.data) { $item in
                    if item.status == true {
                        Button(item.tag){
                            item.status.toggle()
                        }
                        .foregroundColor(.white)
                        .background(Color.red)
                    } else {
                        Button(item.tag){
                            item.status.toggle()
                        }
                        .foregroundColor(.white)
                        .background(Color.blue)
                    }
                }
            }
        }
    }
}

The problem is when I've to use some nested views like:
struct ContentView: View {
    @ObservedObject var dataManager: ContentViewModel
    var body: some View {

        ScrollView(.horizontal, showsIndicators: false){
            HStack(spacing: 20){
                ForEach($dataManager.data) { $item in
                    if item.status == true {
                        DetailView(dataManager: dataManager, item: item)
                            .foregroundColor(.white)
                            .background(Color.red)
                    } else {
                        Button(item.tag){
                            item.status.toggle()
                        }
                        .foregroundColor(.white)
                        .background(Color.blue)
                    }
                }
            }
        }
    }
}

and:
struct DetailView: View {

    @ObservedObject var dataManager: ContentViewModel
    var item: SMTTagBoardItem

    var body: some View {
        Button(item.tag){
            item.status.toggle()
        }
    }
}

struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView(dataManager: ContentViewModel(), item: SMTTagBoardItem(id: UUID(), tag: "tag1", rank: 0, status: true))
    }
}

I receive this error:
Cannot use mutating member on immutable value: 'self' is immutable

at line :
item.status.toggle()

How can I implement a two-way binding in a ForEach statement that works by passing values to nested views?
Answer: First of all, instead of using @ObservedObject, use EnvironmentObject and StateObject.
Then instead of var item use @Binding var item. (I think dataManager.data is @Published variable)
ContentView
struct ContentView: View {
    @StateObject var dataManager: ContentViewModel
    var body: some View {

        ScrollView(.horizontal, showsIndicators: false){
            HStack(spacing: 20){
                ForEach($dataManager.data) { $item in
                    if item.status == true {
                        DetailView(item: $item)
                            .environmentObject(dataManager)
                            .foregroundColor(.white)
                            .background(Color.red)
                    } else {
                        //more code
                    }
                }
            }
        }
    }
}

DetailView
struct DetailView: View {

    @EnvironmentObject var dataManager: ContentViewModel
    @Binding var item: SMTTagBoardItem

    var body: some View {
        Button(item.tag){
            item.status.toggle()
        }
    }
}


An infinite loop appears to have resulted from cross-dependent views

Question: In my graphical application, I have a feature to export all pages to images, I have this exception which I don't know where to start looking to solve it:
<code>An infinite loop appears to have resulted from cross-dependent views.
</code>
Any one can help me to get an idea of this exception ? how to solve it ? or what causes such a crash ?
Here is the stack trace:
<code>   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at KETAB.KStudio.UI.SingleInstanceManager.OnStartup(StartupEventArgs e) in C:\Users\KETAB\Desktop\KStudio.V3.0.0_Official_Before_Gitex\KETABStudio\App.xaml.cs:line 555
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
   at KETAB.KStudio.UI.SingleInstanceManager.Main(String[] args) in C:\Users\KETAB\Desktop\KStudio.V3.0.0_Official_Before_Gitex\KETABStudio\App.xaml.cs:line 536
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
</code>
Answer: Well there's not a lot to go on without any code to look at, but I'll give it a shot anyway.
The first step is to make the views less dependent on each other.  Perhaps have a model that they both look at rather than having them look at each other.
Another step might be making the update code only do an update when needed.  Sometimes, when I have a control that changes another control and I put in logic to update it when the other control changes, I find my update stuff is being called when no change is really needed.  For example, if some event results in the resize of a control, you might want to calculate the new values and then ONLY change the size properties if they have actually changed.  (ie: aren't the same as the new values)
Hope this helps...
Comment: thanks, did you encounter the same error message ? can't we tell what would cause the problem ? we are doing virtualizing for the loaded pages, using a view list, when all elements loaded into the page, we capture it, then, we move to the next page .. some times, we render all the pages without problems, but, some times, the bug happens after about 150 page ..
Comment: The problem is that there is no error message.  It's just two windows changing and resulting in each getting updated recursively.  You need to change your event handling on changes such that the changes on one don't cause updates on the other that will in turn update the first window again (and so on and so on..)
Comment: Thanks, We've solved the problem by using do while loop with a wait logic inside ..


Permutations- Restriction on two items placed next to each other.

Question: Having trouble with a question in textbook on permutations: "How many ways can 5 items be arranged out of 9, if two items can't be next to each other."
A question like this is easy when you are ordering items and not leaving any out, like if it was 5 items out of 5 items the answer would be $_5P_5 -~ _{(2\times 4)}P_4$.
I was trying to work it out by thinking of all the possible ways of having 5 items but two not together like:

neither item $A$ or item $B$: $_7P_5$ (discard both, leaving 7)
just item $A$: $_8P_5$ (discarding $B$)
just item $B$: $_8P_5$

But from there I'm stumped because I don't know how to calculate the scenario where both items are in the arrangement of 5 but aren't next to each other.
Can anyone help out?
Answer:
How many ways can five items be arranged in a row if two particular items may not be adjacent?

There are $5!$ ways of arranging items in a line.
From these arrangements, we must subtract those in which two particular items are adjacent.  Place those two items in a box.  That gives us four objects to arrange, the box and the other three objects.  The objects can be arranged in a row in $4!$ ways.  The two objects in the box can be arranged in $2!$ ways.  Hence, the number of inadmissible arrangements is $4!2!$.
Therefore, the number of admissible arrangements is $5! - 4!2!$.

How many ways can five of nine items be arranged if two items can't be next to each other.

Your approach is sound.  Your counts for the case neither item $A$ nor item $B$ is correct.  However, your count for only item $A$ is incorrect.
If only item $A$ is used, then item $B$ is not used, so we must select four of the other $9 - 2 = 7$ objects in addition to item $A$. The five selected objects can be arranged in $5!$ ways.  Hence, the number of arrangements containing only item $A$ is actually
$$\binom{1}{1}\binom{1}{0}\binom{7}{4}5!$$
By symmetry, the same number of arrangements contain only item $B$.
The two cases in which exactly one item is present can be handled simultaneously.  Choose one of $A$ and $B$, four of the remaining seven objects, and arrange the selected objects in $5!$ ways, which gives
$$\binom{2}{1}\binom{7}{4}5!$$
For the case in which both item $A$ and item $B$ are selected, we must select three of the other seven objects to be in the arrangement.  Once those five objects have been selected, they can be arranged in $5! - 4!2!$ ways without placing items $A$ and $B$ next to each other.  Hence, there are
$$\binom{2}{2}\binom{7}{3}[5! - 4!2!]$$
ways to select five objects including $A$ and $B$ and arrange them so that $A$ and $B$ are not adjacent.
Adding the three cases gives
$$\binom{2}{0}\binom{7}{5}5! + \binom{2}{1}\binom{7}{4}5! + \binom{2}{2}\binom{7}{3}[5! - 4!2!]$$
where the first term is the number of admissible arrangements in which neither $A$ nor $B$ is selected, the second term is the number of admissible arrangements in which exactly one of $A$ or $B$ is selected, and the third term is the number of admissible arrangements in which both $A$ and $B$ are selected.


Show a series is Cesaro summable.

Question: I am given this series: $\sum_{n=1}^{\infty}\cos(\frac{n\pi}{6})$ and asked if it converges and if it's Cesaro summable or not.
I can easily show that this series diverges. However, I am unsure how to proceed with showing that this is Cesaro summable or not. Here is what I have so far:
Let $\sigma_m=\frac{1}{m}\sum_{n=1}^{m}\cos(\frac{n\pi}{6})$ where
$$\{\sigma_m\}=\frac{\cos(\frac{\pi}{6})+\cos(2\frac{\pi}{6})+\cos(3\frac{\pi}{6})+\dotsb+\cos(m\frac{\pi}{6})}{m},$$
and then I have no clue how to proceed. Any help is greatly appreciated!
Comment: Is the numerator for $\sigma_m$ bounded or unbounded? Any special structure?
Comment: @erfink It's bounded below by -1 and above by 1. So the sum of the numerator is less than $m$. In fact, the sum is also bounded due to the nature of the cosine function. Would that mean the partial sequence $\{\sigma_m\}$ converge to 0?
Comment: Close. It is bounded, but you'll want to be a little more careful about the precise bounds. Once you find those bounds, it's all squeeze theorem.
Comment: @erfink Would the precise bounds be $-\frac{3}{2}-\frac{\sqrt{3}}{2}$ and $\frac{1}{2}+\frac{\sqrt{3}}{2}$? Would I apply the squeeze theorem such as: Since the numerator is bounded but $m$ is unbounded, we have the partial sequence converging to zero, hence it's Cesaro summable? Sorry if I seem a bit clueless.
Comment: Yep, those are the bounds that I get. Then we have $\forall m$ that $\frac{1}{m} (\frac{-3-\sqrt{3}}{2}) \leq \sigma_m \leq \frac{1}{m}(\frac{1 + \sqrt{3}}{2})$ and taking a limit as $m \to \infty$ gives the desired result. Also, "sequence of partial sums converging to..." instead of "partial sequence converging to...".
Comment: @erfink Okay! Thank you very much!
Answer: The sequence $(\cos n\pi /6)_n$ is periodic :$(\sqrt 3 /2,1/2,0,-1/2,-\sqrt 3/2,-1, -\sqrt 3 /2, -1/2,0,1/2, \sqrt 3 /2,1)$ & repeat.  And the sum of any $12$ consecutive terms of the sequence is $0.$  So the sequence has bounded partial sums.
BTW there is a general method to get a closed form for $\sum_{j=1}^n \cos jx.$
From $\sin (a+b)-\sin (a-b)=$ $(\sin a\cos b +\sin b \cos a)-(\sin a \cos b-\sin b \cos a)=$ $2\sin b \cos a,$ we have $$2\sin (x/2)\cos jx =\sin (jx+x/2)-\sin (jx-x/2)=\sin (jx+x/2)-\sin ((j-1)x+x/2).$$ So $2\sin (x/2)\sum_{j=1}^n \cos jx=$ $\sum_{j=1}^n(\sin(jx+x/2)-\sin ((j-1)x+x/2).$ This last sum telescopes to $\sin (nx+x/2)-\sin (x/2).$
So if $\sin (x/2)\ne 0$ then $\sum_{j=1}^n\cos jx=\frac {\sin (nx +x/2)}{2\sin (x/2)}-\frac {1}{2}.$
If $\sin (x/2)=0$ then $x/\pi \in \mathbb Z.$

Show a series is Cesaro summable.


How can I use relaimpo with glm?

Question: I want to examine the relative importance of the predictors in my model.
I know the {relaimpo} package in R allows for the examination of relative importance for lm but my model a glm and doesn't have a Gaussian family.
Is there a package that I can use to examine relative importance in this situation?
Take for example the following glm:
glm(hp ~ vs + am + disp, family=poisson(), data=mtcars)

Is there a method that would allow me to examine the relative importance of the three predictors in this model either using {relaimpo} or some other software implementation?
Comment: Your `glm` has no specified `family` and the default is `gaussian`. So it's a gaussian glm and works with `calc.relimp`. For other families, an error will be given, as the help file for `calc.relimp` states: "Objects of class mlm or glm with link functions other than identity or family other than gaussian lead to an error message."
Answer: Yes, the package {domir} on CRAN can accommodate a glm.
GLM does not have an explained variance metric in quite the same way as lm but you can obtain a very similar result (i.e., an "lmg"-type metric) from it using the {pscl} package's pR2 function such as:
> domir::domin(hp ~ vs + am + disp, glm, list(pscl::pR2, "McFadden"), data = mtcars, family = poisson())
Overall Fit Statistic:      0.5997781

General Dominance Statistics:
     General_Dominance Standardized Ranks
vs          0.24878939   0.41480242     2
am          0.03508896   0.05850324     3
disp        0.31589971   0.52669434     1

Conditional Dominance Statistics:
         IVs: 1     IVs: 2     IVs: 3
vs   0.46514343 0.24708946 0.03413528
am   0.05091885 0.03338903 0.02095901
disp 0.51211049 0.31419978 0.12138886

Complete Dominance Statistics:
           Dmned?vs Dmned?am Dmned?disp
Dmate?vs          0        1         -1
Dmate?am         -1        0         -1
Dmate?disp        1        1          0

The "General Dominance Statistics" produced by domir::domin are identical to relaimpo::calc.relimp's "lmg" type (see github page for an illustration).

How can I use relaimpo with glm?


Add "delete row and shift up" function to script

Question: I have a script that takes B2 cell as input from google sheets. I set up a list of strings I want to process in rows. I want to "delete cell and shift up" in B2 cell after I run the script. To create a kind of magazine of strings to be input.
Any help is greatly appreciated :)
Answer: Try adding to your code (change "spreadsheet" with the variable you're using for selecting the sheet):
spreadsheet.getRange('B2').deleteCells(SpreadsheetApp.Dimension.ROWS)

Answer: You can do that with Sheet.deleteRow() or Range.deleteCells(), but it would probably make more sense to iterate through the values in column B2:B with something like this:
function magazine() {
  const strings = SpreadsheetApp.getActive().getRange('Sheet1!B2:B').getValues().flat();
  strings.forEach(string => myFunctionThatUsesStringInB2(string));
}


creating randomisation order that is equal across both columns and rows

Question: I'm trying to randomize the order for the receipt of 6 drinks (each in a different day) for 40 participants. I want to ensure that every participant get each drink once, and that every drink has roughly the same number of occurrences across participants in each day.
I create the data, with participants in columns and days in rows.
library(ggplot2)
set.seed(123)
random_order <- as.data.frame(replicate(40, sample(1:6, 6,
                                                   replace = F)))

random_order$trial <- c(1:6)

random_order

Then I check the number of occurrences of each drink within each row / trial, which shows that the frequency of different drinks within trials is not uniform:
tidyr::pivot_longer(random_order, cols = c(1:40),
                    names_to = "participant", values_to = "drink_order") |>
  dplyr::group_by(trial, drink_order) |>
  dplyr::summarise(count = dplyr::n())
# # A tibble: 36 × 3
# # Groups:   trial [6]
#   trial drink_order count
#   <int>       <int> <int>
# 1     1           1     9
# 2     1           2     8
# 3     1           3     8
# 4     1           4     4
# 5     1           5     5
# 6     1           6     6
# 7     2           1     7
# 8     2           2     4
# 9     2           3    10
# 10    2           4     7
# # … with 26 more rows

and look at it with a density plot:
tidyr::pivot_longer(random_order, cols = c(1:40),
                    names_to = "participant", values_to = "drink_order") |>
  dplyr::group_by(trial, drink_order) |>
  dplyr::summarise(count = dplyr::n()) |>
  ggplot(aes(count)) +
  geom_density()

Basically, I want to have a very thin normal curve. How can I make it so that the count column above has a small range during creating the data?
Thanks!
Comment: I'm not sure if you are examining the number of occurrences correctly. Your current code creates a 6 row by 40 column matrix. In each  column, each number appears exactly once, so it is intuitive that each number has 40 occurrences. If you run `table(unlist(random_order))` you will see that each value `1`, `2`, ... ,`6` appears exactly 40 times. Could you clarify what you are wanting?
Answer: You're looking for a variation on a Latin square, which is a set of ordered elements such that each element occurs exactly once per column and once per row. You can generate random Latin squares using agricolae::design.lsd(). In your case, instead of once per row, you want each element to occur the same number of times per row, which you can do by binding together multiple Latin squares.
library(agricolae)
set.seed(123)

# to get 40 columns, first get 7 Latin squares
# (7 squares x 6 columns per square = 42 columns)
orders <- replicate(
  7,
  design.lsd(1:6)$sketch,
  simplify = FALSE
)
# then column-bind and subset to 40 columns
random_order <- data.frame(do.call(cbind, orders))[, 1:40]
random_order$trial <- c(1:6)

Using the code from your question, we can see that all trials include 6 or 7 of each drink:
# A tibble: 36 × 3
# Groups:   trial [6]
   trial drink_order count
   <int> <chr>       <int>
 1     1 1               7
 2     1 2               7
 3     1 3               7
 4     1 4               6
 5     1 5               6
 6     1 6               7
 7     2 1               7
 8     2 2               6
 9     2 3               6
10     2 4               7
# … with 26 more rows

Comment: This is what I was looking for. Very informative, thank you!


Is the 808 sound used as a drum or a bass?

Question: I've been looking at trap/rap tutorials and sometimes the 808s are formed like a bass, where it can even have a bass line, where each has a pitch (note). And other times it's just used like a drum where they don't really talk about its pitch, it just sounds like a heavy kick drum. So which one is it?
Edit: I'm not talking about the actual tr-808 machine. I'm talking about how an 808 sample (or synth that sounds like 808) is used in trap/hip-hop. I'm confused of if it's used as a drum or a bass instrument.
Answer: The 808 was an early drum machine and has many sounds.
One of the more famous sounds is the bass drum which I believe there were several of, varying in length.
Since these were not real drum sounds but synthesized sounds it does have a low pitch to it and a lot of sustain.
If I recall the actual 808 had only one pitch to the bass drum however you can creat your own 808 type kick with a bass drum and a tone generator and a gate. Or even with a bass a bass drum and a gate and then can create a 808 style drum that has a bass line in it. To do this you have the gate open (triggered) by the bass drum signal and have the gate control the sound of the bass or tone. You can control the length of the gate by varying the speed at which the gate closes. Too long and it no longer sounds like a 808 but a drum and a bass. Too short and you don't hear the effect you are going for. If done correctly the effect is pretty cool.
Comment: IIRC, the original 808 had just a single kick generator, with no tuneable pitch, but decay & 'tone' as you say. https://en.wikipedia.org/wiki/Roland_TR-808
Answer: Thus spoke Wikipedia https://en.wikipedia.org/wiki/Roland_TR-808

The Roland TR-808 Rhythm Composer, commonly known as the 808, is a
  drum machine manufactured by the Roland Corporation between 1980 and
  1983.

In electronic music, pitched drum sounds such as kick and snare sounds, are often tuned to fit the key of the song, so that they support the harmony instead of fighting against it. For example if the song is in Cm, you might tune the kick to C and the snare to something like F or G.
https://www.soundonsound.com/sound-advice/q-how-do-i-tune-my-kick-drum-samples-fit-my-song
As the Sound-on-Sound answer above says, it's good to do the tuning of the sounds by using a sampler and pitching the samples up/down in the old-fashioned way instead of trying to use pitch-shifters, because "intelligent" pitch shifters tend to spoil the attacks and other percussive characteristics of the drum sounds.
Answer: Trap producers (along with practioners of many other and earlier styles) revere the sounds of the old Roland TR-808 drum machine, particularly the bass drum.   They use it 'as is', and they process it into a pitched sound by adding harmonics.   So it's both (as you said in your question).
'808' seems to be also sometimes used as a generic term for the whole style of music that features an annoyingly heavy bass beat, stemming from the (apparantly false) information that in the American penal code an '808' is 'Disturbing the peace'.  This is not a musical culture much concerned with rigorous academic definitions :-)
Comment: Trap certainly isn't the first genre of music to make use of the 808. The first wave of house music in the 80s used it extensively, to the extent that one famous English group named themselves 808 State.
Comment: I like the info in this answer, but -1 because you call an entire genre annoying, which I disagree with.
Comment: See if you like it any better after my changes.  You may not use the term this way. It seems that some people do though.. Anything, thanks for explaining a downvote.
Answer: The TR-808, and other machines in the TR series were drum machines. The TR is an acronym for "Transistor Rhythm".
Another machine in the TR series, TR-606, was designed to be paired up with the legendary bass synthesizer, TB-303 (Transistor Bass). They could be synchronizes using a special synchronization cable (this was before the MIDI standard was introduced).
As far as I know, their intended market was to provide a cheap rhythm backing for soloists or small bands.
However, their destiny turned out to be quite different. While the TR-808 and TR-909 found heavy use in both Techno and Hip Hop genres, the sound of the TB-303 was more or less the source for the acid techno and acid house genres (as some ingenious pioneers discovered that you could make interesting music by turning the dials as the it was playing).


Views No results Behaviour Show All

Question: I have a proximity search on views using Gmap and Location API, I've imported all the UK post codes into my zipcodes table in my database, and it all works great. The only thing I would like to change is the no results behaviour.
If a user enters a postcode, and there isn't a venue nearby, the map disappears, and I can show a no results message in its place.
What I would like to happen, is for the map to stay where it is, but showing all venues, with a message underneath saying "Please widen your search area".
Anyone know if this is possible? I've been searching for a similar post on Google, but can't find anything, as I'm not having any errors, just wondering if its possible, and can't seem to figure it out myself!
Answer: You can embed a different View under "No results behaviour"
e.g a View that lists all venues.
Comment: Good idea, I can just add a block to the view and display that as a no results. Thanks.
Answer: BTW: If you want to show just empty map (without markers), you may add a 'Global: TextArea' to 'No Result Behaviour' and put the text area inside:

Comment: You are right. I was looking for a solution without the markers on the map. I posted this message here for my memory. Sorry for disturbing you!
Comment: Thats no good. I finished that website ages ago, but in the original question I asked for a no results behaviour that showed all icons. The questions I marked as the answer was perfect as I created an attachment for the existing view and showed that instead. I dont see how your solution would be useful to anyone?
Answer: To work around, add a dummy item inside the result array
/**
* Implements hook_views_pre_render.
* to render the map even if there is no results
**/
function ei_users_customize_views_pre_render(&$view){
  if( $view->name == 'map_view'  ){
    if( count($view->result) == 0 ){
      $view->result = array('' => '');
    }
  }
}

Views No results Behaviour Show All


Tratar retorno de Post em Javascript

Question: Opa,
Tenho uma página em que é executado um SetInterval de segundos em javascript, esta página captura os dados das divs e envia via post, sendo que estes dados enviados não são fixos, as vezes, pode ser enviado 1 ou mais de um.
No envio, trato essa quantidade de inteiros enviados e separo-o por virgulas, ou seja, o arquivo .php recebe no formato registro_id = 1, 3, 4, 5.
Lá no php dou um explode no valor e um foreach para a consulta de dados e retorno em Json. O problema é que se for enviado mais de um valor via javascript, serão retornados via json a quantidade de resposta obtida na consulta.
O formato de resposta em json é:
Se enviado apenas um ID:
[{"registro":{"registro_id":"1","estado":"1","preco":"R$ 5,99","usuario_id":"18","usuario_nome" :"joao"}}]

Se enviado apenas mais de um ID:
[{"registro":{"registro_id":"1","estado":"1","preco":"R$ 5,99","usuario_id":"18","usuario_nome" :"joao"}}]
[{"registro":{"registro_id":"3","estado":"1","preco":"R$ 3,99","usuario_id":"48","usuario_nome" :"maria"}}]

O problema é que preciso receber esses valores em minha função javascript e atualizar os campos da página, mas, são recebidos valores distintos para campos com classes distintas, tentei assim:
    usuario_id   = $('.user-id-'+ registro_id);
    usuario_nome = $('.user-name-'+ registro_id);

Os campos estão com as devidas classes, a variavel registro_id é a mesma recebida na função no setinterval, mas, isso só funciona se é enviado apenas um item ao .php, se são enviados dois, nada acontece.
Exemplo resumido:
DIVS

Função JavaScript
function atualizaregistro() {
    var registros = '';

    $.ajaxSetup({
        cache: false
    });
    $('.content_item').each(function() {
        var new_value = $(this).attr('title');
        if (registros != '') registros = registros + ',';
        registros = registros + new_value;
    });

    if (registros) {
        $.ajax({
            url: '_files/_update_information.php',
            dataType: 'json',
            type: 'POST',
            data: 'registro_id=' + registros,
            global: false,
            success: function(data) {

                $.each(data, function(j, item) {

                    var usuario_id = item.registro.usuario_id;
                    var usuario_nome = item.registro.usuario_nome;

                    field_user_id = $('.user-id-' + registro_id);
                    field_user_name = $('.user-name-' + registro_id);

                    field_user_id.text(usuario_id);
                    field_user_name.text(usuario_nome);

                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }
}

PHP
$registros = explode(',',$_POST['registro_id']);
foreach($registros as $registro_id)
{
    ...Código Consulta BD

    $temp = '{"registro":{"registro_id":"'.$registro_id.'","estado":"1","preco":"'.$preco.'","usuario_id":"'.$usuario_id.'","usuario_nome":"'.$usuario_nome.'"}}';
}

echo "[".$temp."]";

Alguem pode ajudar?
Comment: Quando envias dois items ao PHP como é que os distingues no JavaScript e HTML? cada um tem a sua chave como `user-name` ou cada item tem `user-name` e `user-id`?
Comment: No html cada div tem os campos com user-name-ID e user-id-ID, esse ID é o valor enviado ao javascript, e o mesmo consultado no php
Comment: Então o melhor era criares um JSON no javascript com esses IDs... como estás a ir buscar esses valores no JavaScript? podes mostrar um exemplo de HTML com dois items?
Comment: Sim, farei um exemplo, por favor, só um instante
Comment: @Sergio Adicionei o exemplo resumido do código, diretamente na questão
Answer: Acho que o melhor era enviares um JSON, e devolveres um JSON.
O que estás a fazer agora é a criar uma string customizada, a fazê-la "explodir" (explode) no PHP e etc... o melhor é não reinventar a roda.
Sugestão:
function atualizaregistro() {
    $.ajaxSetup({
        cache: false
    });
    var registos = $('.content_item').get().map(function(el) {
        return el.id;
    });

    if (registros) {
        $.ajax({
            url: '_files/_update_information.php',
            dataType: 'json',
            type: 'POST',
            data: {registro_id: JSON.stringify(registos)},

depois no PHP:
$registros = json_decode($_POST['registro_id']);
$retorno = [];
foreach($registros as $registro_id){
    // etc
    $retorno[] = array(id, estado, preco, etc...)

e para devolveres retorna o mesmo, ou pelo menos só uma array:
echo json_encode($retorno);

Desta maneira sabes no JavaScript que tens a mesma ordem da array e podes fazer:
registos.forEach(function(id, i){
    $('#' + id).find('.coupon-time').html(data[i].preco);
    // etc...

});

Ou seja:

cria uma array com os elementos
passa um JSON para, e do, PHP
itera essa array de novo e usa o index para aceder ao datado ajax

Nota:: tens IDs duplicados! Só podes ter um ID coupon-time por página. Eles têm de ser únicos. No meu exemplo mudei para uma classe, assim agrupas os elementos com a mesma funcionalidade.
Enfim, foi uma sugestão, espero que dê para interpretar e adaptar ao teu código.
Comment: Concordo plenamente, não tenho palavras para agradecer sua sugestão, já estou adaptando-a a meu código, mas, surgiu-me um problema, o php não está reconhecendo a variavel enviada no post

 `Undefined index: registro_id in`

As variaveis no javascript estão corretas e com valor, podeira me dar uma força
Comment: @sNniffer acho que tinha trocado a sintaxe, vê o `data` do ajax de novo e depois no PHP.
Comment: Show de bola, Sergio não querendo abusar muito, mas, me tira uma dúvida rápida.

Estou enviando o json e recebendo do php com sucesso, mas se envio para o php apenas um valor, os dados são retornados com sucesso, se são enviados mais de um valor é retornado os dados referente apenas ao último valor. Lá no php pelo foreach vi que os ID são recebidos corretamente. Ex.: Ao enviar os ID 1 e 3, o foreach é executado e envia os dados apenas referente ao 3.

Abraço

Tratar retorno de Post em Javascript


How to add a column name to a column that doesn't have a name already

Question: I am trying to add a column name to a column that doesn't already have a name. I would be fine with even deleting the column, I just don't know how to select a column without a name. Here is a small example. I would be trying to rename that first column or even delete it. For whatever reason, I think dplyr add that column when I manipulate my data. It could even be tidyr. I'm not sure which package is adding that column, but it is annoying.
The first column doesn't have a name. What I want to do is either give it a name or delete it because it gives me issues when I save the data as a text file.
<code> chr location effect impact
1 4 345765 missense moderate
2 7 6543 frameshift high
3 8 864523 missense moderate
</code>
Comment: are you sure you're not looking at the row names of the data frame? these are printed by default.  Can you show us `str(your_data)` ? (what is `names(your_data)`? `ncol(your_data)` ?
Comment: You can delete a column also by its position, for example: `your_data = your_data[,-3]`.
Comment: try `write.table(df, "test.txt", row.names = F)` while writing your final data in a text file.
Answer: This Question is not clear, but you can change the name of the first (or any) column using the index of the column like this:
<code>colnames(data.frame)[1] <-  "Brian"
</code>
Comment: That's all I was asking. Quick and easy solution. Thanks for the help


Como fazer uma notificação de aumento usando ajax + php?

Question: Estou apenas tentando aumentar a notificação de um item. Quero que sempre que adicionar um novo item ao meu carrinho, tenha de ver o número de aumento de notificação do carrinho. no console javascript vejo que está funcionando bem mas na minha tela nada muda. alguem pode me ajudar a ver onde esta o problema por favor?
Esse é a parte HTML. eu estou usando o id="show_result" para mostrar o que rola na parte back-end com ajax.

Esse é a parte javascript com ajax:
setInterval(function()
{
    $.ajax({
        type: "get",
        url: "API/READ/count_panier.php",
        success:function(data)
        {
            $('#show_result').html(data);
            //console.log the response
            console.log(data);
        }
    });
}, 1000); //10000 milliseconds = 10 seconds
// MAKING REGISTRATION

E aqui está a pagina que eu chamo para contar se há dados que foram adicionando no carrinho.PAGINA: count_panier.php
$count = $conn->prepare("SELECT  *FROM panier");
$count->execute();
$counter = $count->rowcount();
echo ''.$counter.'';

Comment: Como vc diz que no console aparece corretamente, o problema está no seu HTML e/ou css e nesse caso não há dados suficientes na pergunta para verificar o problema. Também diria que não faz muito sentido a sua "api" retornar HTML. Deveria alterar o retorno para um JSON, por exemplo.
Answer: Atualizar um elemento no DOM com o HTML daquele da chamada ajax pode ser feito dessa forma
$('#show_result').html($('#show_result',data).html());
ou
$('#show_result').replaceWith($('#show_result',data));
Comment: tentei seguir seu exemplo mas o problema continua infelizmente


Basic Quadratic formula calculator shell script trouble

Question: This is my very first shell script for a Unix class, this is one of the scripts I hope to submit for my final. However there are a few kinks I cannot seem to clear up, it seems to be arithmetic operation errors, and I can't seem to figure it out. Please be kind! thank you so much for your time.
lightgreen=`echo -en "\e[92m"
echo What are the values of a, b \& c?

LIGHTRED=`echo -en "\e[101m"

echo a value:
read a

echo b value:
read b

echo c value:
read c

discrim=$(($b**2 - 4*$a*$c))

sqrtd=$((sqrt($discrim) | bc ))

echo test $sqrtd

echo ${lightgreen}The discriminant is:${discrim}

#xone=$((( -$b + sqrt$discrim) / (2 * $a) | bc ))
#xtwo=$((( -$b - sqrt$discrim) / (2 * $a) | bc ))

xone=$((echo (-1*$b + sqrt($discrim)) / (2*$a) | bc ))
xtwo=$((echo (-1*$b - sqrt($discrim)) / (2*$a) | bc ))

echo ${lightgreen}The discriminant is:${discrim}

#if [$discrim -lt 0 ]
#       echo $LIGHTRED There are no real solutions.
#
#
#
echo The two solutions are $xone $xtwo

I have tried to mess with the syntax a good amount, I'm not sure if it's the parentheses that mess me up or the sqrt function, I have tried to incorporate  | bc but to no avail. Any help is greatly appreciated! :)
Comment: You're confusing the syntax for getting bash to do math -- `$((someformula))` -- with the syntax for getting `bc` to do math -- `$(echo someformula | bc)`. `$(( ))` does bash math, while `$( )` runs commands (like `bc`) and captures their output. bash's can't do more than basic integer math, so you need to use `bc` pretty much everywhere.
Comment: It would help if you'd post error messages for each thing you've tried.
Answer: Don't hesitate to call man bash, man bc manual pages.
Use https://www.shellcheck.net/ to check your shell scripts.
Shellcheck also exists on command line and in Visual Studio Code with extension.
#! /usr/bin/env bash
# The first line is very important to now the name of the interpreter

# Always close " , ' , or ` sequences with same character
# Do not use old `...` syntax, replaced by $(...)
# Here, use $'...', to assign value with \... sequences
lightgreen=$'\e[92m'
lightred=$'\e[101m'
normal=$'\e[0m'
# It's better to put phrase between "..." or '...'
echo "What are the values of a, b & c?"

# Use read -p option to specify prompt
# Use read -r option to not act backslash as an escape character
read -p "a value: " -r a
read -p "b value: " -r b
read -p "c value: " -r c

# With bash only, it's only possible to use integer values
# discrim=$(($b**2 - 4*$a*$c))
# use bc instead
discrim=$(bc -l <<<"$b^2 - 4*$a*$c")

# The syntax:
#    bc <<<"..."
# is equivalent to:
#    echo "..." | bc
# but without pipe (|)

# Close the color change with normal return
echo "${lightgreen}The discriminant is: ${discrim}${normal}"

if [[ "${discrim:0:1}" == "-" ]]; then

    echo "${lightred}There are no real solutions${normal}"
    # ... complex ...

else

    sqrtd=$(bc -l <<<"sqrt($discrim)")
    echo "sqrt($discrim)=$sqrtd"

    xone=$(bc -l <<<"(-1*$b + $sqrtd) / (2*$a)")
    xtwo=$(bc -l <<<"(-1*$b - $sqrtd) / (2*$a)")

    echo "The two solutions are: $xone and $xtwo"

fi


Enable case sensitivity for spark.sql globally

Question: The option spark.sql.caseSensitive controls whether column names etc should be case sensitive or not. It can be set e.g. by
spark_session.sql('set spark.sql.caseSensitive=true')

and is false per default.
It does not seem to be possible to enable it globally in $SPARK_HOME/conf/spark-defaults.conf with
spark.sql.caseSensitive: True

though.
Is that intended or is there some other file to set sql options?
Also in the source it is stated that it is highly discouraged to enable this at all. What is the rationale behind that advice?
Answer: As it turns out setting
spark.sql.caseSensitive: True

in $SPARK_HOME/conf/spark-defaults.conf DOES work after all. It just has to be done in the configuration of the Spark driver as well, not the master or workers. Apparently I forgot that when I last tried.
Answer: Yet another way for PySpark. Using a SparkSession object named spark:
spark.conf.set('spark.sql.caseSensitive', True)

Answer: Try sqlContext.sql("set spark.sql.caseSensitive=true") in your Python code, which worked for me.


Simplifying $\frac{^nC_{1}}{1 \times 2}-\frac{^nC_{2}}{2 \times 3}+..+(-1)^{n+1}\frac{^nC_{n}}{n \times (n+1)}$

Question: I was thinking about the following sum -
$\frac{^nC_{1}}{1 \times 2}-\frac{^nC_{2}}{2 \times 3}+\frac{^nC_{3}}{3 \times 4}+..+(-1)^{n+1}\frac{^nC_{n}}{n \times (n+1)} = 1 + \frac{1}{2}+\frac{1}{3}+\frac{1}{4}+\frac{1}{5}+..+\frac{1}{n+1}$
How to approach to prove this summation equality?, I could owrite the LHS as $2n - 3n(n-1) + 2n(n-1)(n-2) +...$ after simplification.
Comment: Prove by induction.
Comment: Write $$\binom nr/r(r+1)=\binom nr/r -\binom nr/(r+1)$$ the second can be managed easily . For the first see https://math.stackexchange.com/questions/437523/proving-binomial-identity-without-calculus
Comment: But is there any alternative way ?
Comment: Yup, got it, thanks!!
Answer: Firstly,
$$\frac{^nC_{1}}{1 \times 2}+\frac{^nC_{2}}{2 \times 3}+\frac{^nC_{3}}{3 \times 4}+..+\frac{^nC_{n}}{n \times (n+1)} =\left[\frac{^nC_{1}}{1}+\frac{^nC_{2}}{2}+\frac{^nC_{3}}{3}+..+\frac{^nC_{n}}{n}\right]-\left[\frac{^nC_{1}}{2}+\frac{^nC_{2}}{3}+\frac{^nC_{3}}{4}+..+\frac{^nC_{n}}{(n+1)}\right] $$
Now consider,
\begin{align*}
(1+x)^n-1 & = \binom{n}{1}x+\binom{n}{2}x^2+\dotsb+\binom{n}{n}x^n\\
\int_0^1((1+x)^n-1)\,dx & = \binom{n}{1}\frac{1}{2}+\binom{n}{2}\frac{1}{3}+\dotsb+\binom{n}{n}\frac{1}{n+1}\\
\frac{(1+x)^n-1}{x} & = \binom{n}{1}1+\binom{n}{2}x+\dotsb+\binom{n}{n}x^{n-1}\\
\int_0^1\frac{(1+x)^n-1}{x}\,dx & = \binom{n}{1}\frac{1}{1}+\binom{n}{2}\frac{1}{2}+\dotsb+\binom{n}{n}\frac{1}{n}.
\end{align*}
So your given series is
$$\int_0^1\frac{(1+x)^n-1}{x}\,dx-\int_0^1((1+x)^n-1)\,dx$$

Since the question was edited later:

Since you made the changes in the sign of the actual expression, so you need to redo what I have proposed with $(1-x)^n$.
Comment: Thanks for your effort, sorry for late edit.
Answer: We can prove the following involving harmonic numbers:
$$\sum_{r=1}^n \frac{(-1)^{r+1}}{r(r+1)} {n\choose r}
= H_{n+1} - 1.$$
Start by writing for the LHS
$$\sum_{r=1}^n \frac{(-1)^{r+1}}{r(r+1)} \frac{r+1}{n+1} {n+1\choose r+1}
= \frac{1}{n+1}
\sum_{r=1}^n \frac{(-1)^{r+1}}{r} {n+1\choose r+1}
\\ = \frac{1}{n+1}
\sum_{r=2}^{n+1} \frac{(-1)^r}{r-1} {n+1\choose r}.$$
Working with the sum term and introducing
$$f(z) =  (-1)^{n+1}
\frac{(n+1)!}{z-1} \prod_{q=0}^{n+1} \frac{1}{z-q}$$
we have for $2\le r\le n+1$ that
$$\sum_{r=2}^{n+1} \mathrm{Res}_{z=r} f(z)
= \sum_{r=2}^{n+1}  (-1)^{n+1}  \frac{(n+1)!}{r-1}
\prod_{q=0}^{r-1} \frac{1}{r-q} \prod_{q=r+1}^{n+1} \frac{1}{r-q}
\\ = \sum_{r=2}^{n+1}  (-1)^{n+1}  \frac{(n+1)!}{r-1}
\frac{1}{r!} \frac{(-1)^{n-r+1}}{(n+1-r)!}
= \sum_{r=2}^{n+1} \frac{(-1)^{r}}{r-1} {n+1\choose r},$$
so this is the  desired sum. Now residues sum to  zero and the residue
at infinity  is zero since $\lim_{R\to\infty}  2\pi R / R  / R^{n+2} =
0.$ The remaining poles are at $z=0$ and $z=1.$ We write
$$f(z) =  (-1)^{n+1} (n+1)! \frac{1}{z} \frac{1}{(z-1)^2}
 \prod_{q=2}^{n+1} \frac{1}{z-q}$$
to get
$$\mathrm{Res}_{z=0} f(z)
= (-1)^{n+1} (n+1)! \frac{(-1)^n}{(n+1)!} = -1$$
as well as
$$\mathrm{Res}_{z=1} f(z)
= (-1)^{n+1} (n+1)!
\left. \left(-\frac{1}{z^2} \prod_{q=2}^{n+1} \frac{1}{z-q}
- \frac{1}{z} \prod_{q=2}^{n+1} \frac{1}{z-q}
\sum_{q=2}^{n+1} \frac{1}{z-q} \right) \right|_{z=1}
\\ = (-1)^{n+1} (n+1)!
\left(- \frac{(-1)^n}{n!}
+ \frac{(-1)^n}{n!} H_n \right)
= n+1 - (n+1) H_n.$$
Restoring the multiplier in front we thus obtain
$$\frac{1}{n+1}
(- \mathrm{Res}_{z=0} f(z) - \mathrm{Res}_{z=1} f(z) )
= \frac{1}{n+1} (1 + (n+1) H_n - (n+1))
\\ = H_n - \frac{n}{n+1} = H_{n+1} - 1.$$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\sum_{r = 1}^{n}{\pars{-1}^{r + 1} \over r\pars{r + 1}}
{n \choose r} =
H_{n + 1} - 1:\ {\LARGE ?}}$.

\begin{align}
&\bbox[10px,#ffd]{\sum_{r = 1}^{n}{\pars{-1}^{r + 1} \over r\pars{r + 1}}
{n \choose r}} =
-\sum_{r = 1}^{n}
{n \choose r}\pars{-1}^{r}\pars{\int_{0}^{1}x^{r - 1}\,\dd x}
\pars{\int_{0}^{1}y^{r}\,\dd y}
\\[5mm] = &\
-\int_{0}^{1}\int_{0}^{1}\sum_{r = 1}^{n}{n \choose r}\pars{-xy}^{r}\,
{\dd x \over x}\,\dd y =
-\int_{0}^{1}\int_{0}^{1}\bracks{\pars{1 - xy}^{n} - 1}\,{\dd x \over x}\,\dd y
\\[5mm] = &\
-\int_{0}^{1}\int_{0}^{y}\bracks{\pars{1 - x}^{n} - 1}
\,{\dd x \over x}\,\dd y =
-\int_{0}^{1}{\pars{1 - x}^{n} - 1 \over x}\int_{x}^{1}\dd y\,\dd x
\\[5mm] = &\
-\int_{0}^{1}{\pars{1 - x}^{n + 1} - 1 + x \over x}\,\dd x =
\int_{0}^{1}x\,{x^{n} - 1 \over x - 1}\,\dd x =
\int_{0}^{1}\sum_{k = 1}^{n}x^{k}\,\dd x
\\[5mm] = &\
\sum_{k = 1}^{n}{1 \over k + 1} =
\sum_{k = 2}^{n + 1}{1 \over k} = \bbx{H_{n + 1} - 1} \\ &
\end{align}


What is $\nabla\cdot A\nabla u$ for $A\in C^1(\mathbb{R}^n\to\mathbb{R}^{n\times n})$ and $u\in C^2(\mathbb{R}^n\to\mathbb{R})$?

Question: Let $A\in C^1(\mathbb{R}^n\to\mathbb{R}^{n\times n})$ and $u\in C^2(\mathbb{R}^n\to\mathbb{R})$. How can we compute $\nabla\cdot A\nabla u$? I assume we need to apply some kind of product rule, but I wasn't able to figure out how exactly.
Comment: How are you using $\nabla$ and $\nabla\cdot$? I assume $\nabla u$ is a matrix?
Comment: @snarski No, $u$ is a scalar-valued function. $\nabla\cdot f$ is the formal scalarproduct of $$\nabla=(\partial_1,\ldots,\partial_n)^T$$ and $f\in C^1(\mathbb{R}^n\to\mathbb{R}^n)$.
Answer: We have the mappings $\nabla u : \mathbb{R}^n \to \mathbb{R}^n$ and $A: \mathbb{R}^n \to \mathbb{R}^{n \times n}$, so $A \nabla u : \mathbb{R}^n \to \mathbb{R}^n$ is given by $(A\nabla u)_i(x) = \sum_{j=1}^n A_{ij}(x) \partial_j u(x)$.
Now you want to compute $\nabla \cdot A \nabla u$, which is then given by
$$
\nabla \cdot (A \nabla u)(x) = \sum_{i=1}^n \partial_i (A\nabla u)_i(x) = \sum_{i=1}^n\sum_{j=1}^n\partial_i [A_{ij}(x) \partial_j u(x)] \\= \sum_{i,j=1}^n [A_{ij}(x) \partial_i \partial_j u(x) + \partial_i A_{ij} \partial_j u(x) ].
$$
In the last equality we just used the normal product rule.


getting error null pointer exception attempt to invoke virtual method

Question: getting error that null pointer exception has occurred and trying to invoke virtual method
public class after10th extends AppCompatActivity {

    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.after10th);

        ListView lv = (ListView) findViewById(R.id.searchten);
        ArrayList<String> after_ten = new ArrayList<>();
        after_ten.addAll(Arrays.asList(getResources().getStringArray(R.array.after_ten)));

        adapter = new ArrayAdapter<>(after10th.this, android.R.layout.simple_list_item_1, after_ten);

        lv.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_search, menu);
        MenuItem item = menu.findItem(R.id.menusearchten);
        SearchView searchView = (SearchView) item.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                adapter.getFilter().filter(newText);
                return false;
            }
        });

                return super.onCreateOptionsMenu(menu);`enter code here`
    }

}

This is the error:
09-23 19:09:17.242 9000-9000/com.example.supriya.career_guidance E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.supriya.career_guidance, PID: 9000
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
Answer: The error message pretty much says outright that item.getActionView() returns null, on this line:
SearchView searchView = (SearchView) item.getActionView();


JSON alimentado por while

Question: Tenho um contrutor de Gráficos que é alimentado por JSON o que eu queria erra gerar casas dinamicamente ou seja ter um numero de elementos estipulado por uma variável.
Exemplo do que eu tentei fazer:

Comment: Bem observado @Otavio, corrigido a resposta :)
Comment: O corpo `while` vai ser executado alguma vez? Na linha anterior você define `i = 0` e na condição do `while` o `i` tem que ser igual a 2 para ser executado.
Answer: Funcionou.Porem não estou conseguindo passar valor de um array do PHP.

JSON alimentado por while