PDO não conecta ao MySQL

Question: Estou tentando fazer uma conexão com o banco por PDO, mas toda vez que tento fazer essa conexão, aparece a mensagem:
could not find driver

Fui atrás pra saber e fiquei sabendo que tinha que habilitar o PDO no php.ini. Ok, fui lá e tirei a ; da onde precisava, mas mesmo assim ainda aparece a mensagem.
Meu código é esse:
<?php

try{
// Faz conexão com banco de daddos
$pdo = new PDO("
    mysql:host=localhost;
    dbname=servidores;",
    "root",
    "root");
}catch(PDOException $e){
// Caso ocorra algum erro na conexão com o banco, exibe a mensagem
echo 'Falha ao conectar no banco de dados: '.$e->getMessage();
die;
}

?>

Alguém sabe o que pode ser?
Comment: Você reiniciou o PHP depois de alterar o `php.ini`? Que sistema operacional está usando?
Comment: @user2154508  Qual versão do php vc esta usando? e qual linha foi descomentada?
Comment: Qual sistema operacional você está usando?
Comment: Eu estou usando o Windows, e a versão do meu PHP é: PHP Version 5.2.6
Comment: Cara, tem certeza que está usando PHP 5.2.6? Se sim, tem algum motivo especial? Caso contrário, atualize isso. Não é a resposta direta para seu problema, mas essa versão de é arcaica.
Comment: Olá, podes dizer qual é o erro retornado ?
Comment: @Edilson está no começo da pergunta: `could not find driver`
Comment: @user2154508 além da linha do pdo_mysql você configurou a pasta de extensões do php no arquivo .ini ?
Answer: A extensão do mysql não está instalada ou você não tem o mysql instalado no localhost.
Crie um arquivo info.php na raiz do webserver, com a funcao phpinfo(); e depois acesse localhost/info.php e procure por pdo, la você vê se o driver pdo para mysql está instalado.
Comment: Isso deveria ser um comentário, não uma resposta.
Answer: No linux,digite no terminal:
php -i | grep drivers

E verifique se o driver está habilitado.
Nos sistemas baseados em Debian/Ubuntu a instalação é simples, no terminal digite:
//para instalar
sudo apt-get install php5-mysql

//reiniciando o apache
sudo service apache2 restart

Answer: É bastante comum ocorrer, principalmente com pessoas que desenvolvem em ambiente Windows em versões anteriores à 5.3, versão na qual não existe a necessidade de se habilitar uma extensão à parte para a PDO em si, de elas habilitarem apenas a DLL da PDO (php_pdo.dll) e se esquecerem de habilitar a(s) DLL(s) do(s) SGBD(s) suportados pela PDO que estarão utilizando.
A solução, também simples, é editar o PHP.INI removendo o sinal de comentário ( ; ) da linha referente a, no caso, php_pdo_mysql.dll
Answer: Quando ocorre esse tipo de problema o que pode acontecer:

se você estiver usando o windows. pode não ter a dll respectiva
A porta do MySql instalado não é a padrão (3306)
Os dados do banco de dados não estão corretos
Answer: Uma maneira rapida e facil de testar se o mySQL está disponivel é pelo proprio PDO com sua função PDO::getAvailableDrivers()
  $drivers = PDO::getAvailableDrivers();
    foreach ($drivers as $nome) {
      echo 'Disponivel: ' . $nome . '
';
    }

Deste modo você lista todos os drivers que o PDO consegue utilizar.
Answer: Execute php -m no terminal/prompt e verifique se a extensão pdo_mysql está realmente habilitada, caso esteja e ainda não funciona verifique se o MySQL foi iniciado.
Comment: Isso deveria ser um comentário, não uma resposta.
Answer: Assim funciona.
try{
    // Faz conexão com banco de daddos
    $host = ('localhost');
    $user = ('root');
    $pass = ('root');
    $bancodb = ('curso_php');

    $conecta = new PDO("mysql:host=$host;dbname=$bancodb", $user, $pass);
}catch(PDOException $e){
    // Caso ocorra algum erro na conexão com o banco, exibe a mensagem
    echo 'Falha ao conectar no banco de dados: '.$e->getMessage();
    die;
}

PDO não conecta ao MySQL


how to sort the null objects in a dynamically allocated array of objects, so that the null objects are in the back of the array c++

Question: I have a dynamically allocated array of objects. Some of the array is populated by objects  but the other parts are null. When I use a bubble sort to sort the objects in the array it sorts correctly, but the array parts that are null are in  front of the array parts that are populated. Is there any way to push the null objects to the back of the array instead of the front?
picture of what is happening in the array:
| null | null | null | object | object |

picture of what I want the array to look like:
| object| object | null | null | null |

Here is my code for my bubble sort:
::bubbleSort()
{
  bool flag = true;
  obj temp;
  int j = 0;

  while(flag)
  {
    flag = false;
    j++;

    for(int i = 0; i < (max - j); i++)
    {
      if(arr[i] > arr[i + 1])
      {
        temp = arr[i];
        arr[i]= arr[i+1];
        arr[i+1] = temp;
        flag = true;
      }
    }
  }
}

here is how i define my arr:
private:
obj *arr;

then in my constructor
max = 25
arr = new obj[max];

Comment: `null` has a specific meaning in C++ programming involving pointers; do you just mean objects with a value of 0? I ask because your sample code appears to treat them as values rather than as pointers, but you didn't include the definition of `arr` so I can't tell.
Comment: Can you add your bubble sort code also to the question? It will help people in providing answers.
Comment: Wherever you are doing the comparison in your code, instead of considering null to be smaller than everything else, consider it larger than everything else.
Comment: my comparisons are being made in my operator overload of < >, do i need to add some code in there stating that NULL > the strings that the objects are comparing and if so any suggestions?
Answer: You can just use std::sort with a custom comparator:
std::sort(std::begin(arr), std::end(arr), [](auto *p1, auto *p2) {
    if (p1 == nullptr) {
        return false;
    }

    if (p2 == nullptr) {
        return true;
    }

    return *p1 < *p2;
});

This assumes that your custom type defines operator<. You can, of course, use anything else you like to compare them.
If you have to implement your own sorting algorithm, you can still just inline the body of the comparator function into the middle the sorting code.
Comment: Thank you for your response, and ya i overloaded the < and > to deal with a string element of  the object. Some of this stuff seems  a bit more advanced then what we have learned, but i will look up some of the unknown stuff and try and add it to my code. thanks again.
Comment: Why limit which types the sort can be used for with `p1->operator<(p2)`? `*p1 < *p2` makes the code much more flexible.
Comment: @kfsone of course, you're right. It was a brain fart.
Answer: The function you are looking for could be std::partition, if all you want is to have the nulls at the back. If you also need sorting for the other values, std::sort is the right choice. Both allow you to define a comparison which defines the sorting or partitioning order, allowing you to customize how the elements are sorted.


upgrade pip fail: "python -m pip install --upgrade pip" was tried

Question: Command I input: pip install ipython
Output:
*Exception:
Traceback (most recent call last):
  File "c:\python27\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\python27\lib\site-packages\pip\commands\install.py", line 324, in run
    requirement_set.prepare_files(finder)
  File "c:\python27\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "c:\python27\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hashes)
  File "c:\python27\lib\site-packages\pip\download.py", line 821, in unpack_url
    hashes=hashes
  File "c:\python27\lib\site-packages\pip\download.py", line 659, in unpack_http_url
    hashes)
  File "c:\python27\lib\site-packages\pip\download.py", line 880, in _download_http_url
    file_path = os.path.join(temp_dir, filename)
  File "c:\python27\lib\ntpath.py", line 85, in join
    result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 7: ordinal not in range(128)
You are using pip version 9.0.3, however version 21.2.4 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.*

I tried the command it provided: python -m pip install --upgrade pip
it showed nothing. After that, I tried "pip install ipython" again the same error popped up.
Comment: Last pip version for Python2 is 20.3. https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Comment: You should really move to python3
Comment: Do you have python3 installed too?
Comment: Because the existing program has been developed on python2.7, I have to move on it on this version.
Answer: This was the case for me. By typing this command easy_install -U pip it worked for me.


Prove that $\exists x_0, x_1\in (0,1)$, such that $\frac{f'(x_0)}{x_0}+\frac{f'(x_1)}{x_1^2}=5$

Question:
Let $f:[0,1]\to\mathbb{R}$ be a differentiable function, such that
  $f(0)=0$ and $f(1)=1$. Prove that there exist different $x_0, x_1\in
(0,1)$, such that $$\frac{f'(x_0)}{x_0}+\frac{f'(x_1)}{x_1^2}=5$$

I have thought of possibly using Cauchy's theorem, so that we would only need to prove that there exist $k, l\in (0,1)$ such that $f(k)=k^2$ and $f(l)=l^3$, but I don't know how to prove these. Any hint?
Edit 1: Apparently my thought here is wrong, so any ideas?
Comment: How finding such $k,l$ would help you? $f(k) = k^2$ for some $k$ doesn't neccesarily mean that $f'(k) = 2k$
Comment: Interesting question, the only thing you for sure is that $f'(c)=1$ for some $c\in (0,1)$, but I'm not sure how to go from there.
Comment: @Stefan4024 Yes, you are right... But then the exercise becomes impossible!!!
Comment: The latter statement is not provable. Think of $f(x)=(x)$, then finding $k$ and $l$ such that $k=k^2$ and $l=l^3$ is not possible on $(0,1)$, and this will be the case for many more $f$'s
Comment: No correct solution here too, right?
Answer: Consider the function $g(x) = \frac{1}{3}x^3$. Then as it's differentiable on $(0,1)$ and continuous on $[0,1]$, by Cauchy Mean Value Theorem we have $\exists c \in (0,1)$, s.t.:
$$\frac{f(1) - f(0)}{g(1) - g(0)} = \frac{f'(c)}{g'(c)} \implies \frac{f'(c)}{c^2} = 3$$
Similarly now taking $h(x) = \frac{1}{2}x^2$, by Cauchy Mean Value Theorem $\exists d \in (0,1)$, s.t.:
$$\frac{f(1) - f(0)}{h(1) - h(0)} = \frac{f'(d)}{h'(d)} \implies \frac{f'(d)}{d} = 2$$
Hence the proof.
Comment: How can you show that $c$ and $d$ are different?
Comment: @Paolo I'm trying to prove but $c=d=\frac 23$ is the only "bad" point. Maybe proving that there exists yet another point such that it satisfies one of the equations.
Comment: I'm trying to prove that, too. But I don't know how, at the moment...


Contact form in content type

Question: I've made a content type User. Each user has a field email. I will not display the email but I would like a way for visitors to contact each user. So I am looking for a way to have a simple contact form inside a content type.
Any ideas?
Answer: If you use the module Email Field to create your email field you can set the field to be displayed as a contact form. You will find the setting to turn the field into a contact form under Display settings for the field.
Answer: You can refer the following modules in addition to Email Field, which performs similar function as you need
Email Contact

This module provides display formatters for the email field to display
email as a link to the contact form, or as an inline contact form.
Depends on the Email module.

Views Contact Form

Use cases
You need to create a block, an attachement or a page with a
custom URL with a contact form inside that will send an email to a
particular person (the recipient is taken from any field you want),
you will use this module, Views and/or Panels. You need to create
block that will send an email to the author of a content. You need to
create block that will send an email to an email field, referenced
through a reference in another content. Instead of displaying an email
field as an email link (with mailto:), display a contact form instead
and the recipient is taken from the field.
Answer: Contact Form On Node module add a contact form right under the node. You can choose:
<code>to add a contact form on teaser,
to add a contact form on full view,
to add a contact link on teaser,
to add a contact link on full view,
which content types these settings will apply to.
</code>
or
Author Contact Creates a block that shows a contact form that when submitted, sends a simple contact email to the author of the current node. This might be useful for a multi-user blog or auction site.
or
Node feedback offers a check box on the node form asking the author to allow the visitors of the node to send feedback/request for the node using the personal/site wide contact form. Author can choose which category will be selected when user request the node information or wish to give her/his feedback. Admin can select between the individual contact form and site wide contact form. This is ideal for social networking sites as well as sites maintained by a single user.

Contact form in content type


How to return custom JSON output in Django REST Framework

Question: I am trying to return custom json with the following structure
[ {
'yesterday': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

'today': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

'tomorrow': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}]
}]

The following is my code:
serializer.py
class GamesSerializer(serializers.Serializer):
    class Meta:
        model = AllGames
        fields = ('teams', 'start_time', 'pick',
                  'score', 'odds', 'won_or_lost', 'date')

class GamesViewSet(viewsets.ModelViewSet):
    today_date = date_picker

    yesterday = AllGames.objects.filter(
        date=today_date(-1)).order_by('start_time', 'teams')
    today = AllGames.objects.filter(
        date=today_date(0)).order_by('start_time', 'teams')
    tomorrow = AllGames.objects.filter(
        date=today_date(1)).order_by('start_time', 'teams')

    queryset = [yesterday, today, tomorrow]
    serializer_class = GamesSerializer

Current Output
[
    {},
    {},
    {}
]

How can I modify my GamesSerializer to return the custom output as shown above.
Answer: You can convert your response class from DRF ModelViewSet to ViewSet.
Then you can further parse your data before returning response, by overriding retrieve
As mentioned here: https://www.django-rest-framework.org/api-guide/viewsets/#example
Answer: For anyone trying to find the answer for this I used Viewset instead of ModelViewSet as suggested by @jay-vasant and then overrode list method above to customize the output like I wanted.
This is my GamesViewSet after update.
class GamesViewSet(viewsets.ViewSet):
def list(self, request):
    today_date = date_picker

    yesterday = AllGames.objects.filter(
        date=today_date(-1)).order_by('start_time', 'teams')
    today = AllGames.objects.filter(
        date=today_date(0)).order_by('start_time', 'teams')
    tomorrow = AllGames.objects.filter(
        date=today_date(1)).order_by('start_time', 'teams')

    queryset = [yesterday, today, tomorrow]
    games = []
    for day in queryset:
        serializer = GamesSerializer(day, many=True)
        games.append(serializer.data)
    return Response(games)

Output I get there after.
[
    [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

    [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],
    [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2",'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}]
 ]

Which is now close to what I wanted.


Combine Webforms to export multiple form results in a single CSV

Question: I need to be able to select multiple webforms and then be able to export all of their results in a single CSV download.
I am considering using this module (Views data export) but I'm not yet sure it will fit the task.
Any suggestions on the approach you would take would be appreciated.
UPDATE:
I approached this using the 'Webform Mysql Views' module but the process is incredibly time consuming as each Webform needs to have a view created for its submissions. These fields then need to be associated in the Webform Submissions view and duplicate fields need to be merged.
Answer: Webform 4.x is integrated out of the box with views on drupal 7.

Upgrade to last webform 7.x-4.x release.
Create a view: webform submissions
Select each field: webform submission data:Value and your webform node to extract the fields

To download all results the best option is Views data export, you should configure it to use batch for better performance.


Radical extension with root of cubic polynomial

Question: If I take $f(x)$ is an irreducible cubic  over $\mathbb{Q}$ with a root $\alpha$ in a splitting field and given that $\mathbb{Q}(\alpha)$ is a radical extension is it true that $\mathbb{Q}(\alpha) = \mathbb{Q}(b^{1/3})$ for some $b \in \mathbb{Q}$?
We have that $\alpha^q \in \mathbb{Q}$ for some $q$. I.e. $\alpha$ satisfies an equation $g(x) = x^q - b$ with $\alpha^q = b$. As $f$ is the minimal polynomial of $\alpha$ we must have $f$ divides $g$.
Now if it's the case that $q = 3$ then we'd have $f=g$ but that's clearly not the case in general. I'm not quite sure where I am going wrong here - or perhaps the original statement is false.
Another slight point of confusion is that it seems that $g$ is irreducible for any $b$ because it's splitting field is $\mathbb{Q}(\omega, b^{1/q})$ where $\omega$ is a primitive qth root of unity - that extension is Galois and acts transitively on the roots of $g$? But if that were the case then again we'd have $f=g$?
Thanks for any help clearing up this confusion!
Comment: Precisely what is a radical extension? Isn't the field of seventh roots of unity a radical extension? It has a subfield cubic over $\Bbb Q$ that definitely is not gotten by adjoining the third root of something. If you'd like me to expand this in an answer, just give the word.
Answer: The original statement is true.
We have that if $f$ is an irreducible cubic, and then $\mathbb{Q}(\alpha): \mathbb{Q}$ is radical. Then there exist, from the definition, $\beta_1, \ldots, \beta_n$ with
$$
\mathbb{Q}(\alpha) = \mathbb{Q}(\beta_1, \ldots , \beta_n),
$$
and for each $i$ we may assume there is some prime $p_i$ such that
$$
\beta_i^{p_i} \in \mathbb{Q}(\beta_1, \ldots, \beta_{i-1}).
$$
Then by the Tower Law  applied repeatedly to $[\mathbb{Q}(\beta_1,\ldots, \beta_n):\mathbb{Q}]$ we get
$$
[\mathbb{Q}(\beta_1,\ldots, \beta_n):\mathbb{Q}]$ = \prod_{i=1}^n[\mathbb{Q}(\beta_1,\ldots, \beta_i):\mathbb{Q}(\beta_1,\ldots, \beta_{i-1})] = \prod_{i=1}^n p_i.
$$
But then as $[\mathbb{Q}(\beta_1,\ldots, \beta_n):\mathbb{Q}] = [\mathbb{Q}(\alpha):\mathbb{Q}] = 3$, we see that, by prime factorisation, there is only one element $\beta$ with $\beta^3 \in \mathbb{Q}$ and
$$
\mathbb{Q}(\alpha) = \mathbb{Q}(\beta).
$$
But the important point is that this does not imply that $\alpha = \beta$, but instead that there are rational numbers $q_0, q_1, q_2$ with
$$
\alpha = q_0 + q_1 \beta + q_2 \beta^2.
$$
EDIT:
Because $\mathbb{Q}(\alpha)$ is a radical extension of degree 3, by the tower law analysis above we know that there is some $\beta$ which generates $\mathbb{Q}(\alpha)$.
Then the minimal polynomial of $\beta$ divides $x^3 - \beta^3$. But since $[\mathbb{Q}(\alpha):\mathbb{Q}] = 3$, then $[\mathbb{Q}(\alpha):\mathbb{Q}] = 3$, so the minimal polynomial of $\beta$ must be of degree 3 and so equals $x^3 -\beta^3$.
Comment: Thanks for your answer - so by the tower law any subfield of $\mathbb{Q}(\alpha)$ must be a divisor of 3 but then why is $\mathbb{Q}(\beta)$ a degree 3 extension?
Comment: Since $\beta$ is not in $\mathbb{Q}$, but $\beta^3$ is. So $x^3 - \beta^3$ is the minimal polynomial of $\beta$ over the rationals.
Comment: I'll edit my answer, maybe the use of the tower law isn't clear
Comment: Okay yes that is clear - how do we know that $f(x) = x^3 - \beta^3$ is irreducible? I think this is causing some of the confusion in my original post as well
Comment: We know that $x^3 - \beta^3$ is irreducible because we chose $\beta$ so that $\mathbb{Q}(\alpha) = \mathbb{Q}(\beta)$, then we must have $[\mathbb{Q}(\beta):\mathbb{Q}] = [\mathbb{Q}(\alpha):\mathbb{Q}] = 3$. Then this degree is the degree of the minimal polynomial of $\beta$ which clearly divides $x^3 - \beta^3$.
Comment: Sorry I'm still working through the details - If $\beta^p \in \mathbb{Q}$ with $\beta$ not in $\mathbb{Q}$ how do we know that $\mathbb{Q}(\beta)$ is a degree p extension? Surely that relies on showing $f(x) = x^p - \beta^p$ is it's minimal polynomial?
Comment: You don't, that statement you wrote is not true. BUT since $\mathbb{Q}(\alpha)$ is a radical extension of $\mathbb{Q}$ and is of degree 3, we know there is some $\beta$ with those properties. I edited the answer again.
Comment: Sorry - I'm still a little confused with this! If we don't know that $\mathbb{Q}(\beta)$ is a degree p extension in general - how did you apply this fact with the tower law at the start?
Comment: What I meant was that $\beta^p \in \mathbb{Q}$ but $\beta$ not in $\mathbb{Q}$ doesn't imply that $x^p - \beta^p$ is the minimal polynomial. But since we know from the tower law bit that $\mathbb{Q}(\alpha)$ is generated by one element $\beta$ with $\mathbb{Q}(\beta) = \mathbb{Q}(\alpha)$ we must have that (by the comment above) $[\mathbb{Q}(\beta):\mathbb{Q}] = 3$, so the minimal polynomial of $\beta$ is degree 3.


How to draw a lattice for the divisors of big numbers?

Question: An exercise ask to find atoms and join-irreducible elements for the set of divisors of 360. I know how to find them by drawing the lattice but it seems difficult in this case.
Is there another way to find atoms?
If not, is there a easy way to draw such a lattice?
Comment: I would be surprised if there isn't a nice characterization of what you're looking for. But to draw the lattice: It's essentially a $4 \times 3 \times 2$ box, due to the factorization of $360$ (three distinct primes, to various powers). To see what I mean, try to draw the lattice of divisors of $72 = 2^3 \cdot 3^2$ as a $3\times 2$ rectangle.
Answer: The join-irreducible elements are precisely the prime powers dividing $360$:
Let $d=p^k$ be a divisor of $360$. Then $d=a\vee b$ implies $a=p^k$ or $b=p^k$, so $d$ is join-irreducible. Conversely, let $d$ be a join-irreducible divisor of $360$ and write $d=a\times b$ with $\gcd(a,b)=1$. Then $d=a\vee b$ and hence $d=a$ or $d=b$, meaning that $b\mid a$ or $a\mid b$, respectively. This holds for every factorization $d=a\times b$ and hence $d$ is a prime power.
The atoms are the numbers with no nontrivial proper divisors, i.e. the primes.
Comment: It took me some time but now, when I'm solving lattice, problems is like I know kung fu. Thank You.
Answer: How to draw a lattice; I think it would get tricky if you had more than three prime divisors,  but $360$ is not too bad:


VIews Proximity Search Fields as Separate Block?

Question: Just a quick question, or if someone can point me in the right direction...
I have a website that needs to have a search field where customers can enter a service (e.g. photography) in one field, and a post code/zip code in the other so search for services near them.
To do this, I have  a content type for each service with addressfield, geofield and geocoder modules installed, and I have a view set up with an exposed filter criteria to filter the results.
This all works perfectly.
What I would like to do is have the filter criteria search in an external block at the top of every page (like the default drupal search block) that will show a list of results on a NEW page whenever a customer submits the form. Using my current method, I first have to direct customers to the page with the view on before they can search.
I experimented with the Search Configuration module (https://drupal.org/project/search_config) which lets you use the existing drupal search block, but can limit the results to only show one content type, which is perfect, but doesnt include the location post code field, and doesnt have the configuration of displayed results like views fields would do.
If anyone could offer up a bit of advice of where to go next I'd really appreciate the help.
Answer: If you are using drupal 7 You have an option to expose the filter as a block. and you can display the block in any region as you do all the other blocks. You would find this option under the advanced section in the views.
Please check the screenshot below


Hiding the scroll bar in WebView

Question: I want to hide a vertical scroll bar in my WebView when I do not scroll the page. As for now, it is displayed always. I create a WebView programmatically, so my question is related to customization of the scroll bar programmatically. Thanks!
Answer: try this code,
webView.setVerticalScrollBarEnabled(false);

Comment: Thank you. I was looking for exactly this – to give the in-app experience, rather than an in-an-iframe experience.
Answer: No need to change your Java code.
It will work if you put android:scrollbars="none" in your XML.
<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none" />

Answer: setScrollbarFadingEnabled() method does exactly what you want. It hides scrollbar when the view isn't scrolling.
webView.setScrollbarFadingEnabled(true);

Answer: Set scrollbars to none in the XML for WebView. For reference try this code.
<WebView android:id="@+id/webView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:scrollbars="none"/>

Answer: This is what you are after:
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

Answer: Try this -
For vertical scrollbar -
webView.setVerticalScrollBarEnabled(false)

For Horizontal scrollbar -
webView.setHorizontalScrollBarEnabled(false);

Answer: Similar to other answers but to get a scrollbar that behaves like the one in ListView, this is the code:
webView.setScrollbarFadingEnabled(true); // Explicitly, however it's a default, I think.
webView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

Answer: This finally worked for me:
mWebView.setVerticalScrollBarEnabled(false);

Comment: It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.

Hiding the scroll bar in WebView


Change in IAM role for EC2 instance not affecting already running EC2 instance

Question: I have an IAM role for EC2 instance (so called Instance Profile) with two policies attached, giving full access to SQS and S3. There is an EC2 instance running associated with this role. It runs several apps, that do use temporary credentials and everything is working fine.
Right now, one of my apps needs also access to SNS. I've modified IAM role, adding an Inline policy with policy generator, allowing certain API calls for particular SNS topic. However after modification of IAM role, when trying aws sns list-topics I get following error (respective arn's replaced with triple X):
User: XXX is not authorized to perform: SNS:ListTopics on resource: XXX:*

Does the addition of policy require instance to be restarted? Or do I have to wait for the temporary credentials (/latest/meta-data/iam/security-credentials/iam-role-name) to expire? Can I somehow force expiration of those credentials?
EDIT: The last question seems to be answered by IAM FAQ. Temporary credentials can't be reactivated or extended.
Comment: The FAQ also implies that what you're doing should work: *You can change the permissions on the IAM role associated with a running instance, and the updated permissions will take effect almost immediately.*  This (if true) contradicts an assumption I've been making that there was policy information embedded (and signed and encrypted) in the security token (otherwise, it's not clear why the token is needed).  If, when the temporary credentials expire, you can then access SNS, that will be interesting to know.  If not, that's potentially informative, as well. Wish I could offer more.
Comment: Out of curiosity, I just stopped and started an instance with an IAM role, without changing anything about the permissions associated with the role, to see what would happen to the temporary creds.  Before the reboot, my temporary credentials were not due to expire for several hours, and yet, after the reboot, they were completely reissued, with a new key, secret, token, and expiration time.
Answer: After many different approaches, it turned out that limiting my policy for a single queue was causing all the problems. I assumed that when policy applies to single queue and you do ListTopics, then you will get just the topic you have access to. However, my SNS had several other topics and most probably their existence in ListTopics result was considered a violation of policy. When I replaced particular topic name with '*' and saved the policy, then immidiatelly (no need for expiration of credentials or EC2 instance restarts) it started working.


How to insert value with new increment in codeigniter?

Question: public function myfuntion() {
    if($_POST){
        $urnno = "NU-62819100";
        $data = array(
                    "name" => $this->input->post('name'),
                    "email" => $this->input->post('email'),
                    "phone" => $this->input->post('phone'),
                    "urnno" => $urnno + 1
                );
        $sql = $this->db->insert('student',$data);
        if($sql){
            echo "success";
        }else{
            echo "fail";
        }
    }
    $this->loca->view('myform');
}

In this code I am simply insert form value but what happen here when I insert value then urnno must be auto increment after new insert like if when I insert value first time then urnno must be NU-62819101 second time it will be 102 then 103 like this. So, How can I do this? Please help me.
Thank You
Answer: You can first get the last urnno stored in the table, get its numerical part increment it and then save it in the table.
I've written a possible solution for your problem, comments are mentioned wherever necessary. See if it helps you.
public function myfuntion() {

    if($_POST){

        // get the last row saved in table
        $last = $this->db->select('urnno')->from('student')->order_by('id', 'DESC')->get()->row(); // id or some other auto incremented field

        // get urnno from the last row
        $last_urnno = $last->urnno;

        $last_arr = explode("-", $last_urnno); // make it an array to get the numerical part

        $new = $last_arr[1] + 1; // increment the value

        $urnno = "NU-{$new}"; // new value

        $data = array(
                    "name" => $this->input->post(''),
                    "email" => $this->input->post(''),
                    "phone" => $this->input->post(''),
                    "urnno" => $urnno // new value
                );

        $sql = $this->db->insert('student', $data);

        if($sql){
            echo "success";
        }else{
            echo "fail";
        }
    }
    $this->loca->view('myform');
}

Answer: if you only increment the column with value 1 then you can try with setting up the column auto incremented in database. it makes easier and remove unwanted calculations.


Excel VBA: find the union of two duplicate entries

Question: I am new to vba and I've got two updating columns of text & I want to find the union of the two columns.
For Example:
+---------+---------+
| A | B |
|    1    |    1    |
|    1    |    2    |
|    1    |    3    |
|    2    |    4    |
|    3    |    5    |
|    4    |    6    |
|    4    |    7    |
... so on
I want to write the result in a new column A, B, C ...
With column A

number 1, 1 to 3
number 2, 4 to 4 (if not duplicate at value column A)
number 3, 5 to 5
number 4, 6 to 7

like this :
+---------+---------+---------+
| A | B | C |
|    1    |    1    |     3   |
|    2    |    4    |     4   |
|    3    |    5    |     5   |
|    4    |    6    |     7   |
... so on
How to work out this? Thanks in advanced
Comment: Firstly, try to do something on your own. Then, if you don't mange to solve the problem, share what you have done and ask for help.
Comment: @braX I used to comment exactly in the same way and voted up a comment of such a type... But two weeks ago I have received a message from administrators. They warned me that the way I commented is not appropriate. I also used to say that *we do not offer free code writing services*, but they stated that **we really offer such services**. The question must be clear and proving that OP made some researches is only a bonus. Voting for closing in such a case is also not appropriate. After that I changed my way of commenting and acting, from this point of view...
Answer: Please, use the next code. It will return in columns E:F, starting with the second row.
<code>Sub extractMinMax()
  Dim sh As Worksheet, lastR As Long, arr, arrIt, arrFin, i As Long, j As Long, dict As New Scripting.Dictionary

  Set sh = ActiveSheet 'use here the necessary sheet
  lastR = sh.Range("A" & sh.rows.count).End(xlUp).row

  arr = sh.Range("A2:B" & lastR).Value2
  'place the range in a dictionay:
  For i = 1 To UBound(arr)
        If Not dict.Exists(arr(i, 1)) Then
            dict.Add arr(i, 1), Array(arr(i, 2))
        Else
            arrIt = dict(arr(i, 1))
            ReDim Preserve arrIt(UBound(arrIt) + 1)
            arrIt(UBound(arrIt)) = arr(i, 2)
            dict(arr(i, 1)) = arrIt
        End If
  Next i

  'process the dictionary content
  ReDim arrFin(1 To dict.count, 1 To 3)
  For i = 0 To dict.count - 1
     arrFin(i + 1, 1) = dict.Keys()(i)
      arrFin(i + 1, 2) = WorksheetFunction.min(dict.Items()(i))
      arrFin(i + 1, 3) = WorksheetFunction.Max(dict.Items()(i))
  Next i

  'drop the processed array content:
  sh.Range("E2").Resize(UBound(arrFin), UBound(arrFin, 2)).Value2 = arrFin
End Sub
</code>


wrap_content on recycleview, take height of item (horizontal list)

Question: I have a RecycleView, set to horizontal. Now i would like the height to match the height of an item in the view. I don't know the height in advance.
Currently i have this:
Main fragment:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="horizontal"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginTop="1dp"
        android:layout_gravity="top"
        android:id="@+id/my_listview"/>

</RelativeLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

The image
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/banner_image"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:background="@color/dark_gray"
    />

but it always takes up the entire screen. so i have a lot of whitespace in between. Is there a way that i could use wrap_content on the recycleview items?
This is what it currently looks like:

I have placed 2 banners currently, the top one with the big whitespace and small image is the one with the recyclerview. The one below is just the image placed in an imageview (is what it should look like, but i want it with a recyclerview so i can scroll through the banners if i have multiple)
Comment: What happens if you define your recyclerView with height as `wrap_content` and remove the `scaleType` and the `adjustViewBounds` from the `ImageView`?
Comment: you've defined your recyclerView with height="match_parent". What happens when you replace that with "wrap_content"?
Comment: Then it takes on the incorrect height, the banner measure about 60px in height but with wrap_content it would resize it to about 30 or something.
Comment: I have done that now, it stays the same. I updated my original post with an image of what it looks like
Answer:
Now i would like the height to match the height of an item in the
  view. I don't know the height in advance.

During layout pass, LinearLayoutManager cannot predict the height of all the views down in the adapter that are yet to be created, ahead of time.
You can measure() an item view, probably the first one, from the adapter and then set the height of RecycleView through code.
If all items can have different height then you'll have to measure them all, which is certainly not the correct way for a good UI.
Comment: The images all have the same dimensions
Answer: Is there a reason why you have the RecycleView wrapped inside a RelativeLayout ?
I would try to move the RecycleView out of the RelativeLayout first.
Secondly i see that your ViewPager has a layout_weight but i do not see a android:weightSum attribute in the parent layout. Is there a reason you are specifying the ViewPager to have a weight but not the RecycleView ? Have you tried fixing the size of the RecyleView to some dp to check if the arrangement is correct and the ViewPager is using the weight attribute correctly ?
Thirdly i would try to play around with the Imageview. Try maybe wrapping it inside a RelativeLayout maybe ? You will have to play around with the parameters there and see if it works out for you. Because you want something custom there is not a straight answer to this question.
Comment: Thank you for your reply, none of your suggestions seemed to work. when setting it to a fixed dp size, the whitespace seems to scale down respectively to the set dp.
Answer: You are probably inflating the layout incorrectly.
Did you use?
layoutInflater.inflate(R.layout.your_layout, null);

Try using instead. (The other way messes with measuring)
layoutInflater.inflate(R.layout.your_layout, parent, false);

Comment: I am currently using the following code to inflate it: `View v = LayoutInflater.from(mContext).inflate(R.layout.banner_item, parent, false);`
Answer: I also faced the same problem and I wanted to view two images in two columns with the same size in RecyclerView and I could solve the problem by using below code. Please try this.
// inner class to hold a reference to each item of RecyclerView
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView imgViewIcon;

        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
            int colSpan = 2;
            imgViewIcon.getLayoutParams().height = (int) (displayMetrics.widthPixels / colSpan);
            imgViewIcon.getLayoutParams().width = (int) (displayMetrics.widthPixels / colSpan);

        }
    }


How to make different users profile pages for different user types in Open Atrium2?

Question: I have 3 different user types and I want to provide a specific profile edit page for each. The user type is set when registering for an account. I have the profile fields associated to each user type created in config/people/accounts, but I'm lost on how to create the separate pages for each user type and then to trigger the loading of the correct page based on the users type.
Answer: I have not find a such module in the OpenAtrium bundle. You can use the contribute module https://www.drupal.org/project/profile2
Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
Comment: I'm only just beginning to grasp Page Manager and Panes and am thinking it could be done with PM and P with more display flexibility that with Profile2. But I'm unable to see where the profiles page is defined and so how to override it.
Comment: Panels it is the cool tool. But it has another reason. It charges of the layout system. The Profile2 module helps you to attach different types of node to users with with different roles. So **Panels** - layout, **Profile2** - data .


Point-free pattern matching possible in Haskell?

Question: Given:
data TwoInts = TwoInts Int Int

add'em :: TwoInts -> Int
add'em (TwoInts a b) = a+b

is it possible to write add'em without having to name a and b.  Something like:
 add'em TwoInts = (+) -- (Note: Fails to type check)

Comment: Possible: yes. Wise: not necessarily.
Answer: Via analogy to tuples,
data TwoInts = TwoInts { fst', snd' :: Int }

we can define an operation for lifting functions of two arguments onto a TwoInt
uncurry' f p =  f (fst' p) (snd' p)

Giving us the nice notation:
add'em = uncurry' (+)

Comment: @mathepic, uncurry can be written pointfree. `uncurry = ('ap' snd) . (. fst)`. The key is getting rid of pattern matching.
Comment: @mathepic it's much clearer with the points, imho. I once heard it said of Lisp (in reference to Lisp macros): you only have to write the same kind of ugly code once. If you consider pointful code as "ugly", then just write one "ugly" lifting function and then make use of it repeatedly thereafter.
Comment: As Conor McBride [points out](https://twitter.com/#!/pigworker/status/66797697436368896), idiom / applicatives help here too, `uncurry f = f <$> fst <*> snd` -- and is much simpler than the silly `(.)` version.
Comment: You could even make a type class for curryable things, so it could apply to more than just TwoInts...
Comment: I usually write that kind of thing as `f . fst <*> snd`, because it's faster to type. The <*> for the instance of Applicative selected here is a little bit like `DUP` in stack-based languages like FORTH.
Answer: In general I'd say no, it's not possible.  However, if you are trying to solve the practical problem of unwrapping and wrapping all over the place (especially common with newtypes), I often define a mapf f (Type val) = Type (f val) function, analogous to fmap, and then don't export it.  You can do the same for a n-ary data type just by passing more functions.  If the implementation isn't supposed to be secret, you can export it too (as fmap for unary).  I recommend either this kind of map function or views for complicated types because pattern matching will tie you to the implementation.
The basic types already have such functions defined, e.g. maybe and either.
Comment: `maybe` and `either` are actually a fold over the type (even if the datatype is not recursive, that's probably why they are not called folds), because it converts an object of that type into its Church encoding: you supply it a function corresponding to each constructor. To build the return value, calls to those functions replace calls to the constructors of the data type. Your `mapf` is very similar to `fmap`, but only for a type with 1 constructor having 1 parameter; otherwise the analogy to folds is more useful.
Comment: Why do you say that it is not possible in general? You can always define constructors and deconstructor functions to replace explicit pattern matching; and you can always translate a pointed Haskell function to an (arbitrarily complicated) pointfree version. So in general, it *is* possible.
Comment: Just a terminology thing, I thought he was looking for a solution that didn't require a helper function.  I.e. point-free *pattern matching*.  If you define a function then it's point-free functions.  Destructing a constructor always boils down to a case eventually, right? I suppose you could say practically speaking the generic programming stuff means you don't have to write a case, but only because the compiler put one in the automatic Data instance.


In a recursive DNA query procedure, if a local DNS server needs to query root DNS servers, how does it know/get their IP addresses?

Question: I am taking a computer networks class, and was wondering how a local DNS server knows the root DNS servers' IP addresses when querying them. I am assuming that since this is the root server, maybe there is a pre-provided root server address list for the local DNS, since a root server address can't be found from DNS servers from lower hierarchy, but I may be mistaken.
Answer: The list of root DNS servers is built into DNS servers usually as a configuration file. The list can also be downloaded to update installed and running DNS servers. This list is called "Root Hints".
Root Hints File
Comment: @BeowulfNode42 - The root servers are global ANYCAST clusters that can handle massive traffic. However, using forwarders is not related to the question asked. Depending on your architecture, you may want to offload resolution to other DNS servers such as Google or Cloudflare. If you specify DNS hostnames for the forwarders, then your DNS servers must start with the root servers to resolve those hostnames.
Comment: In an Windows DNS server it prefers using the IP addresses listed on the "Forwarders" tab in the DNS server properties, but will fall back to using the root hints if there are no forwarders available. Using the forwarders allows reducing the load on the internet's root hint servers and potentially improves your DNS speed by querying a closer server.
Comment: To add to this there is an important followup called root priming: even with the hardcoded internal list, on start, the software will contact any of these servers to download the current list, as names/IPs do change over time (albeit very slowly) which allows it then to continue working with updated data.


Replace body dots to spaces

Question: $('body, html').replace(".", " ");

I tried it, but this one doesn't work. I want to replace dots to spaces in the whole page.
Comment: This seems like a really bad idea.  Performance is going to be terrible unless this is a very small page.  If there are any assumptions you can make about the page, you may be able to do something more specific and not as slow.
Comment: One thing to consider. Do you want it to only replace in the text, or in the entire source. For example, it may break your page if it changes `style="width: 2.2em;"`.
Answer: Try replaceAll functionality. You want to make sure that you replace all elements and not just one.
Update: replaceText can be used to replace all text present in the element.
Comment: replaceAll replaces element nodes, not text within text nodes
Answer: Does jQuery have a .replace() method? You seem to be trying to use the String.replace() on a jQuery object.
You could try the following instead:
var $body = $("body");
$body.html( $body.html().replace(/\./g, " ") );

Or if you wanted to do it for a more select select of elements, say only those with a certain class:
$(".aCertainClass").html( function(i, oldVal) {
   return oldVal.replace(/\./g, " ");
});

Note that .replace() is using a regex with the g flag set so it does a global replace rather than just replacing the first match.
Note also that if you replace the body's html it effectively removes and recreates all your elements so it will kill any event handlers already bound - so do it before attaching your handlers.
Answer: If I got you, you want only change the dots into the text.
This function at http://jsfiddle.net/KmZ5A/ should do what you need:
  function searchDOM(element) {
      var items = [];
      items.push(element);
      var item;
      while (item = items.pop()) {
          if (typeof item != 'undefined' && item.nodeValue && item.nodeValue != null) {
              item.nodeValue = item.nodeValue.replace(/\./g,' ');
          }
          for (var key in item.childNodes) {
              var child = item.childNodes[key];
                  if (typeof child != 'undefined' &&
                      (child.nodeType == 1 || child.nodeType == 3)) {
                      items.push(child);
                 }
          }
          if (item.nodeName == "IFRAME") {
              if (!item.src) items.push(item.contentDocument.body);
          }
      }
      return null;
  }
  searchDOM(document.body);

Replace body dots to spaces


How to skip a date if it is generated in a loop?

Question: What this code does:
It generates dates based on a single day that is grabbed before ($date).
It counts always up one week. E.g. If your start date ($date) is 07.04.2019 it will generate the dates for $final_amount times.
So, if the start of the date is 07.04.2019 and $final_amount is: 5 it will output:
07.04.2019` (handled in separate code, as the first day is excluded in code!)
14.04.2019
21.04.2019
28.04.2019
05.04.2019

The issue with my code: I need to skip the date if it falls into a holiday. So if e.g. 21.04.2019 is a holiday, it should be skipped and replaced with a new date one week later. It should always have the amount $final_amount even if one ore more dates are laying on a holiday.
I have no Idea how this could be accomplished, as I am relatively new to PHP.
setlocale(LC_TIME, "de_DE"); //only necessary if the locale isn't already set
$date = new DateTime(helper('com://site/ohanah.date.format', array(
   'date' => $event->start,
   'format' => 'Y-m-d H:i',
   'timezone' => 'UTC'
)));

$date_scn = new DateTime(helper('com://site/ohanah.date.format', array(
   'date' => $event->end,
   'format' => 'H:i',
   'timezone' => 'UTC'
)));

$cnt = 2; // start the termin to count at two as the first one is already defined above
$raw_ticket_type = $event->ticket_types->name;
$filter_numbers = array_filter(preg_split('/\D/', $raw_ticket_type));
$filtered_numbers = reset($filter_numbers);
$first_occurence = substr($filtered_numbers[0], 0, 1);
$final_amount = $first_occurence - 1; // subtract 1 from $first_occurence as it is always one more

for ($i = 0; $i < $final_amount; $i++)
{ // loop
    $date->add(new DateInterval('P1W')); //add one week
    $formatted_time = utf8_encode(strftime("%A, %d. %B %Y, %H:%M", $date->getTimestamp()));
    $formatted_time_scnpart = utf8_encode(strftime("%H:%M", $date_scn->getTimestamp()));

    // This is the modal

    echo '
' . $cnt++ . '. ' . 'Termin' . '
' . $formatted_time . ' - ' . $formatted_time_scnpart . '
';
}

echo '

';

Comment: @RiggsFolly Your duplicate answers the title, but not the actual question. He doesn't want to exit the loop, he wants to skip that iteration.
Comment: @Barmar Woops, my mistake
Comment: Please do not use `utf8_encode`. It is for the most part a very useless function. There are definitely better ways of doing what you want to do.
Comment: What is the use of goes to operator in `$date-- > add(new DateInterval('P1W'));` Is this a typo?
Comment: @Dharman yes, thanks for pointing this out. I fixed it with an edit. It looks like I copy and pasted this wrong time ago. This was not in the real code.
Answer: You can use a while loop instead of the for loop. Then you can skip incrementing the counter if a condition is met.
$i = 0;
while ($i < $final_amount) {
    $date->add(new DateInterval('P1W'));
    if (is_holiday($date)) {
        continue;
    }
    $i++;
    $formatted_time = utf8_encode(strftime("%A, %d. %B %Y, %H:%M", $date->getTimestamp()));
    $formatted_time_scnpart = utf8_encode(strftime("%H:%M", $date_scn->getTimestamp()));

    // This is the modal

    echo '
' . $cnt++ . '. ' . 'Termin' . '
' . $formatted_time . ' - ' . $formatted_time_scnpart . '
';
}


angular material 2 on quickstart rc5

Question: I've been using angular2 rc 5 with ngModule
So right now I wanna use angular material. For example I wanna use angular2 material sidenav. I've been install it using npm

npm i @angular2-material/sidenav

then I put that angular 2 material on my systemjs-config.js
const map: any = {
  '@angular2-material': 'vendor/@angular2-material'
};

after that I imported the angular material in my ngModule
@NgModule({
  imports: [MdButtonModule, MdCardModule],
  ...
})

but I got an error

http://localhost:3000/node_modules/@angular2-material/button/ 404
  (Not Found)

is there some thing wrong with my code?
Comment: You are probably missing `packages` configuration in the `systemjs-config.js` Refer to [this](http://stackoverflow.com/a/39155382/4593335)  and [this](https://github.com/ajtowf/ng2_play/blob/master/src/system-config.ts) links for more details.
Answer: Your basic problem is that SystemJS doesn't know which file to import when it sees import {...} from '@angular2-material/button, so it tries to fetch the path that is returning the 404 error.  To fix:
1 Confirm that the path http://localhost:3000/node_modules/@angular2-material/button/ contains the button.js file.
2 In your systemjs-config.js file, add the setting that tells SystemJS how to import your Material packages:
var ngMaterialPackageNames = [
    'button',
    'card',
    //... any other Material packages you use
];

//tells SystemJS what file to load when a package name is imported
ngMaterialPackageNames.forEach(function(pkgName) {
    packages['@angular2-material/'+pkgName] = {
         main: pkgName+'.js', defaultExtension: 'js'
    };
});
...
// then later, do (you probably already have these lines)
var config = {
    map: map,
    packages: packages
};
System.config(config);

Comment: thanks, i tried it already but i got another error http://localhost:3000/node_modules/@angular2-material/core/annotations/field-value 404 (Not Found) is it the same?
Answer: I've finally found out how to load angluar material 2 with systemjs, and share this with you.
Get latest version(2.1.2) of ng2 from  angular 2 quickstart,
add these two in your package.json
 "@angular/material": "^2.0.0-alpha.9-3",
 "@types/hammerjs": "2.0.33"

Add to your systemjs.config.js
map: {
  // our app is within the app folder
  app: 'app',
    :
    '@angular/material': 'npm:@angular/material/material.umd.js',
    :

change your app.module.ts from
@NgModule({
      imports:      [ BrowserModule],

to :
 @NgModule({
      imports:      [ BrowserModule, MaterialModule.forRoot()],

Also you can add some css inside index.html. For more detail, pls see https://github.com/Longfld/ng2QuickStartForBeginning

angular material 2 on quickstart rc5


do_compile fails when building an image using the yocto-project "no such file or directory"

Question: I tried to append a layer from git (https://github.com/sigysmund/meta-lora-net) to my Image and whenever I try to bitbake one of the recipes (the other worked), I get this error message:
ERROR: lora-pkt-fwd-4.0.1-r0 do_configure: oe_runmake failed
ERROR: lora-pkt-fwd-4.0.1-r0 do_configure: Function failed: do_configure (log file is located at /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_configure.23440)
ERROR: Logfile of failure stored in: /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_configure.23440

(see last part for full message)
I have already tried to edit the bb file.
I changed the DEPENDS to "lora-gateway pkgconfig" instead of just the name since I read on another thread, that this can produce Issues but it didn't help.
This is the bb file of the recipe:
SUMMARY = "LoRa network packet forwarder project"
SECTION = "libs/network"
LICENSE = "MIT"
LIC_FILES_CHKSUM =                "file://LICENSE;md5=22af7693d7b76ef0fc76161c4be76c45"

SRC_URI = "https://github.com/Lora-net/packet_forwarder/archive/v${PV}.tar.gz"

SRC_URI[md5sum] = "a1f942e0cc7b02d604b11c8cb5f2a029"
SRC_URI[sha256sum] = "e68fadf6f1d2e5e7b601e504d5efb48b0a8f374c2c29c0476ab2fe9db68d33ae"

#old: DEPENDS += "lora-gateway"
# since new release of yocto you should add pkg-config
DEPENDS += "lora-gateway pkgconfig"

S = "${WORKDIR}/packet_forwarder-${PV}"

CFLAGS_append = "-I ${includedir}/libloragw -I ${S}/lora_pkt_fwd/inc -I ${S}/util_tx_test/inc "

do_configure_prepend() {
export LGW_PATH="${STAGING_LIBDIR}/libloragw"
}

do_compile_prepend() {
    export LGW_PATH="${STAGING_LIBDIR}/libloragw"
}

do_install() {
install -d ${D}${bindir}
install -d ${D}${docdir}/lora-pkt-fwd/conf

install ${B}/lora_pkt_fwd/lora_pkt_fwd ${D}${bindir}
install ${B}/util_*/util_* ${D}${bindir}

install -D -m 0644 ${S}/PROTOCOL.TXT ${D}${docdir}/lora-pkt-fwd/PROTOCOL.TXT
install -D -m 0644 ${S}/lora_pkt_fwd/readme.md ${D}${docdir}/lora-pkt-fwd/readme.md
install -D -m 0644 ${S}/lora_pkt_fwd/global_conf.json ${D}${docdir}/lora-pkt-fwd/global_conf.json
install -D -m 0644 ${S}/lora_pkt_fwd/local_conf.json ${D}${docdir}/lora-pkt-fwd/local_conf.json
install -D -m 0755 ${S}/lora_pkt_fwd/update_gwid.sh ${D}${docdir}/lora-pkt-fwd
install -D -m 0644 ${S}/lora_pkt_fwd/cfg/*.json.* ${D}${docdir}/lora-pkt-fwd/conf

rm -f ${D}${bindir}/util_tx_test
rm -f ${D}${bindir}/.debug/util_tx_test
}

PACKAGE_DEBUG_SPLIT_STYLE = "debug-without-src"

PACKAGES = "${PN}-dbg ${PN} ${PN}-doc"

# Avoid QA Issue: No GNU_HASH in the elf binary
INSANE_SKIP_${PN} = "ldflags"

FILES_${PN}-dbg = " \
    ${bindir}/.debug \
"
FILES_${PN} = " \
    ${bindir}/* \
"
FILES_${PN}-doc = " \
    ${docdir} \
"

the full error is:
ERROR: lora-pkt-fwd-4.0.1-r0 do_configure: oe_runmake failed
ERROR: lora-pkt-fwd-4.0.1-r0 do_configure: Function failed: do_configure (log file is located at /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_configure.23440)
ERROR: Logfile of failure stored in: /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_configure.23440

Log data follows:
| DEBUG: Executing python function sysroot_cleansstate
| DEBUG: Python function sysroot_cleansstate finished
| DEBUG: Executing shell function do_configure
| NOTE: make clean
| ERROR: oe_runmake failed
| make clean -e -C lora_pkt_fwd
| make[1]: Entering directory `/home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/packet_forwarder-4.0.1/lora_pkt_fwd'
| Makefile:17: /home/kilian/mlinux-4.x/build/tmp/sysroots/mtcdt/usr/lib/libloragw/library.cfg: No such file or directory
| make[1]: *** No rule to make target `/home/kilian/mlinux-4.x/build/tmp/sysroots/mtcdt/usr/lib/libloragw/library.cfg'.  Stop.
| make[1]: Leaving directory `/home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/packet_forwarder-4.0.1/lora_pkt_fwd'
| make: *** [clean] Error 2
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_configure (log file is located at /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_configure.23440)
ERROR: Task (/home/kilian/mlinux-4.x/layers/meta-custom/recipes-wireless/lora-pkt-fwd/lora-pkt-fwd_4.0.1.bb:do_configure) failed with exit code '1'
NOTE: Tasks Summary: Attempted 1590 tasks of which 1580 didn't need to be rerun and 1 failed.

Summary: 1 task failed:
  /home/kilian/mlinux-4.x/layers/meta-custom/recipes-wireless/lora-pkt-fwd/lora-pkt-fwd_4.0.1.bb:do_configure
Summary: There was 1 WARNING message shown.
Summary: There were 2 ERROR messages shown, returning a non-zero exit code.

I know that is has got something to do with the libloragw/library.cfg file but since that is imported and I don't know enough about these scripts, I can't find the error.
Any hint is really appreciated!
P.s I didn't include the logfiles since everything in there is already in the Log data follows part of the error. If you need it I can upload it.
Edit:
Thank  you jku, appending CLEANBROKEN = "1" fixed this error.
Sadly I am getting  a new one:
ERROR: lora-pkt-fwd-4.0.1-r0 do_compile: oe_runmake failed
ERROR: lora-pkt-fwd-4.0.1-r0 do_compile: Function failed: do_compile (log file is located at /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_compile.24486)
ERROR: Logfile of failure stored in: /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_compile.24486
Log data follows:
| DEBUG: Executing shell function do_compile
| NOTE: make -j 2
| ERROR: oe_runmake failed
| make all -e -C lora_pkt_fwd
| make[1]: Entering directory `/home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/packet_forwarder-4.0.1/lora_pkt_fwd'
| Makefile:17: /home/kilian/mlinux-4.x/build/tmp/sysroots/mtcdt/usr/lib/libloragw/library.cfg: No such file or directory
| make[1]: *** No rule to make target `/home/kilian/mlinux-4.x/build/tmp/sysroots/mtcdt/usr/lib/libloragw/library.cfg'.  Stop.
| make[1]: Leaving directory `/home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/packet_forwarder-4.0.1/lora_pkt_fwd'
| make: *** [all] Error 2
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_compile (log file is located at /home/kilian/mlinux-4.x/build/tmp/work/arm926ejste-mlinux-linux-gnueabi/lora-pkt-fwd/4.0.1-r0/temp/log.do_compile.24486)

So there is still a problem with the libloragw/library.cfg file
I did check and there is such a file in the recipe given by the DEPENDS variable so I guess that including that and the corresponding commands don't work
CFLAGS_append = "-I ${includedir}/libloragw -I ${S}/lora_pkt_fwd/inc -I ${S}/util_tx_test/inc "

do_configure_prepend() {
export LGW_PATH="${STAGING_LIBDIR}/libloragw"
}

do_compile_prepend() {
    export LGW_PATH="${STAGING_LIBDIR}/libloragw"
}

But I still don't know what to edit so any help is precious.
Answer: | DEBUG: Executing shell function do_configure
| NOTE: make clean
| ERROR: oe_runmake failed
| make clean -e -C lora_pkt_fwd

Yocto/OpenEmbedded tries to run "make clean" during configure to ensure a reproducible build but this particular project fails to do so cleanly. You can either fix the project (patching the Makefile) or add
CLEANBROKEN = "1"

in the recipe: this way OpenEmbedded won't run make clean on configure.
Comment: Hi, thank you for taking the time to read this. I did add the Cleanbroken line to the bb file but now i get a different error. Since it is too long for a comment, I will edit the question.


Terminal Server, Domain User can see folder and files saved in D: drive

Question: I want to set a Group Policy or something like that for old domain user and for new domain user, in a way that the domain user must not be able to see each other folder and files, if they login into same terminal Server
By default, Every Domain User login into Terminal Server, can open and read folder and files.I have two Drive C: and D:
User cannot see desktop of other User, but the folder saved in D: drive by User01 can be seen by User02 in read mode.
I want to deny this open and read folder rights for every domain user except the owner of the folder and files.
Can you help me? to figure it out.
Answer: Remove the BUILTIN\Users NTFS ACL from the path in question and add Creator Owner in its place.


How can I pass multiple values to drupal_view()?

Question: I'm on Drupal 8 and I have a view with multiple argument (list of node ID) but I can't embed this on my node.twig.html.
That's my code:
{% set myArray = [] %}
{% for item in content.field_articles_lies['#items'] %}
    {% set myArray = myArray|merge([item.entity.nid.value]) %}
{% endfor %}

{{ drupal_view('articles_lies','default', myArray()) }}

if I do that: {{ drupal_view('articles_lies','default', myArray.0) }}
it's ok but obviously only for one.
How can I pass an argument with multiple values to a view rendered via drupal_view() in a template?
Answer: You can't pass an array. You have to implode the array to a string first. And use '+' as glue for OR and ',' as glue for AND. Like '1+2+3' or '1,2,3'. And maybe you also have to enable Allow multiple values in your view (in the very bottom of the contextual filter screen).
I have try that and it works but I'm not sure it's very clear:
{% set arguments = '' %}
{% set i = 0 %}
{% for item in content.field_articles_lies['#items'] %}
    {% if i == 0 %}
        {% set arguments = item.entity.nid.value %}
    {% else %}
        {% set arguments = arguments ~ "+" ~ item.entity.nid.value %}
    {% endif %}
    {% set i = i + 1 %}
{% endfor %}

{{ drupal_view('articles_lies', 'default', arguments) }}


Solving for $x$ : $a^x+b^x=c$

Question:
Well the question is to solve for $x$ in $$a^x+b^x=c \tag{a,b,c are constants}$$

Well as of me, I tried to put $\ln{}$ on both sides which does not seem to help. Apart from this I don't seem to have any other way to solve it.
I turned to WolframAlpha and the solution which was given was :
$$x=\dfrac{-i(2\pi n +\pi)}{\ln{a}-\ln{b}} , {n \in \mathbb{Z}}$$
And if $n=0$ $$x=\dfrac{-i\pi}{\ln{a}-\ln{b}}$$
The only thing I am able to recognize is $e^{i\pi}=1$ ... i guess is used.
Link : http://goo.gl/da9G01
So I see that $x$ is independent of the constant $c$.
So how to solve it? Please help...Thanks!

EDIT - It seems that WolframAlpha is taking $c=0$ as suggested by Donkey_2009. And when i write "Solve for x in a^x + b^x = k" it is not returning anything. So are you guys aware of a method to solve this? Also are you guys aware of any other website/software like WA?

P.S. - Also I see that IF we know the values of $a,b,c$ resulting in something like $2^x+3^x=100$ , then Newton's method is the only method I am aware of that can solve it...
Any other suggestions?
Comment: Doesn't seem like the solution is, in general, constructible.
Comment: Has Wolfram ever been wrong before?
Comment: @user3728501 I guess once/twice. But ... its rare.
Comment: I have tested the page with much more simpler equations like $m=a\cdot x$. It seems that the web page is not supposed to solve equations.
Comment: @ajotatxe WolframAlpha is VERY much supposed to be able to solve equations....Try this : Solve for x in m=ax [Link: http://goo.gl/j5HAEm]
Answer: See edit below
I don't think the solution should be independent of $c$.  Maybe you typed into Wolfram
$$
a^x+b^x=0
$$
In that case, it's not too hard to see where the solution comes from.  Move $b^x$ to one side to get:
\begin{align}
b^x&=-a^x\\
&=(-1)\times a^x\\
&=e^{i\pi}a^x
\end{align}
Then take $\ln$ of both sides:
$$
x\ln(b)=i\pi +x\ln(a)
$$
from which it follows easily that
$$
x=\frac{-i\pi}{\ln(a)-\ln(b)}
$$
The other solutions come from using the fact that we have:
$$
e^{i(2n\pi+\pi)}=(e^{i\pi})^{2n+1}=(-1)^{2n+1}=-1
$$
so we can replace $e^{i\pi}$ with $e^{i(2n\pi+\pi)}$ above and get another solution.

If we no longer insist that $c=0$ then we won't get such a nice solution.  This is not unusual in mathematics.  Even nice polynomial equations like $x^5+x+1=0$ don't have solutions that can be written in terms of nice functions.

Edit: I've just see your link, and it looks as if you've misunderstood Wolfram's answer.  You typed in
$$
c=a^x+b^x
$$
and Wolfram Alpha interpreted this as $c$ being a function of $x$, where $a, b$ are constants.  The value
$$
x=\frac{-i\pi}{\ln(a)-\ln(b)}
$$
is listed as a root of this equation, i.e., a value of $x$ that makes $c$ equal to $0$.  So we are effectively solving
$$
a^x+b^x=0
$$
for $x$.
As an example, if you typed in
$$
y=x^2-5x+6
$$
then a root of this equation would be a value of $x$ such that $x^2-5x+6=0$.
Comment: Downvoters - any improvements I can make? :)
Comment: Check the link I gave :)
Comment: Do you know of any other websites/softwares which functions similarly to WA?
Comment: Why do you ask?  Are you unhappy with the answer you got from them?  As I have tried to explain, it is completely correct.
Answer: Not a solve, just an idea. This is for $a^x+b^x=0$ by the way.
$$a^x=-b^x$$
$$\log_ax=-\log_bx$$
$$\frac{\ln x}{\ln a}=-\frac{\ln x}{\ln b}$$
$$\ln a=- \ln b$$
$$x=\frac{-i \pi}{ln(a)-ln(b)}$$
$$x=\frac{-i \pi}{2\ln(a)}$$
$$2x\ln (a)=-i \pi$$
$$e^{2x\ln (a)}=e^{-i \pi}$$
$$e^{2x\ln (a)}=-1$$

Solving for $x$ : $a^x+b^x=c$


Get next and only class on click in the DOM

Question: I am trying to get the next class to show up when clicking on a more-infos span.
          Total Current Liabilities click
          <input type="text" name="currentratio2"  placeholder="$"></input>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum eligendi hic minus dicta atque molestiae, qui suscipit

          Total Current Assets click
          <input type="text" name="currentratio1"  placeholder="$"></input>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum eligendi hic minus dicta atque molestiae, qui suscipit

Ideally, when you click on a more-infos link it will show up the more-infos-container that is the closest to itself. How is that achievable ?
I tried using next and find and closest but it doesn't work.
Thank you .
Comment: possible duplicate of [Efficient, concise way to find next matching sibling?](http://stackoverflow.com/questions/4933236/efficient-concise-way-to-find-next-matching-sibling)
Answer: Use .nextAll() method:

$(function () {
    $('.more-infos').on('click', function (e) {
        var $info = $(this).nextAll('.more-infos-container').eq(0);
        alert($info.html());
    });
});

Total Current Liabilities click
<input type="text" name="currentratio2"  placeholder="$"></input>

Liabilities Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum eligendi hic minus dicta atque molestiae, qui suscipit

Total Current Assets click
<input type="text" name="currentratio1"  placeholder="$"></input>

Assets Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum eligendi hic minus dicta atque molestiae, qui suscipit


mysql - ordering by non standard date format

Question: I'm try to order some data in a database which in it's current format is set as dd/mm/yyyy. Is there a way I can replace the '/'s when selecting the results in the query?
i.e. in php i could use str_replace() and do it that way. I dont want to change the data in the table as it is used elsewhere within the site.
Comment: if at all possible, fix your schema to use the right datatypes.  This will only cause you problems later.
Answer:
Is there a way I can replace the '/'s when selecting the results in
  the query?

Yes, there is.  MySQL offers plenty of string functions.  Here's a simple example of how it works:
SELECT REPLACE(dateField1,'/','')
FROM myTable;

You also should be able to alter the data type using CAST to a SIGNED or UNSIGNED integer.
CAST(REPLACE(dateField1,'/','') as SIGNED)

Comment: you can also `order by REPLACE(dateField1,'/','')`
Comment: this will be marked as the correct answer as it does hat i asked but this doesnt help me. is there anyway to change the datatype on the fly?
Comment: I ended up doing CONCAT(SUBSTRING(pm.meta_value,-4),SUBSTRING(pm.meta_value,-6, 2),SUBSTRING(pm.meta_value,1, 2)) it's only a smaal page so not worried about performance.
Comment: Yeah, I was hoping he'd figure that one out on his own.
Comment: @PhilJackson edit made, if you still need to alter the data type.
Answer: Use STR_TO_DATE() to convert your string version of the date to a correctly useable date format.  I'd also recommend fixing your table structure so that this date is actually stored as a date, not a string.


Laravel and Flutter Notifications System

Question: I Want to Build a Web App with Mobile App in one platform. So, Both of Them will use the Same Database which is MySQL.
I want to use Laravel as backend and flutter for mobile app
Also, I want to build notifications system "when the user does something he will get pop up notification"
and that is the problem.
I searched a lot about this but I found nothing.
for Laravel, I can use Pusher and it's pretty easy.
but I didn't found anything to integrate it to flutter.
NOTE:
I'm beginner at flutter. But i'm good at laravel.
UPDATE
it's okey if there is any other method to do this
Answer: For flutter there is package called flutter_local_notifications,
link: https://pub.dev/packages/flutter_local_notifications
also there is pusher package
https://pub.dev/packages/pusher
so you can use these 2 together, so when a user trigger an event with API, a listener will send notification to pusher, so the other user would listen to it using pusher package.
At this moment you got the notification on your mobile using pusher package, only then you can trigger local notification using the other package instantly.


Cálculo de dias vem negativo. Por que?

Question: Fiz isso:
DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
int dias = (int)dt.Subtract(DateTime.Today).TotalDays;

Se fizer para o dia de hoje(26/01/2018) o resultado na var dias é:
-25
Só queria saber porque veio negativo, só entender mesmo.
Comment: Quanto é 1 - 26?
Comment: Sim, achei que ele pegasse a data atual e subtraísse do dia 1. Mas é ao contrário.
Comment: `int dias = (int)DateTime.Today.Subtract(dt).TotalDays;` essa seria a conta
Answer: Porque você está invertendo a ordem da sua comparação (para obter o resultado que espera):
DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
int dias = DateTime.Today.Subtract(dt).TotalDays;

Explicando:
O que você está fazendo é retornar a diferença em dias da data atribuída à variável dt e como na sua declaração de int dias você usa a data base ao substrair a data atual você está obtendo o valor negativo por "sobrar" dias.
Ex:

01/01/2018 - 26/01/2018 [em dias] = -25 dias (porque é uma data futura)

Cálculo de dias vem negativo. Por que?


Is data distributed as a Gaussian?

Question: I know there are methods to check whatever the observed data DOES NOT follow a Normal distribution. I'm thinking about chi-square test, Anderson test etc.
Is there any function/test/metric which says how Gaussian-like is the data distribution?
Thanks
Comment: The KS test *statistic* is a measure of departure from Normality.  Other distributional tests provide other statistics: they all measure departures from Normality differently, with some of them weighting the tails more or less heavily than the others.  I don't understand why you are challenging @Hunaphu, though: you explicitly ask for a "test" in the last line.
Comment: @marcodena: Re your comments under a now-deleted answer, the KS test statistic indeed has a different distribution when the parameters of the null-hypothesis Gaussian distribution are estimated from the same data. The KS test used in this case is often called the Lilliefors test, after the chap who first tabulated that distribution.
Comment: Can you define what you mean by 'how Gaussian-like'?
Comment: [Is the map the territory?](http://en.wikipedia.org/wiki/Map%E2%80%93territory_relation)
Comment: How about normalising and comparing the empirical cdf with the cdf of Gaussian?
Comment: @Łukasz That is precisely what the QQ plot suggested in Silverio's answer will do.  The related hypothesis test is the Kolmogorov-Smirnov test of distribution.
Comment: @whuber I answered to Hunaphu about the Kolmogorov test, expressing my dubts
Answer: Departures from the assumption of normality are not easy to quantify since they are not uniquely defined. For instance, the data may present departures from normality in terms of asymmetry, heavier tails, lighter tails, multimodality, et cetera.
The use of hypothesis tests does not provide evidence in favour of a hypothesis, for philosophical reasons.
There are some visual tools that you can use to see how close to normality your sample is, such as QQ-plots (against normal quantiles).
If you have a clue about the type of departure your data present (you can take a look at their histogram en 1-D), then you can try to fit a model that contains the normal distribution as a particular case, and see whether this is close to the normal distribution or not.  For instance, if your data seem to have heavier tails than normal and asymmetry, you could use some sort of skew-t distribution to fit your data (or some other distribution that contain the normal distribution as a limit case or a particular case). Then, take a look at the estimators of the degrees of freedom and the skewness parameter to see whether they indicate departures from the assumption of normality (e.g. if the estimator of the skewness parameter is very close to zero (or the one that reduces the model to symmetry) and the estimator of the degrees of freedom is large, then the data should look close to normal). You can also fit a normal model and calculate some distance/divergence between the flexible fitted model and the normal fitted model (e.g. Kullback–Liebler divergence, ...)
Comment: Marcodena, you can quantify the visual test by using the correlation coefficient of the coordinates of the normal qq-plot.  That will allow you to automate the process.  See [Filliben (1975)](http://www.claremontmckenna.edu/pages/faculty/MONeill/Math152/Handouts/filliben.pdf)
Comment: You talked about visual tests. What about the statistical ones? I need to test this for A LOT of different cases.
Thankkks
Comment: @marcodena If I had to do this multiple times, I would go for a likelihood ratio test (I am assuming the use of a model that contains the normal one) of the flexible model vs. the normal model. This should be doable and this is a UMPT.
Comment: @Silverio flexible model? Anyway I don't have the "normal one". Sorry, I'm bothering you :)
Answer: The Jarque-Bera test checks for kurtosis and skew that match the normal distribution.
http://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
Comment: The Wikipedia article on the Normal distribution lists several tests for Normality: http://en.wikipedia.org/wiki/Normal_distribution#Normality_tests

Is data distributed as a Gaussian?


Solving a system of 2nd order differential equations

Question: Given the
$\vec{x}''= \begin{bmatrix}-48 & 16\\32 & -32\end{bmatrix}\vec{x}$
I know how to solve this as a first order equation...Am I to take eigenvalues here? I tried visualizing them individually as second order equations but this confused me.
Comment: I found them here:

For $\lambda = -4$
\begin{bmatrix}-1 \\1\end{bmatrix}

For $\lambda = -1$
\begin{bmatrix}1 \\2\end{bmatrix}
Comment: You can diagonalize the matrix, solve the two equations of the diagonalized matrix independently and then find the solution of the original system by moving back to the standard basis using the eigenvectors of the matrix.
Answer: From the matrix system, you can get a system of equations:
$$x_1''=-48x_1+16x_2$$$$x_2''=32x_1-32x_2$$
We can turn it into:$$(x_1''+48x_1)-16x_2=0$$$$-32x_1+(x_2''+32x_2)=0$$
which is then (using basic definition for differential equations) $$(D^2+48)x_1-16x_2=0$$$$-32x_1+(D^2+32)x_2=0$$
Multiply the first equation by $D^2+32$ and multiply the second equation by 16, we get:
$$(D^2+48)(D^2+32)x_1-16(D^2+32)x_2=0$$$$-32(16)x_1+(D^2+32)(16)x_2$$
Add them together, the equation we get is $$(D^4+80D^2+1024)x_1=0$$
From here you can factor out D and get the general solution for $x_1$, then plug the value back into the original equation to get $x_2$
Comment: Did you mean to have $x_1$ outside of the parentheses on your 5th line?
Comment: Honestly I don't know if I really understand what's going on here. I factored out $D^2$ and got

$[D^2(D^2+80)+1024]x_1 = 0$
Answer: Using the "Ansatz" $x(t)=e^{\lambda t}(x_1,x_2)^T$ with $x_1$, $x_2$, and $\lambda$ yet to be determined we obtain the condition
$$x''(t)-Ax(t)=e^{\lambda t}\bigl((48+\lambda^2) x_1-16x_2, -32x_1+(32+\lambda^2)x_2\bigr)^T\equiv0\ .$$
This only admits a solution with $(x_1,x_2)\ne(0,0)$ if $\lambda$ solves the characteristic equation
$$\lambda^4+80\lambda^2+1024=0\ .\tag{1}$$
Fortunately we obtain four different solutions of $(1)$, namely $\pm4i$ and $\pm8i$. In order to obtain real solutions we therefore refine our "Ansatz" and write $x(t)=\cos(4t)(a_1,a_2)^T$. We then obtain the condition
$$x''(t)-Ax(t)=16\bigl(2a_1-a_2,-2a_1+a_2)^T\cos(4t)\equiv0\ ,$$
which is fulfilled when $a_2=2a_1$. It is easily seen that we obtain the same equation for $\sin(4t)$, so that we now have a two-dimensional space of solutions given by
$$x(t)=\bigl(a\cos(4t)+b\sin(4t)\bigr)(1,2)^T\ .$$
Now do the same  with $\cos(8t)$, resp., $\sin(8t)$, and obtain a second two-dimensional space of solutions in the form
$$x(t)=\bigl(c\cos(8t)+d\sin(8t)\bigr)(1,-1)^T\ .$$
Comment: I want to be able to express this as a system of two equations, but how can I do this when I have two $2 \times 1$ eigenvectors?
Comment: This  route is described in the comment of  Constantinos Vrohidis.


Ambiguous call between Google.Apis.Util.Utilities.GetStringValue(System.Enum) and Google.Apis.Util.Utilities.GetStringValue(System.Enum)

Question: I have this problem with the code posted on this site https://developers.google.com/drive/quickstart-cs is the Google's developers site for Google Drive the quickstart. I ran it as it is on the site and it runs well. The problem comes when I try to use that code, or parts of it, in a desktop app that I am developing for academic purposes (please help), which needs to upload files to Google Drive. Obviously I can't have the prompt calls they use in the example (such as Console.WriteLine("File id: " + file.Id); ). My question is how come it works fine on a basic promt app and when I try to reuse the code anywhere else is giving the error "ambiguous call between Google.Apis.Util.Utilities.GetStringValue(System.Enum) and Google.Apis.Util.Utilities.GetStringValue(System.Enum)"
Comment: Do you have two references to different versions of the same assembly, perhaps?
Comment: Wow! thanks a lot. I had the google.apis.silverlight reference... just deleted it and the red undrescoring went away. I know, rookie mistake. Thanks a lot!
Comment: well i tried to answer the question but because i am a newbie here i can´t. this is the text. The error was that, without thinking i added a lot of references to the project. within those was the google.api.silverlight reference. this was conflicting with another one, i still don't know which one but, for the sake of my deadline i will research the reasons later. Thanks a lot!
Comment: I'll write up an answer, for future reference.
Answer: If you get ambiguous calls to what appears to be the exact same method in the exact same fully-qualified type, that suggests that the same fully-qualified type name is exposed by two (or more!) assemblies that your project references.
In this case (as per the comments) you had references to both the Silverlight and "normal" desktop framework libraries.


Angle of rotation

Question: What angle of rotation is produced by the transformation $w=\sqrt {z}$ at the point
(a) $z_{0} = i$
(b) $z_{0} = -i$
(C )$z_{0} =3+4i $
$f'(z)=\frac{-1}{2\sqrt {z}}$.
a) $f '(i)=\frac{-1}{2\sqrt {i}}$. =$\frac{\sqrt {i}}{2i}$=$\frac{i\sqrt {i}}{2}$=$ \frac{i^(3/2)}{2}$.= $\frac{1}{2}   (e^{\frac{\pi}{2}i})^{3/2}$
$Arg ( f'(i)) =\frac{ 3\pi}{4}.$
|f'(i)|=1/2
b)  $f '(-i)=\frac{-1}{2\sqrt {-i}}$. =$\frac{\sqrt {-i}}{-2i}$=$\frac{-i\sqrt {-i}}{2}$=$ \frac{(-i)^(3/2)}{2}$.= $\frac{1}{2}  (e^{\frac{-\pi}{2}i})^{3/2}$
$Arg ( f'(-i)) =\frac{- 3\pi}{4}.$
|f'(-i)|=1/2
c) I do not know how to complete .
-It is true the solution
 a and b?
I appreciate and thank who helps me
Answer: There's a bit of an issue, here: $\sqrt z$ is ambiguous on the complex plane.
Let's start by writing $z=re^{i\theta}$ and $w=\rho e^{i\phi}$ for some non-negative real $r,\rho$ and some real $\theta,\phi.$ Without loss of generality, we may suppose that $-\pi<\theta\le\pi,$ but since we're trying to figure out what $w$ can look like, we cannot make any further assumptions about $\phi.$
Clearly, we need $z=w^2,$ so that $$re^{i\theta}=\rho^2e^{i2\phi}\tag{$\star$}$$ and applying the modulus to both sides of $(\star),$ we find $r=\rho^2,$ whence $\rho=\sqrt{r},$ and so $w=\sqrt{r}e^{i\phi}.$
Further assuming that $z\neq 0$ (so that $r>0$), we can conclude from $(\star)$ that $$e^{i\theta}=e^{i2\phi}.\tag{$\heartsuit$}$$
Here's where things go off the rails. Unlike the real exponential function, the complex exponential function is periodic, with fundamental period $2\pi i.$ Consequently, for any integer $k,$ we have $e^{i(\theta+2\pi k)}=e^{i\theta},$ so the best we can conclude from $(\heartsuit)$ is that $2\phi=\theta+2\pi k$ for some integer $k,$ so that $\phi=\frac12\theta+\pi k$ for said $k,$ and so $$w=\rho e^{i\phi}=\sqrt{r}e^{i\left(\frac12\theta+\pi k\right)}=(-1)^k\sqrt{r}e^{\frac12 i\theta}=\pm\sqrt{r}e^{\frac12 i\theta}.$$
The two possible definitions are known as branches of the function. What we will typically do, here, is to define $w=\sqrt{z}$ everywhere except on the ray starting at the origin and proceeding along the negative real axis (called a "branch cut"), using one of the two branches. In particular, since we'd like $\sqrt{z}$ to agree with the more familiar square root function defined on the non-negative reals, we will often choose what we call the principal branch: $$w=\sqrt{z}:=\sqrt{r}e^{\frac12 i\theta},$$ where $z=re^{i\theta}$ with $r>0$ and $-\pi<\theta\le\pi$ as above.
The answer that follows will assume this is how it is defined for you, and may well be incorrect if it is defined in another way.

Okay. Now that the caveats have been taken care of, here we go. Given any $z$ not on the branch cut mentioned above, we begin by writing $z=re^{i\theta}$ with $r>0$ and $-\pi<\theta\le\pi.$ Then we'll have $w=\sqrt{r}e^{\frac12 i\theta},$ and the (magnitude of the) angle of rotation will then be $$\left|\frac12\theta-\theta\right|=\frac12|\theta|,$$ in radians. In particular, this will be $\frac\pi4$ for the first two points, and $\frac12\arctan\left(\frac43\right)$ for the third.

Angle of rotation


Given a triangle's circumcenter, incenter, and midpoint of one side, construct its vertices

Question:
Wernick's list problem number 69: We want to find, with straightedge and compass, the vertices of triangle $\triangle ABC$ but we're only given:

its incenter, $I$
its circumcenter, $O$
the midpoint of side $a$, $M_a$

What I've done:

draw half line $OM_a$, $r$

draw $s$ perpendicular to $r$ passing through $M_a$ (this line contains side $BC$)

draw $t$:a parallel to $r$ passing through $I$

$Z = t \cap s$

draw circle $c$ centered at $I$ passing thorugh $Z$ (this is the incircle of $\triangle ABC$)

$Q = c \cap t \neq Z $

reflect $Z$ at the point $M_a$ to find $T$.

draw line $QT$ ($A$ is on this line).

I don't know how to finish. I suspect we can draw the radius of the circumcircle with Steiner porisms and that would end the problem.
Answer: You can indeed find the circumcircle:
draw $IP \perp IO$ such that $P$ is in the incircle already drawn (there are two possible points for $P$ but it doesn't matter which one you pick).
let line $OP$ meet the circle centered at $P$ passing through $I$ at point $X$ ($X$ the point most distant to $O$).
The circle centered at $O$ with radius $OX$ is the circumcircle of $\triangle ABC$.
This is a result that is based on the distance $OI^2 = R^2 -2rR$.
From this, we easily get $\triangle ABC$.
Comment: Yes, apparently Problem 69 was solved when Wernick's list first came out.  I guess the automated solver couldn't figure it out.  So you can breathe a sigh of relief.   Maybe you need to take the answer I gave you for Problem 82 with a grain of salt.  But many people had probably tried to solve 82 before that article came out.
Comment: I haven't checked your construction, but if it is valid you have solved something an automated effort did not. http://poincare.matf.bg.ac.rs/%7Evesnap/animations/construction_0285.html
Comment: I can't access your link. But my construction works and you can check it on geogebra quickly. Thanks for pointing it to me. I hope I'm not the first to draw it because it is not any profound new discovery
Comment: I thought so. I hesitated for a while before accepting your answer but the thruth is that problem seems a lot harder and after a little research and a couple tries I don't think anyone has an easy answer for that one in particular. I will keep your answer unless somebody magically come up with the correct answer


Simplify $(2^{2015})(5^{2019})$

Question:
Question : $(2^{2015})$$(5^{2019})$

How do I simplify/solve that without a calculator? I have no idea how to continue, I know it's important to get the Base number the same so I can add the exponents. I'd appreciate it if someone could teach me how to do this, without a calculator.
I also tried to do it algebraically by letting $x$ $=$ $2015$ and thus
$$ (2^x)(5^{x+4}) $$
but having trouble simplifying any further as I cannot get the same base..
Comment: hint $2\times 5 =?$
Answer: I believe that you can reduce the expression as follows:
$2^{2015}\cdot5^{2019}$
$=2^{2015}\cdot5^{2015+4}$
$=2^{2015}\cdot5^{2015}\cdot5^{4}$
$=(2\cdot5)^{2015}\cdot5^4$
$=625\cdot10^{2015}$
$=6.25\cdot 10^{2017}$
Answer: $$2^{2015}\cdot5^{2019} = 2^{2015}\cdot 5^{2015}\cdot 5^{4}=(2\cdot5)^{2015}\cdot 5^4$$
$$=10^{2015}\cdot (625)$$
Comment: There is no reason to downvote

Simplify $(2^{2015})(5^{2019})$


Probability: Secret Santa with Two donors / Person

Question: this is my first question here. I hope you can help me.
I want to do Secret Santa with my family with following modifications:

For each person there are 2 donors.
Only the 2 donors know from each other (so they can buy a gift together, too)

Practically it would go like this, 7 persons:

There are 7 cards with the names of the 7 persons.
First Round: Everybody draws a card, if it's the own name all have to draw again.
If it's a success the person who drew the name will be the persons first donor. He will write his name hidden inside the card - so that the second donor in the next round will know the other donor.
After this round every person has one donor.
Second Round: Again, everybody draws a card, but this time it can't be the own name NOR the person he already is donor for. Otherwise redo.
If it's a success everybody can keep the actual card. He is now the second donor and knows the first donor for this person.

I hope the situation is clear.
I wondered if I can calculate how many tries the group needs, especially for the second round / respectively what the probabilty is to get a working result.
I wrote an algorithm which gives me for the first round a probabilty of 1854/7!=0,37 and for the second round 1.073.760/(7!7!)=0,04.
I'm not sure if I've done a mistake.
The result would mean that the second round would be pretty horrible. 0,04, that means 25 repeats in average.
If I'm right, I'm also thankful for some ideas to fasten things up a bit.

Here's the code. I'm grateful for checking it. It's written in C#. Its form needs a richtextbox, a label and a button.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SuperSecretDoubleSanta
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int resultA = 0;
        private int resultB = 0;
        private int possibilitiesA = 0;

        private void button1_Click(object sender, EventArgs e)
        {
            int i = int.Parse(textBox1.Text);
            richTextBox1.Text = "";
            //Calculate the probabilty for 1 successful drawing
            richTextBox1.Text += calc(i, false) + "\r\n";
            possibilitiesA = resultA;

            //Calculate the probabilty for 2 sucessful drawings
            richTextBox1.Text += calc(i, true);
        }

        //startpoint for calculating the probabilty for 1 or 2 drawings
        private string calc(int numberOfPersons, bool drawtwotimes)
        {
            resultA = 0;//sucessful drawings in drawing 1
            resultB = 0;//sucessful drwaings in drawing 2

            draw(1, listAllPersons(numberOfPersons), new List<int>(),null, drawtwotimes,false);

            //Output for only 1 drawing
            if (!drawtwotimes) return "Drawing 1:\r\nProbabilty (for success): "+ resultA + "/" + numberOfPersons + "! = " + Math.Round((double)resultA / (double)factorial(numberOfPersons),2) + "\r\n";

            //Output for 2 drawings
            return "Drawing 2:\r\nProbabilty (for success): " + resultB + "/(" + numberOfPersons + "!"+numberOfPersons+"!) = " + Math.Round((double)resultB / ((double)factorial(numberOfPersons) * factorial(numberOfPersons)),2) + "\r\n";
        }

        //Main-Function

        public void draw(int drawingPerson, List<int> remainingPersons, List<int> drawnPersons, List<int> drawnPersonsB, bool drawtwotimes, bool isSecondDraw)
        {
            if (remainingPersons.Count == 1)//only 1 person left: gives result
            {
                if (remainingPersons[0] != drawingPerson)//The drawing person isn't allowed to draw himself.
                {
                    if (drawtwotimes)
                    {
                        if (!isSecondDraw)//do 2 Drawings. It's a successful Drawing 1.
                        {
                            drawnPersons.Add(remainingPersons[0]);//add the last drawn person

                            //now do Drawing 2
                            draw(1, listAllPersons(drawnPersons.Count), drawnPersons, new List<int>(), drawtwotimes, true);

                            //show progress
                            resultA++;//successful Drawing 1
                            label1.Text = resultA + " / " + possibilitiesA;
                            Application.DoEvents();
                        }
                        else if (remainingPersons[0] != drawnPersons.Last())
                            //the drawing person isn't allowed to draw the same person as in Drawing 1
                        {
                            //successful result
                            drawnPersonsB.Add(remainingPersons[0]);//could be printed...
                            resultB++;
                        }
                    }
                    else
                    {
                        resultA++;//only do Drawing 1. It's a successful draw
                    }

                }
                return;//last person has drawn
            }

            //traverse all remaining drawable persons
            foreach (int drawnPerson in remainingPersons)
            {
                if (drawnPerson == drawingPerson) continue;//person isn't allowed to draw himself
                if (drawtwotimes && isSecondDraw && drawnPerson == drawnPersons[drawingPerson-1])
                    continue;//person isn't allowed to draw the person from drawing 1 again.

                List<int> newdrawnPersonsA = new List<int>(drawnPersons);//list of drawn persons in Drawing 1
                List<int> newdrawnPersonsB;//list of drawn persons in Drawing 2
                if (!isSecondDraw)
                {
                    newdrawnPersonsA.Add(drawnPerson);//adds a drawn person in Drawing 1
                    newdrawnPersonsB=null;//not needed in Drawing 1

                }
                else {
                    newdrawnPersonsB = new List<int>(drawnPersonsB);
                    newdrawnPersonsB.Add(drawnPerson);//adds a drawn person in Drawing 2
                }
                List<int> newremainingPersons = new List<int>(remainingPersons);
                newremainingPersons.Remove(drawnPerson);//the next person can draw one person less: the actual drawn person

                //next person draws...
                draw(drawingPerson + 1, newremainingPersons, newdrawnPersonsA, newdrawnPersonsB, drawtwotimes, isSecondDraw);
            }
        }

        //generates a list with all persons
        public static List<int> listAllPersons(int numberOfPersons)
        {
            List<int> t = new List<int>(numberOfPersons);
            for (int i = 1; i <= numberOfPersons; i++) t.Add(i);
            return t;
        }

        //calculates 7! etc.
        public static int factorial(int c)
        {
            int e = 1;
            for (int i = c; i > 1; i--)
            {
                e *= i;
            }
            return e;
        }

    }
}

Comment: Your 0,37 is correct (1/e), and so I expect the second will be correct too. However, after the second one fails, you may also need to redo the first one. Because if I draw myself in the second round, I know 1 donor already. That means 25 * e = 68 repeats.
Comment: thx for your comment. the donor is written hidden inside the card (or in a folded paper), so the one who draws a card only reads the persons name he has to make a gift for. only if all persons don't draw their own names nor the names they already drawn have they can reveal (for themselves) the other donors name and contact him
Answer: What if you'd take 7 colors. Each person takes 2 notes of 1 color (secretly) and writes his name on the note and remembers his own color without telling.
When drawing, take 2 differently colored notes (not your own color).
You still my have some false drawings (e.g. for last person 2 notes left of same color or last person's color), but probably only a small amount.
Contextual information from drawings could be present, but probably not suitable for non-mathemagicians.
Hmm. does not work yet, to determine co-donor, after success, you need to write the co-donor on the notes, draw again, to keep this a secret.
Comment: the colored notes are a nice idea. But if I think about it... if my algorithm was right and the second round needs an average of 25 drawings, and 1 drawing takes 10 seconds (it's your name? - redo; it's the name you have already? - redo), then that's 25*10s. I think we have a new xmas ritual (if they want or not haha)
Comment: I'd like to share my code later for proofreading. Is C# ok for this board?
Comment: For me it is ;)
Answer: I'm afraid it is time to learn python, which has very powerful libraries for this kind of problems:
import itertools
import random

def derangements(n):
    'All deranged permutations of the integers 0..n-1 inclusive'
    return ( perm for perm in itertools.permutations(range(n))
             if all(indx != p for indx, p in enumerate(perm)) )

def different(d1, d2):
    'All elements of d1 and d2 are different req.(len(d1) == len(d2))'
    return (all(d2[indx] != p for indx, p in enumerate(d1)))

l7 = list(derangements(7))

success = 0
tried = 0
successes = []

for i1 in l7:
    for i2 in l7:
        tried = tried + 1
        if (different(i1,i2)):
            success = success + 1
            successes.append((i1,i2))

float(success) / (5040*5040)

print(random.choice(successes))

Which resulted in: percentage and sample:
0.0422713529856387
((4, 5, 6, 0, 1, 3, 2), (2, 0, 1, 5, 3, 6, 4))

Where we have the percentage and a sample with two derangements that have no element in common.
Comment: That's pretty cool. I will look into python. Also this valids my code. I have exactly the same result. Thx a lot. Xmas can come now.