Alguém poderia me ajudar com esse código? o resultado está saindo incorreto

Question: #include <stdio.h>

int main(){

  int salFixo = 0;

  int salFinal = 0;

  int vendas = 0;

  int comissao = 0;

  printf("Informe o salário fixo:\n");

  scanf("%d", &salFixo);

  printf("Informe o valor das vendas:\n");

  scanf("%d", &vendas);

  comissao = vendas * (4/100);

  salFinal = comissao + salFixo;

  printf("Seu salário final será de %d sendo %d de comissões.", salFinal, comissao);

}

As comissôes não estão sendo calculadas.
Answer: O que ocorre é que está usando int, e int somente suporta números inteiros ("numeros sem virgula").

Então, se você faz: (4/100) isso é 0. O que você espera é que isso seja 0.04, mas como virgula não é suportado, isso é "arredondado para baixo".

Altere todos os int pra double ou float para que suporte casas decimas, ou faça um cast disso:
int main(){
    int salFixo = 0;
    printf("Informe o salário fixo:\n");
    scanf("%d", &salFixo);

    int vendas = 0;
    printf("Informe o valor das vendas:\n");
    scanf("%d", &vendas);

    float comissao = (float) vendas * (4.0F/100.0F);
    float salFinal = comissao + (float) salFixo;

    printf("Seu salário final será de %f sendo %f de comissões.", salFinal, comissao);
}

Note que, neste caso, usamos float e usamos 4.0F e 100.0F para indicar que isto é float. Usar o (float) vendas não é necessário, poderia usar somente vendas, o compilador faz a conversão (até onde eu sei). Mas converter explicitamente deixa mais claro o nosso intuito.

Se quiser pode passar tudo pra float/double e usar o F:
int main(){

    // Altera tudo pra float:
    float salFixo = 0;
    float salFinal = 0;
    float vendas = 0;
    float comissao = 0;

    printf("Informe o salário fixo:\n");

    scanf("%f", &salFixo);  // Altera para %f

    printf("Informe o valor das vendas:\n");

    scanf("%f", &vendas);   // Altera para %f

    comissao = vendas * (4.0F/100.0F); // Altere para 4.0F e 100.0F

    salFinal = comissao + salFixo;

    // Altere para %f
    printf("Seu salário final será de %f sendo %f de comissões.", salFinal, comissao);
}

Tanto float quanto double tem problemas de precisão, então se o valor estiver "errado", veja outras perguntas do SO que respondem isso.
Comment: muito obrigado pela explicação.
Answer:     #include <stdio.h>

int main(){

  int salFixo = 0;

  int salFinal = 0;

  int vendas = 0;

  int comissao = 0;

  printf("Informe o salário fixo:\n");

  scanf("%d", &salFixo);

  printf("Informe o valor das vendas:\n");

  scanf("%d", &vendas);

comissao = (vendas/100*4);

  salFinal = comissao + salFixo;

  printf("Seu salário final será de %d sendo %d de comissões.", salFinal, comissao);

}

Não sei exatamente onde estava o erro (não estudo C), mas mudei como a variavel de "comissao" estava sendo calculada e deu certo.
Comment: também ainda não sei onde esta o erro, mas mudar a forma que a variavel é calculada realmente ajudou. Obrigado


IPv6 Gateway outside network (OVH)

Question: We a dedicated server at OVH, assigned 2001:41d0:a:72xx::/64
I have set the machines on a segment bridged to the wan, as per
IPv6 public routing of virtual machines from host
The gateway is 2001:41d0:a:72ff:ff:ff:ff:ff, outside the network
We're running a bunch of virtual debian servers.
Some of our (older) servers are happy to route ipv6 to the gateway, but the new I'm trying to setup are saying ."Destination unreachable; Address Unreachable" when pinging the gw.
Firewall is setup equally (rules for /64, not on host-level), and /etc/network/interfaces are equal; ipv6 are set static. (different adresses of cause)
On both working and non-working machine, netstat -rn6|grep eth1 show
2001:41d0:a:72xx::/64          ::                         U    256 2    40 eth1
2001:41d0:a:7200::/56          ::                         UAe  256 2    71 eth1
2001:41d0:a1:72xx::/64         ::                         UAe  256 0     0 eth1
2000::/3                       2001:41d0:a:72ff:ff:ff:ff:ff UG   1024 2 63479 eth1
fe80::/64                      ::                         U    256 0     0 eth1
::/0                           fe80::205:73ff:fea0:1      UGDAe 1024 1     2 eth1
::/0                           fe80::20c:29ff:fe22:60f8   UGDAe 1024 0     0 eth1
ff00::/8                       ::                         U    256 2108951 eth1

On the non-working machines, pinging the gw or the workd returns "Destination unreachable."
The machines can all reach each other on the local lan.
I don't know if it is relevant, but
ping -c3 ff02::2%eth1
64 bytes from fe80::20c:29ff:fedb:a137%eth1: icmp_seq=1 ttl=64 time=0.240 ms
64 bytes from fe80::20c:29ff:fe22:60f8%eth1: icmp_seq=1 ttl=64 time=0.250 ms (DUP!)
64 bytes from fe80::2ff:ffff:feff:fffd%eth1: icmp_seq=1 ttl=64 time=3.57 ms (DUP!)
64 bytes from fe80::2ff:ffff:feff:fffe%eth1: icmp_seq=1 ttl=64 time=5.97 ms (DUP!)

On the non-working
ping -c3 ff02::2%ens34
PING ff02::2%ens34(ff02::2%ens34) 56 data bytes
64 bytes from fe80::20c:29ff:fedb:a137%ens34: icmp_seq=1 ttl=64 time=0.130 ms
64 bytes from fe80::20c:29ff:fe22:60f8%ens34: icmp_seq=1 ttl=64 time=0.138 ms (DUP!)

The :fffd amd :fffe addresses missing.
All the ipv6-addresses have been assigned at OVH control panel.
TL;DR: Something must be different between the old and new servers, but I can't find it.
UPDATE: A clone of a working machine does not work.
On the outside of the pfsense, set up as bridge, the machine sends this:

    12:33:23.087778 IP6 test1.example.org > fe80::2ff:ffff:feff:fffe: ICMP6, neighbor advertisement, tgt is test1.example.org, length 32
    12:33:24.106302 IP6 test1.example.org > par10s28-in-x0e.1e100.net: ICMP6, echo request, seq 451, length 64

But nothing ever gets back. Pings from outside doesn't go through either.
As the machine is an exact clone of a working machine, except for the ip-addresses, it must be an upstream problem at OVH.
UPDATE 2
Now OVH claims that to get data routed to an IPv6, the mac need to be associated to an IPv4 address. OMG The working IPv6's are not.
Comment: Actually, you can have a gateway address that's on a "different" subnet, as long as the gateway is directly attached, and you have an interface route for that destination. In fact, you *do* appear to have such an interface route, for the prefix `2001:41d0:a:7200::/56`, which your desired gateway actually falls into. If those routes exists on both hosts, then I'm not sure what the difference might be yet.
Comment: Can you update the question details to provide the routing table for the non-working host as well?
Comment: A gateway must be on the same network as the host because it is the host on the network that knows how to forward traffic off the network. You would need a gateway to get to the gateway, and it doesn't work that way.
Comment: Tell that to OVH, that's the way they have set it up.
It works for some of my hosts,
Comment: @guzzijason, actually, even if I set the routing address to the same on non- as on working, it doesn't help.
Comment: How exactly did you set up virtual networking?
Comment: A pfsense bridging wan to separate network with second nic on each machine running static ipv6 gateway set to the OVH router. But it seems it's the OVH-router not answering to all my ip's. I've opened a ticket.
Answer: OVH does not know how to do IPv6 properly, their setup only works in certain situations, not applicable everywhere.
It only works without special hoop-jumping when the servers are exposed to the world and also have public IPv4-addresses.
They can't supply one public ipv6 and a subnet routed to it, which is needed if one wants to run VM's behind ones own firewall.
Until they get their stuff working, it is better to look elsewhere, if you are interested in IPv6.
Answer: OVH runs switch port security on their switches, so that only whitelisted MAC addresses can use any given port. This doesn't apply to vRack; switch port security is disabled on vRack. But OVH won't let you route IPv6 subnets to vRack yet. Nor can you failover an IPv6 subnet to another server. This is a critical oversight; until both of these capabilities exist, OVH's IPv6 support is considered limited.
So this is how I've set up an OVH server running a few dozen virtual machines:
On the host server, br3 is a bridge containing eno3 and virtual network interfaces on which I route IPv6. The host is configured as:
# cat /etc/sysconfig/network-scripts/ifcfg-br3
DEVICE="br3"
TYPE="Bridge"
STP="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_FAILURE_FATAL="no"
NAME="br3"
ONBOOT="yes"
ZONE="public"
BOOTPROTO="static"
IPADDR="203.0.113.24"
PREFIX="24"
GATEWAY="203.0.113.1"
IPV6_AUTOCONF="no"
IPV6ADDR="2001:db8:1f3:c187::/64"

I have static routes configured as such:
# cat /etc/sysconfig/network-scripts/route6-br3
2001:db8:1f3:c187::/64 dev br3
2001:db8:1f3:c1ff:ff:ff:ff:ff dev br3
default via 2001:db8:1f3:c1ff:ff:ff:ff:ff dev br3

I then run ndppd, which answers NDP neighbor solicitation queries for any address in my /64. It's configured as such:
# cat /etc/ndppd.conf
route-ttl 30000
proxy br3 {
   router yes
   timeout 500
   ttl 30000
   rule 2001:db8:1f3:c187::/64 {
      static
   }
}

This causes the MAC address of the host to be used for all IPv6 addresses in the subnet, which I then route to virtual interfaces in libvirt, split into /80 networks. One example is configured as such:
# cat /etc/libvirt/qemu/networks/v6bridge_1.xml

<network>
  <name>v6bridge_1</name>
  <uuid>7007a2b2-08b8-4cd5-a4aa-49654ae0829b</uuid>
  <forward mode='route'/>
  <bridge name='v6bridge_1' stp='on' delay='0'/>
  <mac address='52:54:00:fc:d4:da'/>
  <ip family='ipv6' address='2001:db8:1f3:c187:1::' prefix='80'>
  </ip>
</network>

All VMs in this particular network are assigned manual IPv6 addresses, but you could set up DHCPv6 if you wanted. That would look like:
  <ip family='ipv6' address='2001:db8:1f3:c187:1::' prefix='80'>
    <dhcp>
      <range start="2001:db8:1f3:c187:1::100" end="2001:db8:1f3:c187:1::1ff"/>
    </dhcp>
  </ip>

I then route IPv4 failover addresses to the vRack, which is bridged to a single bridge br4 on eno4 that all my VMs get a second virtual NIC from. Thus they have IPv6 on one interface and IPv4 on another. This is optional; you could just keep IPv4 failover addresses on your main interface (if you don't have a vRack, for instance).
Comment: So the host server is the esxi or my pfsense (running as a vm on the esxi) ?
Comment: @Lenne Oops, I see nothing about your hypervisor in your question, and I (apparently wrongly) assumed you were using KVM. The general comments about OVH's network design and how to work around it still apply though. Though I don't think you can run ndppd on any hypervisor other than KVM, and it's a critical part of making this work.
Comment: I finally gave up. When I made OVH look into why some hosts worked and some didn't, they made all equal, so now noone working?!?
So now I have made a IPv6 tunnel to HE instead.

IPv6 Gateway outside network (OVH)


Continuous on $\{0\}$ but discontinuous at $0$

Question:
Define a function $f$ on the subset $\{0\}\cup\bigcup\left\{\left(\frac1{n+1},\frac1n\right)\middle|\ n\in\mathbb N\right\}$ of $[0,1]$ as follows:
  $$ f(x) = \begin{cases}
1, &\text{if $n\in\mathbb N$ and $\frac1{2n+1}<x<\frac1{2n}$}; \\
-1, &\text{if $n\in\mathbb N$ and $\frac1{2n}<x<\frac1{2n-1}$}; \\
0, &\text{if $x=0$}.
\end{cases} $$
The function $f$ is constant, and therefore certainly continuous, on each of the intervals that make up its domain, including the degenerate interval $\{0\}$. But $f$ is not a continuous function; although it is continuous at every other point of its domain, it is not continuous at $0$.

In the above example, $f$ is continuous on the interval $[0,0]$, but is discontinuous at $0$. Firstly, does that make sense? Secondly, why is there a discontinuity at $0$? Is it because the intervals $(1/(n+1),1/n)$ become progressively closer to $0$, but alternate between function values of $-1$ and $1$, so there is no limit as $x\to 0$? As a counter-argument, surely we only take the open intervals $(1/(n+1),1/n)$ so that $\{0\}$ is an isolated point.
Answer: Any function defined on a point $x_0$ is continuous on the "interval" $\{x_0\}$.
This is because, by definition, a function is continuous on $\{x_0\}$ if:

For every $\epsilon >0$, there exists $\delta >0$ sucht that for every $x\in \{x_0\}$ such that $|x-x_0|<\delta$, we have $|f(x_0)-f(x)|<\epsilon$.

This condition is simple to acchieve, since we only have one $x\in\{x_0\}$, and for that $x$, $f(x)-f(x_0)=0.$

The function is not continuous at $0$ because it is not true that:

For every $\epsilon >0$, there exists $\delta >0$ sucht that for every $x\in \mathcal D(f)$ such that $|x-x_0|<\delta$, we have $|f(x_0)-f(x)|<\epsilon$.

You can see this by setting $\epsilon =\frac12$ and showing that no matter what $\delta$ you pick you can always find an $x$ such that $|x-0|\leq \delta$ and $|f(x)-f(0)|>\epsilon$. Specifically, if you take $x$ to be between $\frac{1}{2n}$ and $\frac{1}{2n-1}$, you will have $|f(x)-f(0)|=1$.
Comment: Thank you for your answer. I am still hoping for an answer to my second question.
Comment: @ahorn I added that answer too.
Answer: The text is saying that the restriction of $f$ to each of the intervals that make the domain is a continuous function; the reason is that all these restrictions are constant.
So, yes, (the restriction of) the function can be continuous on $\{0\}$  without the function being continuous at $0$. More precisely, (the restriction of) the function is continuous on $\{0\}$ like any (restriction of a) function defined at $0$.
Why is the function not continous at $0$? Because you can find points arbitrarily close to $0$ where the function differs from the value at $0$ by more than $1/2$.
The situation would be different if the domain of $f$ is the union of open intervals over which the function is continuous; then $f$ would be globally continuous.
Comment: @ahorn More precisely, you can't represent the domain as the union of open intervals.
Comment: Are the intervals in the domain of $f$ not all open because $\{0\}$ is a non-open interval included in the domain? Specifically, does you last statement hold because $\inf \bigcup\{(1/(n+1),1/n)|n\in \mathbb N\}=0$ and $\{0\}$ is included in the domain?


The sum of a number and its reciprocal is 5 (1/5) . Find the number.

Question: The sum of a number and its reciprocal is 5 (1/5) . Find the number.
I found the answer to be:
x+(1/x)=5(1/5)
(x^2 + 1)/x= 26/5
and so on...
Now, I am trying to figure out how a number multiplied by a fraction could lead to 26 and that would only happen by adding a whole number to the fraction 5+(1/5).
But that is not the case here, right? I don't understand why 5(1/5) is suddenly calculated as 5+(1/5)? What am I missing out on? Thank you in advance for any clarification.
Comment: What does $5(1/5)$ mean? Does it mean $5+\frac15$?
Comment: You can cross-multiply to get $5(x^2 + 1) = 26x$, then solve the resulting quadratic.
Comment: @N.F.Taussig, that doesn't seem to be the difficulty the OP is having.
Answer: If I understand correctly, the question probably looked like this:

The sum of a number and its reciprocal is $5\frac{1}{5}.$ Find the number.

When writing a positive rational number, one way of doing so is called a "mixed number," where we write the integer part, followed by the fractional part. In this case, while the numbers $5$ and $\frac{1}{5}$ are written next to each other, this is not intended to indicate multiplication, as it would if one or both of them were a variable, but rather, addition. So, $5\frac{1}{5}$ signifies $5+\frac{1}{5}.$
Interestingly, this gives us one solution to the problem immediately, because we need to solve the equation $x+\frac{1}{x}=5+\frac{1}{5},$ which clearly has $x=5$ as a solution. On the other hand, we can observe that the substitution $x=\frac{1}{t}$ yields $\frac{1}{t}+t=5+\frac{1}{5},$ or equivalently, $t+\frac{1}{t}=5+\frac{1}{5},$ so $t=5$ is a solution, and so $x=\frac{1}{5}$ is the other solution to the initial equation!
Comment: @Ibti, if it were written as $5\left(\frac{1}{5}\right),$ then I would interpret it as implicit multiplication, instead, yes. To see how to write things in math mode on this site, you can right click and select "Show Math As->TeX Commands." That will show you what to put between the dollar signs so that other people aren't confused by your posts' typesetting.
Comment: Thank you truly much for the clarification! So, if it clearly said 5 * 1/5, that would be a whole number multiplied by a fraction. Otherwise 5 (1/5) is just a mixed number that would be calculated as 5+(1/5) as you said.
Comment: @lbti: 5(1/5) isn't a normal or approved  way of writing $ 5\frac15$ I would interpret it as multiplication, as does WolframAlpha.
Comment: @Ibti, if it has parentheses (as you wrote), rather than simply having the two numbers concatenated (as I wrote), then I would interpret it as multiplication, instead. However, if the text instead has $5\frac{1}{5},$ then I *would* interpet it as a "mixed number."
Comment: No, I just can't write the the fraction 1/5 like you on this page so I wrote it with parenthesis. Otherwise it's originally without parentheses, just like you wrote in your answer. But if the fraction is originally in parentheses 5(1/5) it would be interpreted as multiplication?
Answer: $$5\frac12=5+\frac12=\frac{11}2=5.5\neq(5)(\frac12)\left(\text{which is}=5\times0.5=\frac52=2.5\right)$$
Basically, mixed fraction is just a way to write $\frac{11}2$ informing that we need $5$ wholes and a half.
And given sum of number and it's reciprocal as $5\frac15$ then it's quite obvious that one solution is $x=5$ (and the other is $x=\frac 15$). Seen simply by comparing $x+\frac1x=5+\frac15 (\text{or }\frac15 + 5)$.


Cisco DSCP based packet drop

Question: On a Cisco router, when setting up a policy-map to shape traffic and drop packets based on DSCP (such as the example below), which class of packet will be dropped first: DSCP 0 or AF13?  DSCP AF13 is described as most likely to be dropped, yet DSCP 0 is described as "best effort", which one will win?
<code>policy-map mypolicy
 class class1
  shape average 128000
  random-detect dscp-based  <-- which will be dropped first, DSCP 0 or AF13?
</code>
Answer: Here's some good documentation from Cisco about DSCP: http://www.cisco.com/en/US/docs/ios-xml/ios/qos_dfsrv/configuration/12-4t/qos-dfsrv.html.
There may very well be something I'm missing, so hopefully someone else can verify this (not a CCIE, yet), but the important bit to know is how these DSCP values map to the binary values, and what AF (Assured Forwarding) is.
DSCP 0 (decimal value 0) would be 000000 in binary.  For AF, you can see that document for more details, but AF13 would be 001110, which is 14 in decimal.
However, it does not go directly off of the decimal value.  If you do not specify any other configurations there, it will use the defaults.  You can find these in this table: http://www.cisco.com/en/US/docs/ios/12_2/qos/command/reference/qrfcmd7.html#wp1070240.
So, DSCP 0 (default in that table) would be more likely to be dropped in that the threshold where it could be dropped begins at 20% vs 24% for AF13.
Comment: So if you change the default thresholds, you can change the drop rate of any of the DSCP to anything you want.  Fascinating.  Excellent link!  It looks like the 20% and 24% are not percents but the minimum packets in the queue before packets will start randomly dropping, with 20 and 24 packets respectively.

Cisco DSCP based packet drop


Script para fazer aparecer uma div

Question: Tenho um cadastro de usuários em minha aplicação, quando clico em cadastrar queria que mostrar uma mensagem. Esse tratamento todo eu já estou fazendo e jogando a mensagem na minha ViewBag.Message. Como faço pra mostrar essa DIV ao clicar no botão cadastrar ?
Comment: se você mostrar a div, a mensagem já vai aparecer automaticamente ?
Comment: Sim, pois a minha ViewBag.Message fica dentro da div.
Answer: Após clicar em cadastrar, você tem algumas maneiras de mostrar a div:
1ª -> $("#idDiv").show();
2ª -> document.getElementById('idDiv').style.display = 'block';
3ª -> $("#idDiv").css("display", "block");
Acredito que a primeira funcione.
Answer: Você pode verificar se a ViewBag.Message não está vazia, então exibir uma mensagem.
Abaixo segue um exemplo usando o jQueryUI:
Controller
using System;
using System.Web.Mvc;

namespace SampleApp
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string mensagem)
        {
            ViewBag.Messagem = mensagem;
            return View();
        }
    }
}

View
@{
    Layout = null;
    var mensagem = string.Empty;
    if (ViewBag.Messagem != null) {
        mensagem = ViewBag.Messagem.ToString();
    }
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
        <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/flick/jquery-ui.css" />

        @using (Html.BeginForm())
        {
            <input type="hidden" name="mensagem" value="Hello World!"></input>
            <input type="submit" value="Enviar" />
        }

        @if (!String.IsNullOrWhiteSpace(mensagem)) {

        }

Note que o método exibirMensagem só é chamado se ViewBag.Messagem possuir um valor.
Segue um fiddle:
DotNetFiddle

Script para fazer aparecer uma div


Symfony 4 Doctrine multiple table joins in one property

Question: Very new to symfony and Doctrine. I have the following tables in my database.
mo_user
id   |    email      |   password
__________________________________
9144 | email@example.com  |   !password!

mo_user_role
user_id| role_id
_________________
9144   | 5

mo_permission
id | namespace            | name | description
______________________________________________
1  | admin                | -    |   -
2  | users                | -    |   -
3  | view_summary_report  | -    |   -
4  | view_user_statement  | -    |   -

mo_role_permission
role_id  | permission_id
________________________
    5    | 3
    5    | 4

I am trying to return an array of the permissions of the current user in this case user with id = 9144 which should be array('view_summary_report','view_user_statement').
I have mapped all the tables to their corresponding entity classes. and in MoUser.php entity class which corresponds to mo_user table, I have a
permissions method which should return the array but my join from annotations is failing,
My getPermissions() method in MoUser.php
/**
 * @var Collection|MoPermission[]
 * @ORM\ManyToMany(targetEntity="App\Entity\MoPermission")
 * @ORM\JoinTable(
 *     name="mo_user_role",
 *     joinColumns={@ORM\JoinColumn(name="user_id",referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="role_id",referencedColumnName="id")}
 * )
 */
private $permissions;

 public function getPermissions()
{
    $currentPermissions = array();
    foreach ($this->permissions->toArray() as $index => $permission) {
        $currentPermissions[] = $permission->getNamespace();
    }

    //Return default role if Roles are not assigned to this user.
    if(count($currentPermissions)>0) {
        return $currentPermissions;
    } else {
        return array('DEFAULT_PERMISSION');
    }
}

So I figured out the raw sql to achieve what I wanted which is below, but I would like to know the Symfony/Doctrine annotated way of achieving the following raw SQL.
 SELECT t0.id AS id_1, t0.namespace AS namespace_2, t0.name AS name_3, t0.description AS description_4

 FROM mo_permission t0

 LEFT JOIN mo_role_permission ON t0.id = mo_role_permission.permission_id

 LEFT JOIN mo_user_role ON  mo_role_permission.role_id = mo_user_role.role_id

 WHERE mo_user_role.user_id = 9144;

Answer: I don't think there is a proper way to achieve what you're trying to do directly through property annotations with your current setup.
You could achieve what you want with one of these solution though :

One of mo_user_role and mo_role_permission is not needed, since none of them have additional field. You should just have a mo_user_permission table generated by a ManyToMany relationship between MoUser and MoPermission, which would grant you direct access to MoPermission from MoUser's getPermissions()
Another way would be to create a service which would have a GetPermissionsFromUser(MoUser $moUser) method (for example), calling the proper query from the entity's repository, which you would call when needed.
You could still achieve what you want in your getPermissions() method with your current setup, but you would have to loop through each relation's items to build your new result array manually.

e.g. for last point :
public function getPermissions() {
    $permissions = [];
    foreach($this->roles as $role) {
        foreach($role->getPermissions() as $permission) {
            permissions[] = $permission->getNamespace();
        }
    }
    return $permissions;
}

This would assume you have a MoRole entity, which would make sense regarding your current setup, but you didn't mention it. Otherwise, same logic could still be applied though, it's just a naming matter.
Comment: Thank you, Ill try It out, I do have a MoRole entity. thank you
Comment: Thank you, for me the last bullet point was the easiest to implement. marked it as a correct answer.
Comment: Glad it fixed your problem. Keep in mind other ways for future work.
Answer: I'm pretty sure that you could do that query using Doctrine (and a QueryBuilder) like...
use Doctrine\ORM\EntityRepository

class PermissionRepository extends EntityRepository
{
    //....

    /**
     * @param UserInterface $user
     * @return array|Permission[]
     */
    public function getPermissionsForUser(UserInterface $user)
    {
        $queryBuilder = $this->createQueryBuilder('permission');

        /**
         * permissions will be in a multi-dimensional array
         * with a single key per array of 'namespace'
         */
        $permissions = $queryBuilder
            ->select('permission.namespace')
            ->join('permission.role', 'role')
            ->join('role.user', 'user')
            ->where($queryBuilder->expr()->eq('user', ':user'))
            ->setParameter('user', $user)
            ->getQuery()
            ->getArrayResult();

        if (count($permissions) > 0) {
            /**
             * If there are any permissions found just return
             * the 'namespace' property from each "sub-array"
             */
            return array_column($permissions, 'namespace');
        }

        return ['DEFAULT_PERMISSION'];
    }

    //...
}

And then you would call it like..
$permissions = $repository->getPermissionsForUser($user);


Problem with submenus

Question: I am new at Drupal , and I am using version 7.43. I have already installed Bootstrap, and now I am defining the menus. But to realize Multilevel submenus I need the folder of bootstrap_subtheme
I searched but I couldn't find that folder, I found just the Bootstrap folder.
Any hints?
Answer: Create such sub-theme folder manually. The folder name you'd use for it will be the machine name of your subtheme.
For more details, refer to:

"Creating a sub-theme" (= Community documentation that applies to any sub-theme).
"Sub-theming" (= documentation about sub-theming specific to Drupal's Bootstrap theme).

If you prefer to look at a great (I think) example of a (contributed) Bootstrap sub-theme, then have a look at the Bootstrap Business theme.

Problem with submenus


How can I change an ImageView after a ListActivity?

Question: The idea is to go to a ListActivity, click on an item, and if you clicked on item X it displays an especific image.
That's my Android code.
package vds.cmc;
public class Dae extends ListActivity {
static final String bigfoot[] = {"Boy", "Girl"};

ImageView iv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setListAdapter(new PeopleAdapter(this, bigfoot));
    iv = (ImageView) findViewById(R.id.ivID);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    String qlo = bigfoot[position];
    try {
        if (qlo == "Girl") {
            setContentView(R.layout.ppl);
            iv.setImageResource(R.drawable.cw);
        }
        else {
            setContentView(R.layout.ppl);
            iv.setImageResource(R.drawable.no);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

}

How should I do it? Or how do I fix it?
Thank you, I'm pretty new at this.
Answer: Spawn off a new activity to view the image.
    Intent intent = new Intent(this, ImageViewerActivity.class);
    intent.putExtra(EXTRA_IMAGE_ID, R.drawable.boy); //could also pass the resource
    startActivity(intent);

and then
public class ImageViewerActivity extends Activity {
    private static final String EXTRA_IMAGE_ID = "ImageViewerActivity.EXTRA_IMAGE_ID";
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();
    if (extras == null) {
        return;
    }

        Resource resId = extras.getInt(EXTRA_IMAGE_ID);
        mImageView.setImageDrawable(resId);
}

Answer: You've extended ListActivity, so it means that the activity only has a ListView and nothing more.
You can do any of the next things:

Create a new activity that will show the image.
Use fragments, while one shows the ListView and one shows the image , and switch between them.
Use setContentView twice, one before choosing (to show the ListView) and one after (to show the image).
Use a different layout, which you switch between the ListView and the ImageView (via visibility or via using ViewSwitcher) .

I'm sure there are other ways too.


Drupal 7 image styles ignored by theme preprocess function

Question: I want to display images at the proper image style-defined size, but there's a problem being caused by a preprocess function written by the person who built this site before I came onto the project.
function abc_field__field_video_thumbnail($variables) {
    $output = '';

    // Render the items
    foreach ($variables['items'] as $item) {
        $output .= "
\r";
        $output .= 'field_video_width['und'][0]['value'] . '" data-popup-height="' . $variables['element']['#object']->field_video_height['und'][0]['value'] . '">';
        $output .= '' . "\r";
        $output .= '' . "\r";
        $output .= "\r\r";
        $output .= "
\r\r";
}

    // Render the top-level div
    $output = '
' . $output . '
';

    return $output;
}

This seems to assume the image style processing would occur before this function happened, but unfortunately it doesn't, and I get a full-size image regardless of image style.
Answer: By taking over the display of that field you're actually bypassing all the field system would usually do to apply the custom display settings; it basically passes off the responsibility of creating the field HTML to you, and provides you with the raw values you'll need to build it up.
So if you want to output a style based image, you'll need to do it manually using theme_image_style():
$args = array('style_name' => 'thumbnail', 'path' => $item['#item']['uri'], 'alt' => 'Alt text');
$image = theme('image_style', $args);

// Append $image to your output...


Mtaplotlib issue with spyder 4.0.1

Question: I have upgraded my spyder to 4.0.1 , but now i get this error with matplotlib. The error:
AttributeError: module 'sip' has no attribute 'setapi'
complete error:
NOTE: The following error appeared when setting your Matplotlib backend!!
Traceback (most recent call last):
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\spyder_kernels\console\kernel.py", line 568, in _set_mpl_backend
    get_ipython().run_line_magic(magic, backend)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\IPython\core\interactiveshell.py", line 2317, in run_line_magic
    result = fn(*args, **kwargs)
  File "", line 2, in matplotlib
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\IPython\core\magic.py", line 187, in
    call = lambda f, *a, **k: f(*a, **k)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\IPython\core\magics\pylab.py", line 99, in matplotlib
    gui, backend = self.shell.enable_matplotlib(args.gui.lower() if isinstance(args.gui, str) else args.gui)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\IPython\core\interactiveshell.py", line 3419, in enable_matplotlib
    pt.activate_matplotlib(backend)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\IPython\core\pylabtools.py", line 320, in activate_matplotlib
    from matplotlib import pyplot as plt
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\pyplot.py", line 2282, in
    switch_backend(rcParams["backend"])
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\pyplot.py", line 221, in switch_backend
    backend_mod = importlib.import_module(backend_name)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\importlib__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 11, in
    from .backend_qt5 import (
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\backends\backend_qt5.py", line 15, in
    import matplotlib.backends.qt_editor.figureoptions as figureoptions
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\backends\qt_editor\figureoptions.py", line 12, in
    from matplotlib.backends.qt_compat import QtGui
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\backends\qt_compat.py", line 163, in
    _setup()
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\backends\qt_compat.py", line 124, in _setup_pyqt4
    _setup_pyqt4_internal(api=2)
  File "C:\Users\premp\anaconda3\envs\tfcuda\lib\site-packages\matplotlib\backends\qt_compat.py", line 107, in _setup_pyqt4_internal
    sip.setapi(_sip_api, api)
AttributeError: module 'sip' has no attribute 'setapi'
Currently i have matplotlib 3.2.1 , i have tried downgrading and also tried changing the setting from automatic to inline. But not able to figure out the issue. Is this a bug?
Answer: As I understand you are running your command in a virtual environment.
I had similar issue with matplotlib 3.3.2, on windows 10, when running the command on my virtual environment:
<code>(base) (venv) C:\Users\Samtha\Documents\automation_tool>python -c "import matplotlib.pyplot as plt"
</code>
It gave AttributeError: module 'sip' has no attribute 'setapi'.
Tried the mentioned solution here: enter link description here
<code>(base) (venv) C:\Users\Samtha\Documents\automation_tool> python -c "import matplotlib;matplotlib.use('TkAgg');import matplotlib.pyplot as plt"
</code>
and it works now.
Comment: It works for me too.  Do you know why this happen and whether this will be fixed permanently by any party?
Answer: I had a similar problem and fixed it by adding the sip module to my anaconda environment.
Comment: This seems like such a silly fix, but it did the trick for me, without all the hacking around in rc files mentioned in other solutions.

Mtaplotlib issue with spyder 4.0.1


How do I work around the ActiveX WebBrowser flaw in a WPF Window that AllowsTransparency=true

Question: I'm building an application that I've created a custom skin for all windows and dialogs; each window has a customized "X" button in the upper right-hand corner, among other things.  I've essentially set WindowStyle=None and AllowsTransparency=True. I have a tab control within this window, and one of the tabs has a WPF WebBrowser Control. When I first started out, I didn't have custom skinning on the windows, and the web browser controls worked as expected. Once I skinned the windows and set AllowsTransparency=True, and the WebBrowser Controls just show a blank white page now.
I understand that there is some sort of said flaw in ActiveX that is causing this, since the WebBrowser WPF Control is essentially a wrapper. Can someone please provide a decent solution or a decent workaround for this issue?
The following is my xaml and screenshots. I've simplified it down into a simple Window for the sake of this post:
This works: (AllowTransparency=False)
<Window x:Class="AllowTransparencyIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="500"
        Width="700"
        AllowsTransparency="False"
        WindowStartupLocation="CenterScreen"
        WindowStyle="SingleBorderWindow"

        >
    <Border BorderBrush="Blue" BorderThickness="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Button Grid.Row="0" HorizontalAlignment="Right" Click="Button_Click">Close Window</Button>

            <TabControl Grid.Row="1">

                <TabItem Header="StartPage.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.startpage.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Google.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Bing.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

            </TabControl>
        </Grid>
    </Border>
</Window>

Screenshot:

The following code sets AllowsTransparency=True and WindowStyle=None:
<Window x:Class="AllowTransparencyIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="500"
        Width="700"
        AllowsTransparency="True"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"

        >
    <Border BorderBrush="Blue" BorderThickness="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Button Grid.Row="0" HorizontalAlignment="Right" Click="Button_Click">Close Window</Button>

            <TabControl Grid.Row="1">

                <TabItem Header="StartPage.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.startpage.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Google.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Bing.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

            </TabControl>
        </Grid>
    </Border>
</Window>

Screenshot:
Answer: I found a post that appeared to be redundantly copied and pasted all over the web. The post helped me with my issue, but I decided to improve upon it and package it a bit cleaner. Also, the original code in the post didn't work when I used it in a TabControl.
Here is a link to the original post I found:
http://social.msdn.microsoft.com/Forums/en-US/41088e8f-800d-4a29-a693-d9edf1682c0f/c-wpf-winforms-web-browser-styling?forum=wpf
The solution above calls for creating a Window that hosts a Windows Forms WebBrowser Control in a WindowsFormsHost object that will essentially overlay itself on top of a border control.
Here is my improvement to the solution:
WebBrowserOverlayWindow.xaml:
<Window x:Class="AllowTransparencyIssue.WebBrowserOverlayWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WebBrowserOverlayWindow"
        xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        WindowStyle="None"
        ShowInTaskbar="False"
        ResizeMode="NoResize">
    <WindowsFormsHost x:Name="wfh">
        <winForms:WebBrowser x:Name="wfBrowser" />
    </WindowsFormsHost>
</Window>

WebBrowserOverlayWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AllowTransparencyIssue
{
    ///
    /// Interaction logic for WebBrowserOverlayWindow.xaml
    ///
    public partial class WebBrowserOverlayWindow : Window
    {
        public WebBrowserOverlayWindow()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register("TargetElement", typeof(FrameworkElement), typeof(WebBrowserOverlayWindow), new PropertyMetadata(TargetElementPropertyChanged));
        public FrameworkElement TargetElement
        {
            get
            {
                return GetValue(TargetElementProperty) as FrameworkElement;
            }
            set
            {
                SetValue(TargetElementProperty, value);
            }
        }

        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(WebBrowserOverlayWindow), new PropertyMetadata(SourcePropertyChanged));
        public string Source
        {
            get
            {
                return GetValue(SourceProperty) as string;
            }
            set
            {
                SetValue(SourceProperty, value);
            }
        }
        private static void SourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var webBrowserOverlayWindow = sender as WebBrowserOverlayWindow;

            if (webBrowserOverlayWindow != null)
            {
                webBrowserOverlayWindow.wfBrowser.Navigate(args.NewValue as string);
            }
        }

        private static void TargetElementPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var oldTargetElement = args.OldValue as FrameworkElement;
            var webBrowserOverlayWindow = sender as WebBrowserOverlayWindow;
            var mainWindow = Window.GetWindow(webBrowserOverlayWindow.TargetElement);

            if (webBrowserOverlayWindow != null && mainWindow != null)
            {
                webBrowserOverlayWindow.Owner = mainWindow;
                webBrowserOverlayWindow.Owner.LocationChanged += webBrowserOverlayWindow.PositionAndResize;
                webBrowserOverlayWindow.TargetElement.LayoutUpdated += webBrowserOverlayWindow.PositionAndResize;

                if (oldTargetElement != null)
                    oldTargetElement.LayoutUpdated -= webBrowserOverlayWindow.PositionAndResize;

                webBrowserOverlayWindow.PositionAndResize(sender, new EventArgs());

                if (webBrowserOverlayWindow.TargetElement.IsVisible && webBrowserOverlayWindow.Owner.IsVisible)
                {
                    webBrowserOverlayWindow.Show();
                }

                webBrowserOverlayWindow.TargetElement.IsVisibleChanged += (x, y) =>
                {
                    if (webBrowserOverlayWindow.TargetElement.IsVisible && webBrowserOverlayWindow.Owner.IsVisible)
                    {
                        webBrowserOverlayWindow.Show();
                    }
                    else
                    {
                        webBrowserOverlayWindow.Hide();
                    }
                };
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            Owner.LocationChanged -= PositionAndResize;
            if (TargetElement != null)
            {
                TargetElement.LayoutUpdated -= PositionAndResize;
            }
        }

        private void PositionAndResize(object sender, EventArgs e)
        {
            if (TargetElement != null && TargetElement.IsVisible)
            {
                var point = TargetElement.PointToScreen(new Point());
                Left = point.X;
                Top = point.Y;

                Height = TargetElement.ActualHeight;
                Width = TargetElement.ActualWidth;
            }
        }

    }
}

Generic.xaml ResourceDictionary (in the "Themes" folder):
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:AllowTransparencyIssue">

</ResourceDictionary>

TransparentWebBrowser.cs (Custom Control):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AllowTransparencyIssue
{

    public class TransparentWebBrowser : Control
    {

        private WebBrowserOverlayWindow _WebBrowserOverlayWindow;
        public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register("TargetElement", typeof(FrameworkElement), typeof(TransparentWebBrowser), new PropertyMetadata(TargetElementPropertyChanged));
        public FrameworkElement TargetElement
        {
            get
            {
                return GetValue(TargetElementProperty) as FrameworkElement;
            }
            set
            {
                SetValue(TargetElementProperty, value);
            }
        }

        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(TransparentWebBrowser), new PropertyMetadata(SourcePropertyChanged));
        public string Source
        {
            get
            {
                return GetValue(SourceProperty) as string;
            }
            set
            {
                SetValue(SourceProperty, value);
            }
        }

        private static void SourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var transparentWebBrowser = sender as TransparentWebBrowser;
            if (transparentWebBrowser != null)
            {
                transparentWebBrowser._WebBrowserOverlayWindow.Source = args.NewValue as string;
            }
        }

        private static void TargetElementPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var transparentWebBrowser = sender as TransparentWebBrowser;
            if (transparentWebBrowser != null)
            {
                transparentWebBrowser._WebBrowserOverlayWindow.TargetElement = args.NewValue as FrameworkElement;
            }
        }

        public TransparentWebBrowser()
        {
            _WebBrowserOverlayWindow = new WebBrowserOverlayWindow();

            //TODO: Figure out how to automatically set the TargetElement binding...

            //var targetElementBinding = new Binding();
            //var rs = new RelativeSource();
            //rs.AncestorType = typeof(Border);
            //targetElementBinding.RelativeSource = rs;

            //_WebBrowserOverlayWindow.SetBinding(TransparentWebBrowser.TargetElementProperty, targetElementBinding);

        }

        static TransparentWebBrowser()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TransparentWebBrowser), new FrameworkPropertyMetadata(typeof(TransparentWebBrowser)));
        }
    }
}

Modified MainWindow.xaml:
<Window x:Class="AllowTransparencyIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:AllowTransparencyIssue"
        Title="MainWindow"
        Height="500"
        Width="700"
        AllowsTransparency="True"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"

        >
    <Border BorderBrush="Blue" BorderThickness="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Button Grid.Row="0" HorizontalAlignment="Right" Click="Button_Click">Close Window</Button>

            <TabControl Grid.Row="1">

                <TabControl.Items>
                    <TabItem Header="StartPage.com">
                        <TabItem.Content>
                            <Border>
                                <local:TransparentWebBrowser TargetElement="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}}" Source="http://www.startpage.com" />
                            </Border>
                        </TabItem.Content>

                    </TabItem>

                    <TabItem Header="Google.com">
                        <TabItem.Content>
                            <Border>
                                <local:TransparentWebBrowser TargetElement="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}}" Source="http://www.google.com" />
                            </Border>
                        </TabItem.Content>
                    </TabItem>

                    <TabItem Header="Bing.com">
                        <TabItem.Content>
                            <Border>
                                <local:TransparentWebBrowser TargetElement="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}}" Source="http://www.bing.com" />
                            </Border>
                        </TabItem.Content>
                    </TabItem>

                </TabControl.Items>
            </TabControl>
        </Grid>
    </Border>
</Window>

Screenshot to prove this works:

My final thought and question to my answer is, can anybody figure out how to wire-up the binding code in the instance constructor of the "TransparentWebBrowser" class so I don't have to explicitly set the TargetElement property in the MainWindow.xaml???


A technique for simulating an octave below the 5th of the power chord

Question: In this video:

John Petrucci says:
"He's playing a 7 string song on a 6 string guitar.. that song utilizes the lower 7th string, but there's a trick on the guitar where if you play a power chord and you finger the 5th below the root, if you play that a certain way the octave lower root will sound. It's like a weird aural illusion."
What is he talking about? How can I recreate this?
Comment: The phenomenon is called fundamental tracking.  It cannot be due to the wave interference alone as that is a linear process and will never create a sub-harmonic.  However, the ear is non-linear and the brain is programmed to identify the harmonic sequence.  So, if you feed the ear a sequence of tones that do NOT obey the harmonic sequence the brain tries to ID an f0 such that the rest of the tone fit the sequence relative to that f0.  The brain then thinks that this is the fundamental of the sequence.
Comment: However, there is more to the story than that and each of the notes has their own set of harmonics.  It is not entirely clear at first glance that those harmonics will NOT interfere with the tracking process as the brain will hear those and use them to ID each note as an f0 in their own right.  If you really hear the sub-harmonic then it works.
Answer: It's about the period of the resulting wave. If you play a root note and its fifth dropped by one octave (i.e., a perfect fourth below, e.g., a C with a G below) then the frequencies are
3/4*f, f
if f denotes the frequency of the C note. The question is now what the frequency of the resulting wave will be. We know that periodic waves can be represented by a weighted sum of (phase-shifted) sinusoids with integer multiples of the fundamental frequency (Fourier series). So we just have to figure out if there's some fundamental frequency f0 that results in the two frequencies 3/4*f and f as integer multiples of f0.
We get
3*f0,4*f0
with f0=f/4. So the fundamental frequency f0 of the resulting wave corresponds to a C that is actually two octaves below the C that was played. Even if that low C is not actually played, it is, and can be perceived as, the fundamental frequency of the resulting wave.
Answer: Technique
This video by guitarist Peter Hodgson seems to be describing the same thing, and the technique he uses in reasonable detail.
It seems to be as straightforward as Petrucci describes. Assuming standard tuning, playing a power chord rooted on the A string, but also fretting the lower 5th interval on the E string.
(low to high)

E: 5
A: 5
D: 7
G: 7
B:
e:

The Science (possibly)

The brain perceives the pitch of a tone not only by its fundamental
frequency, but also by the periodicity implied by the relationship
between the higher harmonics; we may perceive the same pitch (perhaps
with a different timbre) even if the fundamental frequency is missing
from a tone.
A low pitch (also known as the pitch of the missing fundamental or
virtual pitch) can sometimes be heard when there is no apparent source
or component of that frequency. This perception is due to the brain
interpreting repetition patterns that are present

That is to say, even if your root note is missing, the brain can still "hear" it. Possibly (my uneducated guess) because we are trained by the musical culture to expect it.
See Missing fundamental.


Daily average pay

Question: Imagine we have the following situation:
Worker 1: worked days: 20; total $ earned: 200; \$/day: 10\$/day
Worker 2: worked days: 30; total $ earned: 200; \$/day: 6.7\$/day
The average pay per day of the two workers is then 8.3\$/day,
however on a website I found the following computation: 400\$/50days=8\$/day. Is it possible to reason in the latter way e.g. when we only have the totals and not each worker's daily average?
Thank u for any help
Answer: the average is a value that, substituted in the original data, ceteris paribus gives the same amount of expense, thus
$$20\times m+30\times m=200+200$$
that is
$$m=\frac{400}{50}=8$$

If you use your value you get that the total amount of expense is
$$20\times8.3+30\times8.3=415\ne400$$
thus your calculation is wrong.
A question... how did you get 8.3? doing an arithmetical mean you get $\frac{10+6.7}{2}=8.35$
Comment: And what is wrong with the first computation?
Comment: @Anna:  see my edits
Comment: It came out 8.3 because I didn't round any decimals from the beginning on

Daily average pay


How to select the first element of a set with JSTL?

Question: I managed to do it with the next code but there must be an easier way.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<c:if test="${fn:length(attachments) > 0}">
    <c:forEach var="attachment" items="${attachments}" varStatus="loopCount">
        <c:if test="${loopCount.count eq 1}">
         attachment.id
        </c:if>
    </c:forEach>
</c:if>

Comment: the solution down as c:out used did not work I get the next error `javax.el.PropertyNotFoundException: Property '0' not found on type org.hibernate.collection.PersistentSet` i used you r code above since am using hibernate like this  `someobject.getSetofsomeObjects()` in request parameter
Answer: You can access individual elements with the array [] operator:
<c:out value="${attachments[0].id}" />

This will work for arrays and lists. It won't work for maps and sets. In that case you must put the key of the element inside the brackets.
Comment: The above will only work for collections types that have a get(int i) method. Is this possible with PersistentSet?
Comment: I get the next error javax.el.PropertyNotFoundException: Property '0' not found on type org.hibernate.collection.PersistentSet
Comment: For a `java.util.Set`, you need to convert it to an array first like ``. A `java.util.Set` is an unordered list and it doesn't have an index like a `java.util.List`.
Comment: @kgiannakakis user asks how to access to Set thus answer is not relevent
Answer: Sets have no order, but if you still want to get the first element you can use the following:
<c:forEach var="attachment" items="${attachments}" end="0">
     <c:out value="${attachment.id} />
</c:forEach>

Answer: Work for arrays and lists only, not for set.
Comment: well, the "aside" implementations are actually useful if you want unicity on top of ordering.
Answer: Since i have have just one element in my Set the order is not important So I can access to the first element like this :
${ attachments.iterator().next().id }

Answer: Look here for a description of the statusVar variable.
You can do something like below, where the "status" variable contains the current status of the iteration. This is very useful if you need special annotations for the first and last iteraton. In the case below I want to ommit the comma behind the last tag. Of course you can replace status.last with status.first to do something special on the first itteration:

    <c:forEach var="tag" items="${idea.tags}" varStatus="status">
        ${tag.name not status.last ? ', ' : ''}
    </c:forEach>

Possible options are: current, index, count, first, last, begin, step, and end
Answer: If you only want the first element of a set (and you are certain there is at least one element) you can do the following:
<c:choose>
    <c:when test="${dealership.administeredBy.size() == 1}">
        Hello ${dealership.administeredBy.iterator().next().firstName},

    </c:when>
    <c:when test="${dealership.administeredBy.size() > 1}">
        Hello Administrators,

    </c:when>
    <c:otherwise>
    </c:otherwise>
</c:choose>

Answer: You can use the EL 3.0 Stream API.

${attachments.stream().findFirst().get()}

Be careful! The EL 3.0 Stream API was finalized before the Java 8 Stream API and it is different than that. They can't sunc both apis because it will break the backward compatibility.
Answer: Using ${mySet.toArray[0]} does not work.
I do not think it is possible without having forEach loop at least one iteration.
Comment: `${mySet.toArray[0]}` is a wrong syntax. The correct one would be `${mySet.toArray()[0].propertyIfAny}`.
Answer: Using begin and end seemed to work for me to select a range of elements. This gives me three separate lists. The first list with items 1-9, second list with items 10-18, and the last list with items 11-25.

                        <c:forEach items="${actionBean.top25Teams}" begin="0" end="8" var="team" varStatus="counter">

${team.name}

                        </c:forEach>

                        <c:forEach items="${actionBean.top25Teams}" begin="9" end="17" var="team" varStatus="counter">

${team.name}

                        </c:forEach>

                        <c:forEach items="${actionBean.top25Teams}" begin="18" end="25" var="team" varStatus="counter">

${team.name}

                        </c:forEach>

Answer: If it's a set ${attachments[0].id} won't work. use this instead
${attachments.first().key} or ${attachments.first().value}


How can I send a query to a URL using Curl POST Using PHP

Question: I wrote a query through 'postman' which looks like this
POST: http://someurl

{
    "elasticQuery": //Elastic Query is a user defined field.
    {
        "_source": [ "field 1", "field 2", "field 3" ],
        "query":
        {
            "match_all":{}
        }
    },
    "index": "indexName",
    "scroll": "True"
}

This returns lots of JSON formatted documents from the site with 3 given fields.
I am wondering how I would format this query using PHP to do a curl call and recieve the same documents.
I am not sure if this is even possible but your help will be greatly appreciated.
Thanks.
Answer: Try the following:
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "YOUR_URL_HERE",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"elasticQuery\":{\"_source\":[\"field 1\",\"field 2\",\"field 3\"],\"query\":{\"match_all\":{}}},\"index\":\"indexName\",\"scroll\":\"True\"}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "cache-control: no-cache",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Remember to replace the CURLOPT_URL string with your own URL. As a further tip, you can get Postman to generate this for you. With the request open in a tab, towards the top right below the "Send" button, there's a small bit of text which says "Code". Select it and you should have the option to generate PHP cURL.


How to add an item to an IEnumerable

Question: In C#
IEnumerable<MyModel> test = _blah.tolist();

Now I can loop through test, but how do I add an item?
Please do not tell me that it makes no sense to add an item, I've already seen that post.
What I want to know is, if I loop through 10 items, how do I put one more on so it loops through 11 items?
Also there is no .Add() method
Comment: I'm not sure how this is a duplicate. That question is for _concatenation of two `IEnumerables`_ -- it's in the title, even -- and this is to _add a single element_ to a _single_ `IEnumerable`. You'll notice that though one answer, below, is to `Concat`, the accepted answer _that would not work for concatenation_ is to cast to something that does have an `.Add` method. They're different questions. **At the very least**, as I wouldn't be surprised if someone had asked how to add before, **the dupe link is wrong.**
Answer: IEnumerable is an interface. You can't use Add() on an IEnumerable because they're not required to implement an Add() method. See the IEnumerable documentation on MSDN.
Instead, create a generic list which inherits from the interface IList. Types that use the IList interface must implement Add().
List<MyBlahType> test = _blah.tolist();
test.Add(new MyBlahType());

If you still want to use an interface to avoid a concrete type, then use IList directly.
IList<MyBlahType> test= _blah.tolist();
test.Add(new MyBlahType());

By the way, it's usually considered poor styling to start variable/type names with underscores and to not use proper capitalization. The preferred style in C# is to use PascalCase or camelCase for capitalization.
Comment: "You don't typically use interfaces directly" – Well, you actually do. You typically want to avoid using concrete types when it's not necessary to achieve loose coupling.
Comment: You absolutely code against interfaces where you can: http://stackoverflow.com/questions/4456424/what-do-programmers-mean-when-they-say-code-against-an-interface-not-an-objec
Comment: I wouldn't be surprised if this question gets an insane amount of downvotes because of your comment about PascalCase being the preferred casing convention for C#.  While I agree that PascalCase is the most logical convention, many argue that camelCase is preferred for variables, fields, and return methods.
Comment: @Jamiec You misunderstood what I said. You don't typically create instances of an interface. I didn't say you can't inherit from interfaces. And I didn't say you can't create instances of interfaces. But the generally accepted practice is to use generic list directly instead of IEnumerable.
Comment: @oscilatingcretin I'm giving general styling advice, not trying to spark a debate about the best styling type. In C#, PascalCase is the more common practice. Either way, his question shows that he went all lower case which is generally not considered good practice anywhere.
Comment: How about `IList` or `ICollection`? There's no need to refer to the concrete type
Comment: @Jamiec If you can provide a concrete reason why to **not** refer to the concrete type, feel free to let me know.
Comment: You might want to change it, you might want to unit test it, you might not know the concrete type at compile time. There are tonnes of reasons not to refer to a concrete type.
Comment: @Jamiec I've done so. I almost never use `IList` directly, but apparently [FxCop encourages it](http://stackoverflow.com/questions/17170/when-to-use-ilist-and-when-to-use-list).
Answer: Use LINQ-to-object's Concat to build a new IEnumerable that iterates the first one and then the second one:
IEnumerable<MyModel> test = _blah.tolist();
IEnumerable<MyModel> second = new[] { theItem };
IEnumerable<MyModel> elevenItems = test.Concat(second);

Answer: If you've called ToList() on an IEnumerable<T>, the return type will be a List<T>.  If the type of your variable were List<T> rather than IEnumerable<T>, you would be able to do whatever you wanted to the list you received, including adding items to it, just like you could do with any other list.  Note that the newly made list would be "detached" from the original IEnumerable<T>, so that adding, removing, rearranging, or replacing items in one would not affect the other.  Note also, however, that a list of mutable-reference-type items does not hold items, but merely identifies them.  If one has an IEnumerable<Car> myCars, and the third item is "Car#24601", then myCars.ToList()[2].Color = CarColors.Red; then the third item in the original list (i.e. Car #24601) will be painted red.

How to add an item to an IEnumerable


Where to define permissions for user roles in FCKEDitor file uploads?

Question: There is this page where you upload files with FCKeditor
My admin user can do that , but I want the same for the Editor role
(I already defined a profile for it)
It´s a matter of permissions and I´ve enabled all on the FCKEditor but I´m sure it´s something else...that I have to enable...
Answer: Are you using the IMCE module for file uploads/directory? It could be a setting there that you need to enable.


multiple domain name pointing to same place that need www before domain

Question: I have 3 domain names that point to the same website.
domain1.com, domain2.com, domain3.com
I would like to add in the .htaccess file a way that
if someone is trying to reach domain2.com the server will redirect him
to www.domain2.com.
same for domain1.com will go to www.domain1.com
I would like to do that in ONE single .htaccess since they point to the
same place.
now I have something like this:
Options -indexes
Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\.domain1\.com [NC]
RewriteRule ^(.*)$ http://www.domain1.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} !^www\.domain2\.com [NC]
RewriteRule ^(.*)$ http://www.domain2.com/$1 [R=301,L]

Answer: I agree with Rikon but here is your answer:
RewriteCond  %{HTTP_HOST}  ^domain1\.com$ [OR]
RewriteCond  %{HTTP_HOST}  ^domain2\.com$ [OR]
RewriteCond  %{HTTP_HOST}  ^domain3\.com$
RewriteRule (.*)  http://www.%{HTTP_HOST}/$1

Answer: Could I suggest a different approach: a 301 Permanent Redirect
This will be much better for your SEO.
Here's a good website that walks through how to do a 301 for each programming language (including how to do it with .htacess): http://www.seoworkers.com/seo-articles-tutorials/permanent-redirects.html
Here's the quote from the web site on how to do this with .htaccess:

II Redirecting with .htaccess
If you are on an Linux/Apache server, or a Microsoft Windows Server that can run Apache modules, you can do your redirects with an .htaccess file.
The .htaccess file is a very powerful tool, but can wreak havoc on a site if not implemented correctly. Always save a backup of any existing .htaccess file before attempting any changes.

Redirection with mod_rewrite
The following lines redirect the client to a new location. In this case, a request for the file contact.php is sent to the file contact-us.php:
rewriteEngine on
  rewriteRule ^contact.php$ http://www.dexterityunlimited.com/contact-us.php [R=permanent,L]

Redirect all non-www traffic
The code below will direct all traffic which does not contain the www in the URL to the same page, but now including the www. And that will clean up the canonicalization problem that arises when the www version of your site gets indexed along with the non-www version:
rewriteCond %{HTTP_HOST} ^dexterityunlimited.com$
  rewriteRule ^.*$ http://www.dexterityunlimited.com%{REQUEST_URI} [R=permanent,L]

Original source: Search Engine Friendly Permanent Redirects - SEO Workers http://www.seoworkers.com/seo-articles-tutorials/permanent-redirects.html#ixzz1Us3DQxtj
   Under Creative Commons License: Attribution No Derivatives

FYI: Here's the quote (from the above site) on why to do a 301:

I am certain there are some of you asking this question. The answers are many, depending on your particular situation.
Are there links to your site that are outdated, but you have no way to change them? Simply create a redirect that will take visitors using that outdated link to the most appropriate new page on your site.
Is there a link in a directory somewhere that is misspelled, or is missing the www? Use one of the methods above to correct the situation at the server.
There are many ways for you to control what people see and where they can go on your web site. Take some time to learn a few tricks, and you might find that your traffic increases because you aren't leaving anyone behind.


ngstrap typeahead unordered multiple keyword search

Question: I having an issue with ngstrap typeahead with the scenario below:
var companyItem= [
 {
"item_id": 1,
"item_name": "mobile phone middle nokia",
"company_id": 1,

},
{
"item_id": 2,
"item_name": "mobile phone iphone",
"company_id": 1,

},
{
"item_id": 8,
"item_name": "mobile phone samsung",
"company_id": 1,

},
{
"item_id": 9,
"item_name": "apple watch",
"company_id": 1,

}
]

My Markup :
<input type="text" class="form-control" name="itemName" id="itemName" ng-model="item.itemName" data-min-length="0" bs-options="item as item.item_name for item in companyItem | filter:{item_name:$viewValue}:customCompare" bs-typeahead="setCustomerData" data-watch-options="true" data-container="body" autocomplete="off" ng-readonly="readOnly" required>

and my scripts is :
$scope.customCompare = function(itemName, viewValue) {
    var keyword = viewValue.split(" ");
    var partialMatch = false;

    for(var i=0;i<keyword.length;i++){
          console.log('keyword'+i+' '+keyword[i]);
            console.log('itemName '+itemName);
            console.log('keyword[i].indexOf(itemName) > -1 '+itemName.indexOf(keyword[i].toString()));
            if(itemName.indexOf(keyword[i].toString()) > -1){
               console.log(' <<>>---------------');
                partialMatch =true;

            }

    }
       return partialMatch;
}

I've try to search with keyword 'mobile iphone' in the input text but there're no result.
This return true as I'm write in the console log but the record not showing
Anyway if 'phone iphone' it's working like default typeahead
Anything I'm done wrong or this approach is not working
https://plnkr.co/edit/3iJwREetLMnTup24Sbtd
Thanks in Advance.
Comment: Could you include the console log when typing 'mobile iphone' and when typing 'phone iphone'? Also, if you can build a plunker like http://plnkr.co/edit/dvmVTZwzjMCHrNUhWkKU?p=preview, it would be helpful.
Comment: Hello Tanin here's the plunker https://plnkr.co/edit/3iJwREetLMnTup24Sbtd f I'm type 'phone iphone' it's working as default typeahead. Anyway 'mobile iphone' it's not working I got another solution for async via api   to back-end but if any solution for not hit too much database would be appreciate, Thanks
Comment: Thanks. That's very helpful.
Answer: I got another solution as I saw "filter: 'bsAsyncFilter'" in typeahead.js so I override in my js by bypass the filter because now I'm using async data through api :
function CustomTypeaheadFilter ($filter)  {
return function(array, expression, comparator) {

  if(array && angular.isFunction(array.then)) {
    return array.then(function(results) {
        console.log(results);
     // return $filter('filter')(results, expression, comparator)
     return results;
    });
  } else {
    //return $filter('filter')(array, expression, comparator);
    return array;
  }
}
};

Mark up:
<input type="text" class="form-control" name="itemName" id="itemName" ng-model="item.itemName" data-min-length="0" bs-options="item as item.item_name for item in getItemfromDB($viewValue)" bs-typeahead="setCustomerData" data-filter="CustomTypeaheadFilter" autocomplete="off"  required>

filter option is not declare in ngstrap document, I'm posted the issue on the github anyway hope ngstrap will raise this option to the document then.
Comment: Yes, setting data-filter to be your own filter works too. You can pretty much make it to do anything you would like to.
Answer: Ng-strap adds a default filter that uses a default comparator after your item as item.item_name for item in companyItem | filter:{item_name:$viewValue}:customCompare.
One hacky solution is to bypass the default filter.

$scope.alwaysTrue = function() { return true; }
<input ... bs-options="item as item.item_name for item in companyItem | filter:{item_name:$viewValue}:customCompare" data-comparator="alwaysTrue" ...>

A cleaner solution would be to set data-comparator="customCompare". Sadly, that doesn't work because here contains :$viewValue, not :{item_name: $viewValue}. So, customCompare never gets to process a whole object.
The API can and should be improved, and you should open an issue about it on github.
Comment: How about I'm set data-comparator=true? I've tried but it's not working
Comment: You can try, but I think it might not work because it expects a function, and `true` is not a function.


How to pull out part of a string after a regex value

Question: Trying to pull part of a string after a variable regex value to be written to a csv
I have a script that scrubs reports for important information.  the way the report is written it has MGRS grids followed by a number.  for ex. the report will have several lines that look like this: (MGRS: 12ABC12345678//, 23 words followed by more words MGRS: 98ZYX87654321// 17 even more words).  I am trying to create a csv that just has the MGRS grid and the following number.
<code>    MGRS_Regex= re.compile('\d{1,2}[A-Za-z]\s?[A-Z-a-z]{2}\s?\d{2,5}\s?{2,5}')
    grid_list = []

    for f in file_list:
        with open(f,'r')as csv_file:
            csv_reader = csvDictReader(csv_file)
            for row in csv_reader:
                for key, value in row.items():
                    if key == 'text_field':  ##text_field is the record##
                        grid_pull = MGRS_Regex.findall(value)
                        for grid in grid_pull:
                            grid_list.append(grid)
                for grid in grid_list:
                    if field == 'important number':  ## field is the key the new csv file##
                        text = row.get('text_field')
                        grid_search = text.find(grid)
                        important_number = text[grid_search : 3]
                        important_info.update({field:important_number})
</code>
expecting to get a dictionaries with the varible field"name" as the key and the sliced out str as the value
Comment: Why do we have to learn about somebody's phd project, can't you simplify this ? At least when asking a question . The question is that little part that needs a solution that you cannot do.
Comment: I'm not sure what flavor of regex you are using but if you want to capture various parts of the regex you should use a capture group. If you tell me what language you are using and give me a sample of what the input looks like I can probably help you build a regex for that.
Comment: unfourtantly I can't add a real sample of the text because it is proriotory information.  best way I can describe it is; I have several hundred reports that have information regarding locations and how long some one was there.  so textualy it looks like ( blah blah blah blah blah MGRS:12ABC12345678// 13 weeks blah blah blah blah MGRS: 98ZYX87654321// 9 days blah blah blah)
Comment: I can pull out the (MGRS) using the provided regex code easy enough but I am having trouble slicing out the "13 weeks" part to do temporal analysis on the data.
Answer: I'll offer up this regex in hope's it will be sufficient
<code>(?i)\d{1,2}[a-z]\s*[a-z]{2}\s*\d{2,5}\s*\d{2,5}//\s*\d+(?:\s*(?:years|days|weeks))?</code>
https://regex101.com/r/Dwoz3a/1
Expanded
<code> (?i)
 \d{1,2} [a-z] \s* [a-z]{2} \s* \d{2,5} \s* \d{2,5}
 // \s* \d+
 (?:
      \s*
      (?: years | days | weeks )
 )?
</code>


How to choose a convergence test for a given infinite series?

Question: I have a general question when it comes to deciding if an infinite series is convergent or divergent. The tests im familiar with are ; Ratio test, Direct comparison test, Limit comparison test, Root test and the Integral test.
My question is if there is any way to tell what test is appropriate to start with just by looking at the series. At the moment I usually follow my own pattern and systematically try different tests. What I do is:

Divergence test to see if the series is divergent. If its unsuccessful
Ratio test, if unsuccessful
Limit comparison test
etc

Which has been working fine, my concern is that it may be very time consuming if the first tests are unsuccessful, and might not be very efficient during exams.
So basically: Is there a way to determine what tests are appropriate by just looking at the series? ( I have found nothing like this in my textbook, all the examples simply jump straight into the "correct" test).
Answer: We have learned that

ratio test is the best for series that converges to zero "fastly" - i.e. when you see that the series has for example factorial, exponential function or something like that in the denominator, it's good to try ratio test ($\sum{\frac{n^5}{5^n}}$,...)
limit comparison test is good for series that converges to 0 slowly that means n-th roots, polynomial function etc ($\sum{\frac{n^2}{n^3+1}...}$) then you just have to find a right series to compare it to
root test is good for series containing exponential functions ($\sum ({\frac{3n+42}{4n+2})^n}$...)

When solving convergence of a series it´s hard to say if one test is better than the others. Different tests can be used to solve the same series. But I hope that those are some useful tips


c++ reference book stack example inefficient?

Question: I'm reading through the book C++ reference by Herbert Schildt and there is a stack example in the c section of the book similar to the following:
#include <stdio.h>
#include <stdlib.h>

#define SIZE 50

void push(int i);
int pop(void);

int *tos, *p, stack[SIZE];

int main(void) {
    tos = stack;
    p = stack;
    // push, pop, etc
    return 0;
}
void push(int i) {
    p++;
    if (p==(tos+SIZE)) {
        printf("Stack overflow");
        exit(1);
    }
    *p = i;
}
int pop(void) {
    if (p==tos) {
        printf("Stack Underflow");
        exit(1);
    }
    p--;
    return *(p+1);
}

The above stack implementation does not use the TOS for storing a value.  The first value is stored at TOS+1.  I couldn't see why you would do that as it seems to waste a memory space.
I have rewritten it to the example below, which doesn't waste the space (EDIT: read the selected answer - the code below is suspect!):
#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

void push(int i);
int pop(void);

int *tos, *p, stack[SIZE];

int main(void) {
    tos = stack;
    p = stack;
    // push, pop, etc
    return 0;
}
void push(int i) {
    if (p==(tos+SIZE)) {
        printf("Stack overflow");
        exit(1);
    }
    *p = i;
    p++;
}
int pop(void) {
    p--;
    if (p<tos) {
        printf("Stack Underflow");
        exit(1);
    }
    return *p;
}

Is there a reason for Schildt's implementation not using the TOS position?
Many thanks.
Comment: Herb Schildt's C Reference is notorious for errors: http://www.seebs.net/c/c_tcn4e.html. I don't know if the C++ series has similar issues.
Comment: Probably an oversight, or just not considered important. There are other oddities too - e.g. why have `tos` at all when you can just as easily refer to `stack`. There's a fairly common convention where stacks sometimes grow from the top downwards - maybe an early version did that, he decided it was unfair on newbies, and he translated a bit naively.
Comment: @Scott - sorry, I'm wrong - he has written several C++-specific books.
Comment: @Scott - technically I don't think there *is* a C++ series - there's a C/C++ series (I have a copy of the second edition, copyright page says 2000). I've just done the pick-random-pages thing and I see `cout` used with no `endl` everywhere - a sure sign of naive translation from the `printf` without `\n` in the C versions that you link mentions. It's not a book I actually use, just one I bought because it was there.
Answer: The original code, though it exhibits poor style, has well-defined behavior. Your modified code's behavior is undefined.
To test whether the stack is empty, you need to do the pointer comparison before modifying the pointer. If the comparison indicates that the stack is empty, do not decrement the pointer.
If p points to stack[0], then p--; has undefined behavior, even if you never dereference p after that. You cannot legally form a pointer that points before the beginning of an array, or more than one element past the end of it. (You can legally form a pointer just past the end of an array, but you can't dereference it.)
It's likely to "work" in most stack-based implementations -- which just means that this is a bug that's difficult to find through testing.
A problem in the original code: tos initially points to element 0 of stack, and it's not modified by either push() or pop(). Why isn't it declared const, why is it called tos (a name that implies "top of stack", but that's what p is used for), and why have that variable at all, given that stack or &stack[0] gives you the same value? I doubt that there are any good answers to these questions.
Also in the original code, exit(1); is not a portable way to signal failure (there are systems on which it signal success). exit(EXIT_FAILURE); is the right way to do that, unless you're writing deliberately non-portable code. (Which can make sense if you're writing a program to be used only on Unix-like systems, but not if you're writing examples for a language tutorial).
My advice: Google "Schildt" to learn about the author's exceedingly poor reputation as an author of C and C++ books, and then find a book written by someone who actually understand the language.
(A previous version of this answer incorrectly blamed Schildt for some errors that were not his; my apologies for that. I still recommend avoiding his books.)
Answer: It looks like he's trying to keep p always pointing somewhere within the stack, rather than pointing at some random location in memory before the stack like yours does.  As long as the invalid p isn't dereferenced anywhere (i.e. since you're calling exit if it is wrong) there shouldn't be much difference.
Comment: @Steve314: Strictly speaking, no example is needed to demonstrate that the behavior is undefined. The language standard says the behavior is undefined, or just doesn't define the behavior. You make a good point about the rationale for the behavior's undefinedness, but there are other possible reasons. For example, an array's starting address might be at the beginning of a segment.
Comment: @larsman - I'm pretty sure it's technically undefined behaviour. For example, on some platforms there's a chance your array might start at address 0 (and NULL wouldn't be zero). But all that's needed to fix it is checking if the stack is empty before decrementing the stack pointer for the `pop`.
Comment: I'm not sure if pointing a pointer one element before the start of an array is valid. One after the end is, but C can be quite picky about these things.
Comment: Regardless of the original reasons for a behavior to be undefined, once it is written as undefined in the standard, compilers start aggressively optimizing based on the undefinedness and the original reason does not matter any more. http://lwn.net/Articles/278137/
Comment: @Keith, Pascal - Human memory works better with context and explanations. Random unexplained facts get instantly forgotten, and "because the standard says so" is really no better than unexplained. Of course once the standard says something, it doesn't matter whether you have a platform where the original reasons were valid or not but still - that's a good point to make - but I feel as if you think I've committed a terrible crime by trying to make it a bit easier for people to remember the issue.
Comment: @Steve314: I certainly hope I didn't imply that you've committed a "terrible crime". In some cases, behavior is left undefined just because it wasn't worth the effort to define it, not necessarily because some specific bad thing is likely to happen. And your example was complete -- as was mine (a compiler is free to *assume* that a program doesn't do anything undefined, and to optimize the generated code accordingly). BTW, you can only notify one person for each comment; if you want Pascal to see a notification in his inbox, you'll need to include an at-sign followed by "Pascal".


Software/Service for Controlled Shutdown/Startup of a Server Room

Question: We are looking for a solution to automatically shutdown server room equipment in a controlled process, based on priority, automatically during a power outage and on demand if necessary.  We would also like to be able to power the servers back on in a controlled manor.
We have a mixture of equipment (physical and virtual servers and multiple types of UPS/storage array/server vendors) and no budget for this :-) so even a partial solution would be helpful.  We hope to get a generator but we have been hoping for years now.
Answer: Stop hoping, start planning & budgeting. To shutdown, you could write a simple script to call psexec, WMI, etc. Most good UPSes come with software to gracefully shutdown the attached computer. To turn on, you either need WoL, or a hardware solution like IPMI (iLO, ILOM, etc).
Comment: the funny thing is that if you use linux, you need no advanced license, the ilo console always works ;-) (at least in the g5 servers we have).
Comment: I'd be curious to hear your thoughts on iLO vs. WoL (wrt the purpose above) -- we have HP systems that include the basic version, but have never enabled.
Comment: Tools like [wolcmd](http://www.depicus.com/wake-on-lan/wake-on-lan-cmd.aspx) make the wake-up scripting a lot less intimidating.  It's not too complicated to pull a list of MAC addresses from your automated inventory database (e.g. [OCS Inventory NG](http://www.ocsinventory-ng.org/)) and fire off some magic packets.
Comment: @nedm, We have all HP servers and i love iLO. It impresses the boss when you can turn servers on from another country while you're on vacation. Or get notifications of a BSOD (and the Stop code). Remote media and console are really useful if you've got the advanced license.
Answer: We have a mixed Windows/*nix environment and have been dealing with the same issues.  We're in the process of implementing apcupsd and using it to kick off .bat and shell scripts to shut things down gracefully.  So far it seems to work very well across the disparate server environments and UPS systems.


I am looking for an efficient way to remove items from a JavaScript array if they are present in another array. Using indexOf

Question: I want to remove those items from arr_2 which contains the domain name from arr_1

let arr_1 = ["domain1.com", "domain2.com"];

let arr_2 = [
  "domain1.com/about-us",
  "domain3.com/contact-us",
  "domain4.com/privacy-policy",
  "domain2.com/pricing-plans",
  "sub.domain2.com/home-1",
];

let filtered_arr = [];

arr_2.forEach((item) => {
  if (item.indexOf(arr_1) == -1) {
    filtered_arr.push(item);
  }
});

console.log(filtered_arr);

i want the result ["domain3.com/contact-us", "domain4.com/privacy-policy"] from this code, but it prints the whole arr_2
Comment: You need to loop over both arrays (one loop inside the other), and you need to use String.includes() instead. Call .filter() on arr_2, then call .some() on arr_1 inside. Give it a try.
Comment: of course filtered_arr is the same as arr_2 - nothing in arr_2 matches arr_1 at all
Answer: Your code right now is returning the whole arr_2 because your filtering logic does not check if each item of arr_2 contains one of the matching strings in arr_1.
indexOf(arr_1) is essentially searching each item in arr_2 for the entire arr_1 array. The function will always return -1 because each item of arr_2 is a string and will never match with the entire arr_1 array.
I assume you'd want to go through each item in arr_1 as well, so you should probably do arr_1.forEach((item1) => { }) inside the forEach loop for arr_2, and do the indexOf check inside this inner loop.
Answer: You can't call indexOf on a string and pass an array as an argument.
You should use find to check if item has a domain from arr_1.
And it's a lot cleaner code using filter than forEach.

let arr_1 = ["domain1.com", "domain2.com"];

let arr_2 = [
  "domain1.com/about-us",
  "domain3.com/contact-us",
  "domain4.com/privacy-policy",
  "domain2.com/pricing-plans",
  "sub.domain2.com/home-1",
];

let filtered_arr = arr_2.filter(item => {
  return !arr_1.find(domain => item.includes(domain));
});

console.log(filtered_arr);

Note: This would also filter out "example.com/domain1.com".
Comment: also i want to remove duplicates from `arr_2` , how can i do it?
Comment: how?
i want to remove duplicates also from this.

`arr_2 = [
        "domain1.com/about-us",
        "sub.domain1.com/post-2",
        "domain3.com/contact-us",
        "domain4.com/privacy-policy",
        "domain4.com/page-1",
        "domain2.com/pricing-plans",
        "sub.domain2.com/home-1",
      ]
`
Comment: `arr_2 = arr_2.filter(...` not removing the duplicates, it prints `['domain3.com/contact-us', 'domain4.com/privacy-policy', 'domain4.com/page-1']`
here `domain4.com` is duplicate
you can see the code here [JSFiddle](https://jsfiddle.net/kazimshah39/skc2djh1/5/).
Comment: I don't see how they are duplicates. Those are different URLs, just same domain.
Comment: I want to keep only one URL from a domain, if there are multiple URLs from the same domain, the first URL should be kept and others should be removed
Answer: you can achive it using filter some and includes

let arr_1 = ["domain1.com", "domain2.com"];

let arr_2 = [
  "domain1.com/about-us",
  "domain3.com/contact-us",
  "domain4.com/privacy-policy",
  "domain2.com/pricing-plans",
  "sub.domain2.com/home-1",
];

const arr3 = arr_2.filter(url => !arr_1.some(domain => url.includes(domain)))

console.log(arr3)
Comment: i want to remove duplicates also from this. `arr_2 = [ "domain1.com/about-us",         "sub.domain1.com/post-2",         "domain3.com/contact-us",         "domain4.com/privacy-policy",         "domain4.com/page-1",         "domain2.com/pricing-plans",         "sub.domain2.com/home-1",       ]`


T-test shows no differences, but the experiment group shows tendency more benefit in all variables measured than control group

Question: I've just finished an animal experiment. I compared 1 control group and 1 experimental group, the only difference between the two is type of diet. For statistical analysis I used the independent groups t-test, and the result showed no significant differences between the two groups. However, the data shows the tendency that the experimental group has more benefit in all variables measured. So, what should I say about my data? All data are normally distributed.
My supervisor said that maybe because I used very small sample (each group n=8) that I could not find any significant differences. He suggested me to do some "probability test" or something to extrapolate my data (unfortunately, I don't have any clue what he was talking about).
So, is there any statistical analysis that I can use like what my supervisor told me to do?
Comment: How many variables did you measure / test?  Do you think of them as related to each other, or are they independent?
Comment: You say "T-test" in your title but "t-test" in your body text. Did you do several univariate two-sample t-tests, or did you do a single multivariate [T-test](http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.bsmsp/1200500217)? (See also [this](http://en.wikipedia.org/wiki/Hotelling%27s_T-squared_distribution#Hotelling.27s_two-sample_T-squared_statistic) and [this](http://faculty.smu.edu/kyler/courses/7314/Hotellings_T.pdf) and [this](http://www.psych.yorku.ca/lab/psy6140/lectures/HotellingT2-2x2.pdf))
Comment: With the 'probability test', do you think he might be referring to [Fisher's method](http://en.wikipedia.org/wiki/Fisher%27s_method)? If so, you'd need the various response variables to be independent, which I would usually doubt.
Answer: Calculate an effect size (such as Cohen's d). Effect sizes are not as influenced by sample size as the test statistic is.
Comment: Effect sizes aren't, but the accuracy of inferential estimates thereof is. Low power probably means a large confidence interval for your d.
Answer: Your supervisor may very well be right and the small sample size is the problem. You might want to do a bit of reading on Power Analysis. An introductory paper is that by Cohen (1992).
In short, there is a relation between sample size, effect size and power (which is the probability that the test detects a significant effect assuming that there is one). For example, if you have an estimate of the effect size you're looking for (in your example the difference between the means of the two groups) and you want to obtain a statistically significant result regardings this effect with a certain error probability (the $\alpha$-Level), then you can compute the size of the sample that is neccessary. Generally, when you have two of the numbers, you can compute the third one.
The difficult part is probably to get an idea of the effect size before doing the analysis. After all, ususally that is what one wants to find out about. An interesting discussion on this can be found on the Cognitive Sciences SE site.
One piece of free software to do power analysis is G Power. There is also the pwr-package for R.
References:

Cohen, J. (1992). A power primer. Psychological Bulletin, 112(1), 155.


How to use try catch for multiple sections of code raising the same Exception?

Question: I have the code below, the until function raises a TimeoutException if the lambda function does not return an element. The problem is, that there are multiple sections of code that raise the same error, both when closing the cookies footer and finding the product title. I imagine it would be incredibly difficult to debug if multiple sections of code raise the same Exception. I initially thought of using the check on the string converted error message str(e), but the TimeoutException also does not provide a useful message. Should I wrap a try-except statement for each section of code?
thanks
try:
            #Closes cookies footer
            reject_cookies_btn = self.wait.until(lambda driver: driver.find_element(By.CSS_SELECTOR, "[data-type='no']"))
            self.wait.until(EC.element_to_be_clickable(reject_cookies_btn))
            reject_cookies_btn.click()

            #Finds the product title and sets the product_description dictionary
            product_title = self.wait.until(lambda driver : driver.find_element(By.CSS_SELECTOR, "[class='title-name a-fonts--26 a-colors--black-t js-detail-title']"))
            product_description["title"] = product_title.text

except TimeoutException as e:
print(str(e))

Comment: Yes, that's what would solve your problem.
Comment: Does the traceback not contain the information you want?
Answer: Since the exception is usually hit in the wait function, that will be the best place to use the try catch block cause i c you calling the said function multiple times.
Answer: One thing that come to my mind would be to provide custom exceptions for each of the errors you described using custom exceptions, as described here.
Also to maintain readable code you should rather put try; except only on the code that generates error.


Find entry in table with a column with same value

Question: The title is a bit wrong, i can explain better here.
Say i have a MySQL table like this:
mysql> select * from people;
+------+---------------+
| name | number        |
+------+---------------+
| John |        100000 |
| Alex |        200000 |
| Tim  |        500000 |
| Alice|        100000 |
| Peter|        500000 |
+------+---------------+

And now i want a query which returns the names of the people who have the same number, ie, for this table i would a query which would return John and Alice (they have the same number, 100000) and Tim and Peter (the same number 500000)
Answer: Try self join as below:
SELECT p1.name
FROM people p1 INNER JOIN people p2
ON p1.number = p2.number
WHERE p1.name != p2.name

Answer: You can do this by aggregating on the number column and using group_concat().  A having clause selects only cases where there is more than one name:
select number, group_concat(name) as names
from table t
group by number
having count(*) > 1;