Cannot push 0 to stack in java

Question: I am newbie in Java. I have the problem. This is my code
Stack<String> st = new Stack<String>();
int num=9;
while(num > 0){
    st.push(Integer.toString(num%2));
    num/=2;
}
int d=0;
if(!st.isEmpty()){
    d++;
    st.pop();
 }
System.out.println(d);

the result is 1.
But correct is 4.
I don't know how to fix it. Sorry if my English is not good. Thankyou
Comment: Hint: how do you expect `d++;` to execute more than once?
Comment: Have you stepped through your program with the debugger?
Comment: What do you mean by "stack has only one element"? How did you determine that? (It really *does* have a size of 4 before the `if` statement. It has a size of 3 after the `if` statement...)
Comment: @VanLeThanh: No, literally: *how do you expect that line of code to be executed more than once?* Look *very* carefully at what you've written.
Comment: _In if {....} I will increase d and pop element until stack is empty_: an `if` statement does not repeat itself - it executes only once. There is no _until stack is empty_ with just a single `if` statement!
Comment: What are you expecting `d+;` to do?
Comment: sorry d++;//d=d+1;
Comment: I found out, in while{....} stack has 4 element 1,0,0,1. But  in if{.....} stack has only one element (value 1). I don't know what is problem
Comment: @JonSkeet I want to check how many elements in stack.
Comment: @JonSkeet can you tell me where is my problem??
Comment: I think after while{...} my stack has 4 element. In if {....} I will increase d and pop element until stack is empty.
Comment: Now that you've been given the answer, it would be a good idea to take a step back and think about how you could have reached it yourself. Did you step through the code in a debugger? What happened? Did you misunderstand how an `if` statement worked, or did you not look at the code closely enough even after hints? This could be a very useful learning experience.
Comment: @JonSkeet thank you so much. I found out my problem. It's if statement.
Comment: @VanLeThanh: Yes, I know it's in the `if` statement. I knew that from the start. I was giving you hints to try to help you spot that for yourself. Again, please don't just move on from this without thinking about it more. Try to work out how you could have figured this out for yourself.
Answer: Your problem is from line 8! When you define if, however you have to write while loop, NOT if statement
Another point is that your stack should be integer and its not essential to define stack with string
So try it:
Stack<Integer> st = new Stack<>();
int num = 9, d = 0;
while(num > 0){
    st.push(num%2);
    num /= 2;
}

while(!st.isEmpty()){
    d++;
    st.pop();
 }
System.out.println(d);

Cannot push 0 to stack in java


Iterate through nested JSON in React JS

Question: I am having trouble finding a way to iterate through this JSON file. The JSON is acquired after calling an API.
I would like to use this JSON for mapping and create components from it.
Problem: How do I navigate through nested JSON and map it?
JSON Format
The JSON format that i received is just as below. I cannot change the file as it is called from an API.
{"animals":{

"dogs":{
    "name": "rex", (required)
    "breed": "yorkshire"}

"cats":{
    "name": "tom", (required)
    "breed": "sphinx"}

    }
}

Goal
Since mapping can be done in an array of objects, the ideal case would be [{dogs},{cats}].
var json = *serializableJSONFormat*
json.map((item)=>{
            <MenuItem value={item.name}>{item.name}</MenuItem>
          })

Comment: What do you want to map to what? Start with defining what the input is and what you expect the output to be. Do you know which keys to expect in the JSON or not? If not, you want to loop over the keys and map those values. If you do know and it are only a few, you can just do a loop for each key.

Currently your "Goal" is some kind of mapping function, not the expected output. What is an `item` in this case?
Comment: can you also write output format, how do you want to format the json
Comment: You probably want the "cats" and "dogs" values to be an array instead of an Object?
Comment: because the mapping is done inside the return(), whenever i put for loops inside, it will show an error instead. So how do I make the json into an array of objects [{dogs},{cats}] in order to map it easily to create the MenuItem components?
Answer: Perhaps you would like something like this:
Object.keys(json["animals"]).map(key => {

  return (
    <MenuItem
      value={json["animals"][key]["name"]}
    >
      {json["animals"][key]["name"]}
    </MenuItem>
  )
})

But as the comments on our questions said, it'd be easier if the "animals" property was an array instead.
Comment: the json format is set by the API, so i can't change it myself. Will try out your solution. Thanks!
Comment: after trying this solution, Object.keys(json["animals"]) returns an array of the keys only. Hence, the array only contains "dogs" and "cats", instead of the whole object
Comment: Yes, but you can use that to iterate over the objects in the json. I made a mistake in my answer. I edited it, try the updated version.
Comment: I see i see, i understand the approach you are going for, but then the results i got is an array of undefined. Will check if i did anything wrong.
Answer: Assuming your JSON is structured like
{"animals":{

"dogs": [
    {
      "name": "rex",
      "breed": "yorkshire"
    }
  ],

"cats":[
    {
      "name": "tom",
      "breed": "sphinx"
    }
  ]
}

(And therefore assuming that every key has an array as value.)
You can loop over all keys and map the arrays
menuItems = [];
animals = YOUR_JSON["animals"];
Object.keys(animals).forEach((key) => {
  menuItems = menuItems.concat(animals[key].map((item)=>{
    <MenuItem value={item.name}>{item.name}</MenuItem>
  }));
}

Comment: btw, i just tried your solution. and let me just say, tears came out hhahah thanks!
Comment: what if the json structure was as stated in the question? sorry for the trouble.
Comment: @montoon88, No trouble ;). If the JSON is as in the question every category of animals can only contain a single animal. `"dogs": { name: "woof" }` vs `"dogs": [ {name: "woof"}, { name: "buster"} ]`
Comment: @montoon88 but if that's what you want, you can remove the `.concat` function around the map and just do `item.name` on each value in "animals".

Iterate through nested JSON in React JS


Is $f(x,y(x))$ a function of two variables? If so, how is that possible?

Question: I don't know how to interpret this function:

Let $D$ be an open subset of $\mathbb{R}^2$ with a continuous function $f:D \rightarrow \mathbb{R}$  and
  \begin{align}
y'(x)=f(x,y(x))
\end{align}
  is a continuous, explicit first-order differential equation defined on $D$.

From $f:\mathbb{R}^2 \rightarrow \mathbb{R}$ I interpret $f$ as a two variable function, $f(x,y)$.
But here $y$ is a function of $x$, so isn't $f(x,y(x))$ a function of one variable, $f:\mathbb{R} \rightarrow \mathbb{R}$?
Comment: A function of $n$ variables takes $n$ parameters. Therefore, $f(x)=0$ is a function of 1 variable and $g(x,y)=0$ is a function of 2 variables even though $(\forall x,y)\,\,\,f=g$ and both functions don't depend on their parameters.
Comment: Sort of but not really.  f takes two variables but g(x) = f(x, y(x)) is not the same thing as f.  It uses f to define it but it isn't f itself.    For example if $f(x,y) = x^2 + 17xy$ takes two veriables but if we define $g(x) = f(x, \sqrt {1- x^2}) = x^2 + 17x(\sqrt{1-x^2})$ that is a function with one variable.  But it isn't $f$.  It is f restricted to limited set of values that are determined by a single variable.
Answer: Note that $f$ is a function of two variables, but the composition $y' = f\circ y$ is a function of one variable, taking as input $x$ and returning $f(x,y(x))$.
Comment: To be pedantic: $f \circ (\operatorname{id} \times y)$.
Comment: Thanks! So we have $f:\mathbb {R}^2 \rightarrow \mathbb{R}$, $y:\mathbb R\rightarrow \mathbb R$ and then the composition is $y':\mathbb R \rightarrow \mathbb R$, i.e. $y'(x)=(f \circ y)(x)$? Right?
Comment: @JDoeDoe Yes, that's right.
Comment: @HansLundmark Is id the identity matrix and $\times$ the cross product?
Comment: @JDoeDoe: It's the identity function and the Cartesian product. Definitions: $\operatorname{id}(x)=x$ and $(f \times g)(x_1,x_2)=(f(x_1),g(x_2))$.
Answer: Why must $f$ be the two-variable function $f(x,y)$? Why can't it be the two-variable function $f(u,v)$ instead?
The point I'm trying to make here is that when we write "$f(x,y)$ is a two-variable function," the $x$ and $y$ in this expression are just placeholders expressing the fact that you need to give $f$ a pair of numbers in order to get a value from it. It is not correct to give these symbols any meaning beyond that in that context; in fact, technically it may be said to be incorrect to say that "$f(x,y)$ is a two-variable function" at all,
because $f(x,y)$ is a notation that denotes the value that $f$ maps the pair $(x,y)$ to, which is a different thing from the function itself.
When we write $y'(x) = f(x,y(x)),$ however, we indicate (somewhat informally) that we have in mind that there is some function named $y$ whose derivative at a value $x$ can be deduced by letting the two-parameter function $f$ map the pair of numbers $x$ and $y(x)$ to the value of the derivative.
Answer: $f$ is a two variables function: $f:\mathbb{R}^2\rightarrow\mathbb{R}$. So, for a given $(x,y)$ it returns a value $f(x,y)$.
Now, $y'$ is a one variable function: $y':\mathbb{R}\rightarrow\mathbb{R}$. So, for a given $(x)$ it returns a value $y'(x)$.
When one states that $y'(x) = f(x,y(x))$; it means that as long $f$ is evaluated in a point of the curve $(x,y(x))$ it will coincide with $y'(x)$.
What is happening is that we are reducing the domain of $f$, so it will only depend on a single parameter.
Answer: Writing $f(x, y(x))$ implies that $y$ is a function of $x$, hence $y'(x)$ is only defined on the subset of $\mathbb{R}^2$ that is on the curve $y(x)$. So, even if $f$ is defined on a larger subset writing $y'(x) = f(x, y(x))$ is restricting $f$ to values on the 1-D curve defined by $y(x)$; in this sense it is a 1-D function (whose value is the slope of the curve $y(x)$ at the point $x$).
However, there is nothing stopping $f$ from being defined on all of $\mathbb{R}^2$, those values just won't be relevant to the differential equation.


How to autoload classes from a 3rd party PHP library

Question: I would like to use a 3rd party PHP library in my module and I wanted to ask what I need to do to autoload the classes?
Example:
Drupal\my_module\MyClass
wants to instantiate
ThirdPartyNamespace\Something\Else\Class1
The official Drupal 8 documentation doesn't really deal with more complex namespacing scenarios.
Comment: See https://drupal.stackexchange.com/questions/86109/how-to-manage-contrib-modules-composer-dependencies-on-drupal-8 and [Composer Manager](https://www.drupal.org/project/composer_manager)
Comment: That other question is a year old, a lot can change in a year in Drupal 8, so not sure where to answer. Composer manager is one way, you can also avoid a hardcoded dependency by shipping with your own autoloader like https://github.com/amateescu/search_api_solr. Or you could even go full composer and build Drupal and the modules with composer, kind of like drush make. I can't find a good resource right now, but people are working on making that happen. The advantage is that it picks up their composer.json files automatically and combines everything.
Comment: @Berdir or @Clive can you tell me where are we with this in 8.1. It says [here](https://www.drupal.org/project/composer_manager) that it supposed to support it in my custom modules but I can't find a way to make this work. I put the `require` statement in my composer.json file in my module folder, then `composer install` but Drupal still says that he can't find my lib.
Comment: You need to install your module with composer too so that it knows about your dependencies. See https://www.drupal.org/node/2404989. If it is a custom module, you need to add them to the main composer.json yourself.
Comment: @berdir if I am not mistaken, composer doesn't install a module in drupal, it simply downloads the libs. I can't see why I need to add my needed libs in the module's composer.json AND the one from the root. And if I need to put it in the root composer.json then I am modifying the Drupal's git and I need to manage another branch of the Drupal's git just for that file. Drupal should be able to include all libs from all composer.json not only the one from the root.
Comment: @berdir Note that I am using Drupal 8.1
Answer: Drupal use composer to manage the 3rd party libraries (Symfony, guzzle, etc...).
The problem is Drupal has versioned the vendor folder into the core directory; it is a problem because, if you added a new library in the root composer, you change the vendor directory and change the composer.json/composer.lock. So, if Drupal releases a new version, your changes will be deleted.
The Composer Manager module is created to solve the problem. You need to include a composer.json file in your module; the Composer Manager module downloads the library and registers a new autoload file (the second autoload).
The problem with this is only when you need use a middle-ware library, since the Composer Manager module registers a new autoload in the Request Kernel Event. This event is called after the middle-ware so this library is not available in the middle-ware layer.
In most cases, the Composer Manager module is the best solution to add new vendors.
There is the issue Remove external dependencies from the core repo and let Composer manage the dependencies instead.
Comment: Please note as of drupal 8.1 composer manager is no longer needed. The reccomended way is to modify the composer.json that ships with drupal in drupal root. Checkout https://github.com/drupal-composer/drupal-scaffold.
Comment: It is not recommended to initiate compose within a module directory. It is better to change the root composer file to include the dependency. And since recent it is even possible to require Drupal modules in the root composer file, which will install all dependencies of these module as well.
Answer: I edited the composer.json in the root of my Drupal project and in the module that relies on the library.
Then I loaded the main class using a fixed path:
require_once (\Drupal::root() . '/vendor/campaignmonitor/createsend-php/csrest_general.php');

Then I noticed having an issue with instantiating an object of the class:
$wrap = new CS_REST_General($auth);

So apparently you need to add a '\' eg:
$wrap = new \CS_REST_General($auth);

Comment: I think you only needed to do this because `campaignmonitor/createsend-php` does not abide by the PSR-0 or PSR-4 standards because it's so old it was written before those standards were adopted, and thus you cannot use the autoloader. This answer is fairly specific to this library, but you should explain in your answer more about *why* you needed to added `\` (because of namespaces) and why it may be necessary for libraries that are this old.
Answer: Seems that the current answers are all outdated. When you use Composer to manage your project's dependencies, preferably with drupal-composer/drupal-project, all you need to do is to require a package in your project-root's composer.json and then load it's classes wherever you need them.
$ cd MYPROJECT
$ composer require ramsey/uuid

Then in your custom module just use it.
use Ramsey\Uuid\Uuid;

To let your custom module provide its own composer.json you can add wikimedia/composer-merge-plugin to your project-root's composer.json and in the "extra": {} section configure it to include other composer.json located at a certain directory pattern.
"merge-plugin": {
    "include": [
        "web/modules/custom/*/composer.json"
    ]
},

Everything else is taken care of by Drupal.


Topology on the extended real line

Question: In our real analysis class we are working through 'Real and Complex Analysis' by Rudin and covered topological spaces (but not bases, subbases and other ways of generating  topologies, so I can't use these in the exercise).
Let $\tau =$ the collection of sets $(a,b),[-\infty,a),(a,\infty]$ and any union of these types. Show that $\tau$ is a topology.
Here's my approach:

$\mathbb{R} \in \tau$ since $\mathbb{R} = [-\infty,a)\cup(a,\infty]$. $\emptyset \in \tau$.
For any $A_1,A_2,\ldots \in \tau,$ we have $\bigcup_{i \in I} A_i = \bigcup_{i \in I} (a_i,b_i) \in \tau.$
For any $A_1,\ldots,A_n \in \tau$, we have $\bigcap_{i=1}^n (a_i,b_i) \in \tau.$

However, I feel like my approach is too naive and I'm missing some details.
Comment: The problem in 3. is to show that the intersection of (unions of) intervals at hand is contained in $\tau$, that is, to prove that this intersection of (unions of) intervals is a union of intervals.
Comment: The extended real line is $X = \mathbb{R} \cup \{\pm \infty\}$? If so, then you have to replace $\mathbb{R}$ in 1. with $X$ and this would almost work (you are missing $a$ on the left hand side in 1. but this is easily fixed by taking $[-\infty,1) \cup (0,\infty]$ or something similar). In 2. and 3. you took $A_i$ to be some interval $(a_i,b_i)$ which you cannot assume as $\tau$ contains many sets which are not intervals but union of intervals. The union of the union of intervals is still a union of intervals, so 2. is still easy. But in 3. you really have to prove something which you did not.
Comment: This is strange, as $(-\infty,\infty)$ is just $\mathbb{R}$. Are you sure you do not mean $[-\infty,\infty]$ in the sense of $\mathbb{R} \cup \{-\infty,\infty\}$?
Comment: I might have made a mistake when taking notes since I was sitting in the back and from afar the brackets looks similar. In the book, $[-\infty,\infty]$ is used to that appears to be the case.
Comment: Could you please elaborate on this part: "But in 3. you really have to prove something which you did not"?
Comment: I would be very grateful if you could take a look at my answer.
Comment: In general, this type of construction is called the order topology. You can define it on any totally ordered set.
Answer: Ok here is my attempt at another answer, please comment if there are still some parts missing/wrong.
Let $\overline{\mathbb{R}} = [-\infty,\infty]$ and let $b <a$. Then we have $\overline{\mathbb{R}} = [-\infty,a) \cup (b,\infty] \in \tau$. Next, let $a =b$ so that $(a,b) = \emptyset \in \tau$.
Now, we define $A = \bigcup_{j \in J} A_j = \bigcup_{j \in J}\left(\bigcup_{i \in I}(a_i,b_i)\right)$. Then $A \in \tau$ since the unions of the unions of intervals is a union of intervals, which are in $\tau$.
Last, we define $A = \bigcap_{j \in J} A_j = \bigcap_{j \in J} \left(\bigcup_{i \in I}(a_i,b_i)\right).$ Then, for any $x \in \bigcup_{i \in I} (a_i,b_i),$ $x \in A$ and so A is open. (this doesn't feel correct..)
Comment: Your $A_j$ are still not arbitrary elements of $\tau$. Note that a typical element of $\tau$ is of the form $\bigcup_{r} [-\infty,x_r) \cup \bigcup_{s} (a_s,b_s) \cup \bigcup_{t} (y_t , \infty]$, so you have to take your $A_j$ to be of this form. Also note that the index sets used to describe $A_j$ as a union of intervals depends on $j$. As for the part concerning the finite (!) intersection of the $A_j$, you are supposed to show that for any $x \in \bigcap_{j} A_j$ there exists an interval $[-\infty,a_x)$, $(b_x,c_x)$ or $(d_x,\infty]$ containing $x$ and being contained in $\bigcap_{j} A_j$.

Topology on the extended real line


18TB with ext4 filesystem

Question: I have the server with 4 disks 6TB each. At start disks were configured as RAID 10 and I had 11TB partition with ex4 filesystem on it. I grew up RAID from level 10 to 5 and now it's 17.9TB. After reconfiguring RAID I used resize2fs for resize partition, but with ext4 32 bit it give me only 16TB available space. How can I use more than 16TB?
This is parted print information:
GNU Parted 3.2

Using /dev/md3

Welcome to GNU Parted! Type 'help' to view a list of commands.

(parted) p

Model: Linux Software RAID Array (md)

Disk /dev/md3: 17.9TB

Sector size (logical/physical): 512B/4096B

Partition Table: loop

Disk Flags:

Number  Start  End     Size    File system  Flags

1      0.00B  17.9TB  17.9TB  ext4

This is available space:
df -h

Filesystem      Size

/dev/md3         16T

Maybe I can create second partition?
Thanks.
Comment: Don't use RAID5. It's obsolete.
Comment: What Sven says - PLEASE don't use R5, it's staggeringly dangerous, especially with big/slow disks.
Comment: try to use future auto_64-bit_support = 1 in /etc/mke2fs.conf
Comment: I really second what Sven said. Unrecoverable read errors are a matter of statistic. With 100 GB drives, you don't run into this. With today's disks, you're almost guaranteed to have at least one on a full disk read. With RAID5, that means a high probability of failure on rebuild.
Answer: It is a limitation of x32 ext4. Check this link as a possible workaround. Don't use RAID-5 for spindle drives especially for 6TB drives. Just imagine the time of rebuilding the RAID array in case if your disk will fail and very poor write performance.
Comment: Unfortunayely I can't convert ext4 to 64 bit, because of server run with Debian Jessie 3.16 kernel. Is it possible to use space another way, like second volume maybe? How can I create a second volume in this situation?

18TB with ext4 filesystem


nao estou achando o erro de syntax error, unexpected end of file in o navegador apontar na linha 88

Question: <?php
require_once("".$_SERVER["DOCUMENT_ROOT"]."/funcoes.php");
require_once("".$_SERVER["DOCUMENT_ROOT"]."/mistake.php");
$whom = anti_sql($_GET["a"]);
if($whom>0){
setcookie("indicado", $whom, (time() + (86400 * 7)));
header("Location: /cadastro");
}
$logo3 = getlogo();
$progra = $mistake->query("SELECT width,height FROM Mmistake_settings WHERE name='logo'")->fetch();
echo"

";
$alink[0] = "Uma Comunidade Diferente";
$alink[1] = "Variados Entreterimentos";
$alink[2] = "Bem vindo";
$alink[3] = "Conteudos Para Celular";
$alink[4] = "Venha Fazer Muitos Amigos";
$alink[5] = "Entre e Divirta-se é Gratuito";
$alinks = rand(0,5);
if($_COOKIE['autologin'] == '1'){
$uidmc = anti_sql($_COOKIE['usuario']);
$uid = getuid_sid($sid);
if($uidmc>0){
$avlink = getavatarmistakepm($uidmc);
?>

<headerm><big>☰
☰</big>

Seja Bem Vindo <?php echo getnick_uid($uidmc);?>
Deseja Logar?

<?php echo $avlink;?>

<form action='/login' method="POST">
<input type='text' placeholder='username' name='usuario' value='<?php echo $_COOKIE[login]; ?>' maxlength='0' title='SEU LOGIN' readonly>
<input type='password' placeholder='password' name='senha' maxlength='0' value='<?php echo $_COOKIE[senha]; ?>' title='SUA SENHA' readonly>

Memorizar login e senha<input type='checkbox' checked='checked' name='ps' id='ps' value='1'/>

Login Automatico?<input type='checkbox' checked='checked' name='autologin' id='autologin' value='1'/>

<input type='submit' value='Entrar'/>
</form>
</headerm>

<?
}
}else{
?>

<headerm><big>☰
☰</big>

<?php echo $alink[$alinks];?>
Deseja Logar?

<?
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
$modoativo = "Modo Normal ";
}else{
$modoativo = "Modo Seguro ";
}
?>
Cadastrar
<?php echo $modoativo;?>
Redefinir Senha

<form action='/login' method='POST'>
Login ou E-mail:

<input type='text' name='usuario' maxlength='250' placeholder='Login Ou E-mail' value='<?php echo $_COOKIE[login]; ?>'/>

Senha:

<input type='password' name='Senha' maxlength='25' placeholder='Digite Sua Senha' value='<?php echo $_COOKIE[senha]; ?>'/>

Memorizar login e senha<input type='checkbox' checked='checked' name='ps' id='ps' value='1'/>

Login Automatico?<input type='checkbox' checked='checked' name='autologin' id='autologin' value='1'/>

<input type='submit' value='➦ Entrar'/></form>
<?
echo '</headerm>
';
$sql = "SELECT id FROM Mmistake_users WHERE confirmacodigo>'0' AND avatar!='imagens/semfoto.png' ORDER BY rand() LIMIT 3";
$query = $mistake->query($sql);
if($query->rowCount()>0){
$x = 0;
while ($item = $query->fetch()){
echo"";
$x++;
}
}
}
echo"";
require_once("useronline.php");
rodape();
?>

Comment: Rosenildo, descreva sua dúvida e faça sua pergunta pois esta parecendo que você quer alguém faça o seu trabalho...
Comment: Por favor não traduza as mensagens de erro. Obs: não fui eu quem negativou a pergunta.
Comment: meu erro de sinttaxe na linha 88 nao estou achando
Comment: Eu te entendo, mas tenta editar a pergunta para explicar isso.
Comment: ok   ja arrumei ver se me ajudar eu agradeço
Answer: No seu caso parece que foi os lugares que usou <? ao invés de <?php, isto porque o short_tag deve estar inativo, fora que aqui faltou os apóstrofos/aspas em $_COOKIE[usuario] e $_COOKIE[senha] (o que apenas causaria warnings):
<input type='text' placeholder='username' name='usuario' value='<? echo $_COOKIE[login]; ?>' maxlength='0' title='SEU LOGIN' readonly>
<input type='password' placeholder='password' name='senha' maxlength='0' value='<? echo $_COOKIE[senha]; ?>' title='SUA SENHA' readonly>

código ajustado:
<?php
require_once("".$_SERVER["DOCUMENT_ROOT"]."/funcoes.php");
require_once("".$_SERVER["DOCUMENT_ROOT"]."/mistake.php");
$whom = anti_sql($_GET["a"]);
if($whom>0){
setcookie("indicado", $whom, (time() + (86400 * 7)));
header("Location: /cadastro");
}
$logo3 = getlogo();
$progra = $mistake->query("SELECT width,height FROM Mmistake_settings WHERE name='logo'")->fetch();
echo"

";
$alink[0] = "Uma Comunidade Diferente";
$alink[1] = "Variados Entreterimentos";
$alink[2] = "Bem vindo";
$alink[3] = "Conteudos Para Celular";
$alink[4] = "Venha Fazer Muitos Amigos";
$alink[5] = "Entre e Divirta-se é Gratuito";
$alinks = rand(0,5);
if($_COOKIE['autologin'] == '1'){
$uidmc = anti_sql($_COOKIE['usuario']);
$uid = getuid_sid($sid);
if($uidmc>0){
$avlink = getavatarmistakepm($uidmc);
?>

<headerm><big>☰
☰</big>

Seja Bem Vindo <?phpphp echo getnick_uid($uidmc);?>
Deseja Logar?

<?phpphp echo $avlink;?>

<form action='/login' method="POST">
<input type='text' placeholder='username' name='usuario' value='<?phpphp echo $_COOKIE[login]; ?>' maxlength='0' title='SEU LOGIN' readonly>
<input type='password' placeholder='password' name='senha' maxlength='0' value='<?phpphp echo $_COOKIE[senha]; ?>' title='SUA SENHA' readonly>

Memorizar login e senha<input type='checkbox' checked='checked' name='ps' id='ps' value='1'/>

Login Automatico?<input type='checkbox' checked='checked' name='autologin' id='autologin' value='1'/>

<input type='submit' value='Entrar'/>
</form>
</headerm>

<?php
}
}else{
?>

<headerm><big>☰
☰</big>

<?phpphp echo $alink[$alinks];?>
Deseja Logar?

<?php
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
$modoativo = "Modo Normal ";
}else{
$modoativo = "Modo Seguro ";
}
?>
Cadastrar
<?phpphp echo $modoativo;?>
Redefinir Senha

<form action='/login' method='POST'>
Login ou E-mail:

<input type='text' name='usuario' maxlength='250' placeholder='Login Ou E-mail' value='<?phpphp echo $_COOKIE['login']; ?>'/>

Senha:

<input type='password' name='Senha' maxlength='25' placeholder='Digite Sua Senha' value='<?phpphp echo $_COOKIE['senha']; ?>'/>

Memorizar login e senha<input type='checkbox' checked='checked' name='ps' id='ps' value='1'/>

Login Automatico?<input type='checkbox' checked='checked' name='autologin' id='autologin' value='1'/>

<input type='submit' value='➦ Entrar'/></form>
<?php
echo '</headerm>
';
$sql = "SELECT id FROM Mmistake_users WHERE confirmacodigo>'0' AND avatar!='imagens/semfoto.png' ORDER BY rand() LIMIT 3";
$query = $mistake->query($sql);
if($query->rowCount()>0){
$x = 0;
while ($item = $query->fetch()){
echo"";
$x++;
}
}
}
echo"";
require_once("useronline.php");
rodape();
?>

Nota: realmente acho que deveria pensar em identar melhor teu código como expliquei nesta resposta Script retornando Parse error: syntax error, unexpected end of file
Comment: ainda deu erro outro
Comment: @ROSENILDOBARROSDEALMEIDA qual erro? "Ainda deu erro outro" não é informação o suficiente para entendermos.


One predictor is a linear combination of another

Question: If I try and fit the linear regression
lm(y~V1+V3,data=x)

with data:
structure(list(V1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L
), .Label = c("A", "B", "C", "D"), class = "factor"), V2 = c(14.95,
    14.95, 14.95, 14.95, 14.95, 14.95, 14.95, 14.95, 14.95, 14.95,
    12.59, 12.59, 12.59, 12.59, 12.59, 12.59, 12.59, 12.59, 12.59,
    12.59, 10.55, 10.55, 10.55, 10.55, 10.55, 10.55, 10.55, 10.55,
    10.55, 10.55, 15.5, 15.5, 15.5, 15.5, 15.5, 15.5, 15.5, 15.5,
    15.5, 15.5), V3 = c(3.33, 3.33, 3.33, 3.33, 3.33, 3.33, 3.33,
    3.33, 3.33, 3.33, 3.99, 3.99, 3.99, 3.99, 3.99, 3.99, 3.99, 3.99,
    3.99, 3.99, 4.02, 4.02, 4.02, 4.02, 4.02, 4.02, 4.02, 4.02, 4.02,
    4.02, 3.96, 3.96, 3.96, 3.96, 3.96, 3.96, 3.96, 3.96, 3.96, 3.96
    ), y = c(3.87904870689558, 4.53964502103344, 8.11741662829825,
    5.14101678284915, 5.25857547032189, 8.43012997376656, 5.9218324119784,
    2.46987753078693, 3.62629429621295, 4.10867605980008, 4.44816359487892,
    2.71962765411473, 2.8015429011881, 2.22136543189024, 0.88831773049185,
    5.57382627360616, 2.99570095645848, -1.93323431325928, 3.40271180312737,
    1.05441718454413, -3.54258964789476, 3.25620068273364, -3.20803558645792,
    -0.831129834329122, -0.000314142794054927, -8.49354648593931,
    11.7022963559562, 6.22698494269212, -4.10509549609558, 15.0305193685594,
    -1.98486866562679, 3.77692131760739, 3.26675717101425, 13.2397209466905,
    6.33304746822537, 9.02654811195804, 6.77162595721038, 6.65703634166947,
    17.9488182721157, 5.19383211472586)), .Names = c("V1", "V2",
    "V3", "y"), row.names = c(NA, -40L), class = "data.frame"

the coefficient on V3 is NA. I assume this is because somehow V3 is a linear combination of V1.
V1 is a factor that seems to default to dummy coding with the level 'A' set as the reference level. So, how is there a perfect linear combination in V3 and dummy codes for 'B', 'C', and 'D' (as I assume 'A' is the reference level)"?
Comment: Thanks for including the data, it makes it much easier to respond in specific terms.
Comment: The simplest way to see that V3 is a linear combination of V1 is to look at the data - everyone in Level "A" scored 3.33 on V3, everyone in Level "B" scored 3.99, and so on. If any scores on V3 deviated from the others in a particular level of V1, even just a bit, V3 would no longer be a linear combination of V1.  However, since everyone in each group obtained the same score, you could use V1 or V3 as your grouping factor and it wouldn't make any difference.  They are perfectly collinear.
Answer: It's easy to see that V3 is a linear combination of the levels of V1:
summary(lm(V3~V1,data=x))

Like so:
Coefficients:
             Estimate Std. Error   t value Pr(>|t|)
(Intercept) 3.330e+00  1.016e-15 3.278e+15   <2e-16 ***
V1B         6.600e-01  1.437e-15 4.593e+14   <2e-16 ***
V1C         6.900e-01  1.437e-15 4.802e+14   <2e-16 ***
V1D         6.300e-01  1.437e-15 4.385e+14   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.213e-15 on 36 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 1.061e+29 on 3 and 36 DF,  p-value: < 2.2e-16

The residual standard error is just accumulated numerical error.
You may also find this form useful in this case: summary(lm(V3~V1+0,data=x))
Answer: This is what your covariates matrix looks like:
$\begin{pmatrix}
1 & 0 & 0 & 0 & \alpha \\
1 & 1 & 0 & 0 & \beta \\
1 & 0 & 1 & 0 & \gamma \\
1 & 0 & 0 & 1 & \delta \\
\end{pmatrix}$
First column is for the intercept, the last is for V3 and the other three for are for V1 (already excluded the first column) .
By substracting the first column by the last divided by $\alpha$, we have:
$\begin{pmatrix}
1-\alpha/\alpha & 0 & 0 & 0 & \alpha \\
1-\beta/\alpha & \beta & 0 & 0 & \beta \\
1-\gamma/\alpha & 0 & \gamma & 0 & \gamma \\
1-\delta/\alpha & 0 & 0 & \delta & \delta \\
\end{pmatrix}$
$\begin{pmatrix}
0 & 0 & 0 & 0 & \alpha \\
1-\beta/\alpha & \beta & 0 & 0 & \beta \\
1-\gamma/\alpha & 0 & \gamma & 0 & \gamma \\
1-\delta/\alpha & 0 & 0 & \delta & \delta \\
\end{pmatrix}$
Now subtracting the first column by a each column of V1 multiplied by a scalar:
$\begin{pmatrix}
0 & 0 & 0 & 0 & \alpha \\
0 & \beta & 0 & 0 & \beta \\
0 & 0 & \gamma & 0 & \gamma \\
0 & 0 & 0 & \delta & \delta \\
\end{pmatrix}$
So, for any $\alpha, \beta, \gamma$ and $\delta$ you have perfect multicollinearity.
Comment: Yes, it is, given three vectors, A, B and C, they are linear depend (same thing as perfect multicollinearity for the covariate smatrix) if and only if, there exists x,y,z not all equal to 0 such that: $xA + yB + zC = 0$ (0 here means the vector where all it's members are 0). Now, if we multiply $xA$ by the scalar 2, you'll have: 2xA + yB + zC = 0: but wait, if there exists x,y,z not all equal to 0 such that: xA + yB + zC = 0, then there exist x,y,z not all equal to 0 such that: 2xA + yB + zC = 0.
Comment: So, those operations with columns were only a way to make easier for us to see that those vectors are linear dependent. But we can always think in a single step starting by the first matrix of my answer: there exist scalars, not all equal to 0, that multiply each vector (column of the matrix of covariates) that will make their sum equal to zero, it'll just be more difficult to find them directly. In the last matrix, however, it's easy to see that any scalar multiplying the first column and the 0 multiplying the other columns will yield the 0 vector.
Comment: I forgot about the intercept (1's)! One question on the last step (matrix) :  I would have thought the last column would be exactly the same as one of the others - but it is not given all zeros in the first row except for the last column.
Comment: Sorry, but I haven't understood what is the question you mean in your comment, or your comment wasn't a question, but only a remark?
Comment: My question was that I expected perfect multicollinearity to show that one of the columns was a linear combination of the others. But that is not possible is it?


Redirect if URL does not match

Question: I am using D7.
I am attempting to create a redirect in my .htaccess file that will redirect the page if the path doesn't match a pattern.
<code># only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# only if URI contains "library"
RewriteCond %{REQUEST_URI} !^/Library$ [NC]
# rewrite the URL
RewriteRule ^(.*)$ http://otherdomain.org/$1 [R=301,L]
</code>
This works fine for most of the site (e.g. http://mysite.domain.org/blogs is redirected to http://otherdomain.org/blogs
However, http://mysite.domain.org/Library?id=1234 is being redirected but to http://otherdomain.org?id=1234 ("library" in URI is missing but this shouldn't redirect at all)
What am I missing?  Am I running into Drupal URL rewriting rules?
Comment: Hello, and welcome to Drupal Answers. Did you write those rules before, or after the ones used by Drupal?
Comment: They come right before the index.php section
Comment: FYI.  I couldn't get this to work but I am not sure if Drupal's own internal functions were interfering.  We abandoned this for a different solution.
Answer: Try this:
<code># only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# rewrite the URL
RewriteRule ^((?!Library).*)$ http://otherdomain.org/$1 [R=301,L]
</code>
The (?!Library) should look ahead, and the match should fail if "Library" is present. Hope this works for you.
Comment: oops. It's been too long since my Perl days. Try this instead: **RewriteRule ^((?!Library).)*$ http://otherdomain.org/$1 [R=301,L]**.
Comment: Getting a 500 error.  `RewriteRule: bad flag delimiters`
Comment: Fixed.  I had a space between the flags.
Comment: Its not failing with "library" in the URL. Its still rewriting the URL.
Comment: Library or library? It will be case sensitive.
Comment: I have tried it both ways and with NC flag.  Same results.  The actual URL I am trying to rewrite is "Library".

Redirect if URL does not match


Wagtail admin - default ordering of child pages

Question: In the admin area I have to activate the "Enable ordering of child pages" every time. Is there a way to set this as a permanent option? The main problem is that the listing in the child pages view changes depending on if this is activated or not(if you have changed the ordering), which might be a bit confusing for some.
Potentially one could change the default ordering of the children list to match the manually ordered list somehow?
Answer: Ok, as of now. It doesn't seem that this is possible. But it does seem that it respects django models default ordering. https://docs.djangoproject.com/en/2.1/ref/models/options/#ordering
Comment: No it doesn't.
https://docs.wagtail.io/en/stable/topics/pages.html#page-queryset-ordering
Answer: Setting the Meta.ordering on the ChildPage model didn't work for me, but overriding the Parent Page's get_children() method by returning the ordered QuerySet resolved the child page order issue.
class MyRootPage(Page):
    description = models.CharField(max_length=255, blank=True)

    content_panels = Page.content_panels + [FieldPanel("description", classname="full")]

    def get_children(self):
        qs = super().get_children()
        qs = qs.order_by('-last_published_at')
        return qs


What are module-info mode switch statements?

Question: The package Environment Modules defines the module-info mode command.  The man page for modulefile lists the possible modes as:
load, remove, display, help, whatis, switch, switch1, switch2, or switch3.

What are the multiple switch statements?
Answer: Couldn't find this documented anywhere, so I figured it out and want to share with you.  Here's my explanation.  Consider the following:
module load a
module swap a b

Here's what's executed under the hood by environment modules for each statement:

module load a

[ module-info mode ] == "load" for modulefile a

module swap a b

[module-info mode] == "switch1" for modulefile a. This should unset prereqs and is similar to remove
[module-info mode] == "switch2" for modulefile b. This should add any dependencies. Simliar to "load"
[module-info mode] == "switch3" for modulefile a. Not sure why you'd need this.
Comment: I confess to never having understood the `module` stuff at all. (I don't use it on any of my systems.) Alas, this means I've got no idea whether your answer is right. However, it does sound like a multi-stage swap where there's some sort of transfer of responsibility. Can the state changes fail? If `switch2` can fail, that's a reason to have `switch3` (and that pattern in general)…


python function call inheritance

Question: I am new guy. Here is an example from python document.
def funtest(num, L=[]):
    L.append(num)
    return L
print(funtest(2))
print(funtest(3))
print(funtest(4))

I thought very function call should execute the same thing, which means L=[] in very function call. so I though the output should like this:
[2]
[3]
[4]

but the real answer is in below. It looks like the funtest() inherited the output from the last function call. And then continually pass it to next function call. I am confusing to it.
[2]
[2, 3]
[2, 3, 4]

When I change the code to below case:
def funtest(L=[]):
    L.append(L)
    return L
print(funtest([2]))
print(funtest([3]))
print(funtest([4]))

the real output go to this:
[2, [...]]
[3, [...]]
[4, [...]]

The output are quite different with the previous one. I am more confused now. Does anyone repair my mind shot? Thanks a lot
Comment: Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument)
Comment: @AlanHoover Yes. I did not search it before.
Answer: The problem is that the default value of L is a mutable object (in your case an empty list).
In Python default values are evaluated at function definition time.
Every time you call the function, you get the same default value and if you add any content to the object (the list) you'll get all the previously added content.
The correct way to get a default list (or dictionary, or set) is to create it at run time inside the function.
This is a common mistake in Python with beginners devs.
You would like to read similar questions:
"Least Astonishment" and the Mutable Default Argument
Good uses for mutable function argument default values?
Answer: to explain what is happening ,
1st case
so the default values in python functions are instantiated only once , only while defining the function , so the list is only created while defining the function and you keep adding to it so now the result contains all the older values
this is true for all values which are mutable when used as default value for arguments in python
what can you do ?
in general use immutable values , and for the case of list you use None as the default value and in the function you check if list is None and create one empty list inside the function
read more here ( the first gotcha ) : https://docs.python-guide.org/writing/gotchas/
2nd case
now you are actually creating infinite list by appending same list to itself when you are doing L.append(L)
and whenever a list is too large to print , python shows those three dots in its place
read more here What does [...] (an ellipsis) in a list mean in Python?
Comment: L is empty at beginning, why it go to infinite by L.append(L)? I mean it is just none append none. Thanks. I got it.
Comment: you are calling it with [2]
Comment: and yes recursively adding empty list to itself will also go to infinity
Comment: why the second case did not show output like this: [2, [...]]
[2,3, [...]]
[2,3,4, [...]]
Answer: move L to inside of function
def funtest(num):
    L=[]
    L.append(num)
    return L
print(funtest(2))
print(funtest(3))
print(funtest(4))

this re set the L
Comment: While moving L=[] inside the function solves your problem, accumulation can be a useful feature. You can reset it by calling the function with a blank list:  print(funtest(5,[]))

python function call inheritance


How to migrate from cp-enterprise-kafka:6.2.1 to cp-kafka:6.2.1 docker image? It fails for me

Question: When I change the image in docker-compose.yml from enterprise cp-enterprise-kafka to regular cp-kafka
it fails to start with:
broker-1       | [2021-10-19 09:22:32,042] WARN [RequestSendThread controllerId=1] Controller 1 epoch 38 fails to send request (type: UpdateMetadataRequest=, controllerId=1, controllerEpoch=38, brokerEpoch=7362, partitionStates=[], liveBrokers=UpdateMetadataBroker(id=1, v0Host='', v0Port=0, endpoints=[UpdateMetadataEndpoint(port=19092, host='broker-1', listener='INSIDE', securityProtocol=0), UpdateMetadataEndpoint(port=9092, host='192.168.100.14', listener='OUTSIDE', securityProtocol=0)], rack=null)) to broker broker-1:19092 (id: 1 rack: null). Reconnecting to broker. (kafka.controller.RequestSendThread)
broker-1       | java.io.IOException: Client was shutdown before response was read
broker-1       |        at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:109)
broker-1       |        at kafka.controller.RequestSendThread.doWork(ControllerChannelManager.scala:253)
broker-1       |        at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
broker-1       | [2021-10-19 09:22:32,045] ERROR [RequestSendThread controllerId=1] Controller 1 fails to send a request to broker broker-1:19092 (id: 1 rack: null) (kafka.controller.RequestSendThread)
broker-1       | java.lang.InterruptedException
broker-1       |        at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1367)
broker-1       |        at java.base/java.util.concurrent.CountDownLatch.await(CountDownLatch.java:278)
broker-1       |        at kafka.utils.ShutdownableThread.pause(ShutdownableThread.scala:82)
broker-1       |        at kafka.controller.RequestSendThread.doWork(ControllerChannelManager.scala:234)
broker-1       |        at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)

My config in docker-compose.yml is:
version: '3'

services:
  zookeeper-1:
    image: confluentinc/cp-zookeeper:6.2.1
    hostname: zookeeper-1
    container_name: zookeeper-1
    ports:
      - "2181:2181"
      - "2888:2888"
      - "3888:3888"
    environment:
      ZOOKEEPER_SERVER_ID: 1
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    volumes:
      - ./kafka-data/zookeeper-1:/var/lib/zookeeper/data
      - ./kafka-data/zookeeper-logs-1:/var/lib/zookeeper/log
    networks:
      - mynet

  broker-1:
    image: confluentinc/cp-enterprise-kafka:6.2.1
    hostname: broker-1
    container_name: broker-1
    depends_on:
      - zookeeper-1
    ports:
      - "9092:9092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: '192.168.100.14:2181'

      KAFKA_LISTENERS: OUTSIDE://0.0.0.0:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: OUTSIDE:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: OUTSIDE://192.168.100.14:9092
      KAFKA_INTER_BROKER_LISTENER_NAME: OUTSIDE

      KAFKA_LOG_MESSAGE_TIMESTAMP_TYPE: 'LogAppendTime'

      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONNECTIONS_MAX_IDLE_MS: 31536000000 # 1 year

      CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: 192.168.100.14:9092
      CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: 192.168.100.14:2181
      CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      CONFLUENT_METRICS_ENABLE: 'true'
      CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'
    volumes:
      - ./kafka-data/kafka-1:/var/lib/kafka/data
    networks:
      - mynet

networks:
  mynet:
    driver: bridge

i.e. I change only broker-1 image from cp-enterprise-kafka to cp-kafka.
I noticed that controllerEpoch is much lesser than brokerEpoch - maybe this is a reason?
Any ideas? Thanks!
Comment: I don't know how but I resolved my issue with manipulation zookeeper data, I copied existing to backup place, then start then got error wrong cluster from broker, then copied all back and run again - bingo! :-D
Comment: If you also wipe the data volumes, then what happens?
Comment: it's not an option to wipe data, that's why I'm asking this question :-)
but maybe zookeeper. I know that kafka stores consumers offsets in the broker. is it safe to wipe zookeper data?
Comment: Zookeeper data stores the actual topic names and configurations... So no. In any case, please add logs as text, not an image
Comment: Nice. Feel free to provide your solution below rather than as a comment
Comment: Added how it worked for me, but not sure about steps (maybe redudant steps with backup). Issue was 100% in zookeeper.
Comment: Please revert the question section and post in the box below as an answer
Comment: I've rolled back your question since you've now correctly posted the answer as an answer.
Answer: RESOLVED (but don't know how exactly):

stopped zookeeper and broker
copy all zookeeper data (backup)
start zookeeper and broker and got this (wrong cluster):

broker-1       | [2021-10-19 09:25:25,648] ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
broker-1       | kafka.common.InconsistentClusterIdException: The Cluster ID MlRI76IVQ8y4nTZgigyUGw doesn't match stored clusterId Some(HXaFk1peQcaR23TAqh0Z2g) in meta.properties. The broker is trying to join the wrong cluster. Configured zookeeper.connect may be wrong.
broker-1       |        at kafka.server.KafkaServer.startup(KafkaServer.scala:218)
broker-1       |        at kafka.Kafka$.main(Kafka.scala:109)
broker-1       |        at kafka.Kafka.main(Kafka.scala)

stopped zookeeper and broker
copied (backed up previously) zookeeper data back
started... and all starts ok!

Maybe even zookeeper data backup not needed at all and it's fine just to change broker's cluster.id inside /var/lib/kafka/data/meta.properties


como carregar dados de uma pagina de acordo com o ID clicado?

Question: O que eu quero é bem simples, quero que ao clicar no nome da pessoa, carregue uma outra pagina com os dados completos da pessoa de acordo com os dados clicados anteriormente e ali eu possa editar os dados dessa pessoa e salvar no dessa pessoa no Banco de Dados MYSQL.
Comment: o que você já fez?
Comment: so o login ate agora, e a pagina que vai receber os dados
Comment: Mas a sua dúvida é como passar esse id, ou como consultar. Coloque código se possivel, para exemplificar melhor
Comment: Como colocar ele no Href para ir para outra pagina e nesta pagina carregar os dados do id que cliquei antes e ali começar a trabalhar com o cadastro dessa pessoa
Comment: @williamDePaula é daquela forma que voce quer? Como respondi ali?
Comment: É assim mesmo, muito obrigado
Comment: @WilliamDePaula marque como resposta então :)
Comment: Possível duplicata de [Passar dados pelo link - aplicação php](http://pt.stackoverflow.com/questions/117858/passar-dados-pelo-link-aplica%c3%a7%c3%a3o-php)
Answer: Um método simples e sem tratamento, é você utilizar o metodo $_GET. Voce pode passar pelo link da seguinte forma:

Esse 5no caso, é o seu id, que você vai recuperar na outra pagina da seguinte forma. Na pagina.php , você faria:
$id=$_GET['id'];

Espero ter ajudado!


Why are my compiled linq queries slow the first time?

Question: We've recently started using complied queries in order to improve performance on our Linq to SQL setup. There are several queries that always take multiple seconds to run the first time take under a second in subsequent runs. This appears to be because the compilation doesn't actually take place until the call is made the first time.
Is there an easy way to force this compilation to happen during the compilation of the program or at the very least during startup?
EDIT:
So from the comments I'm seeing it looks like linq queries are definitely not compiled until the call is made. Righ now I'm writing my queries like this:
static readonly Func<DataContext, int, IQueryable<Item>> getByPLUComp =
    CompiledQuery.Compile<DataContext, int, IQueryable<Item>>((db, PLU) =>
            from i in db.Items
            where i.IntPLU == PLU && i.Terminated == null
            select i);

I have a bunch of these static readonly Funcs floating around. Is there an easy way I can have my program run around and initialize them on startup so the cost is incurred there rather than during regular use?
EDIT 2:
One last try before I give up on this question. To fix this problem I've just added calls to the compiled queries during the initialization of my program. For example:
public void Initialize()
{
    DataContext db = new DataContext();
    getByPLUComp(db, 0);
}

Is there a more elegant way to force compilation without just running the query and throwing away the results?
Comment: You may find this series of blog posts interesting: http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx -- you're right, compiled queries aren't actually compiled until they're first used. One of these posts should shed a bit of light on why this policy exists.
Comment: Are you sure its not just because you're making a connection to the database for the first time?  Or that the delay is not from the sql server side, a caching issue on that end?
Comment: The query in question is not the first query that is run by the application. Also the problem is consistent. Every time the program runs the behavior occurs.
Answer: The database will be caching 2 things when the SQL is executed:

execution plan
data

The execution plan will remain in the cache for subsequent calls for that same query until it "expires".
However, it's the data cache that generally makes the biggest difference in performance as the data is kept in memory so subsequent calls don't need to access the disk to get it.
Comment: This is a very small amount of data and even when the data changes the time for the call does not suddenly increase. Is my problem on the sql server side then?
Comment: I would think so, this is where the query is actually executed. I'd get SQL Profiler running, monitor the calls going in. The query could be inefficient - I'd be checking what SQL is actually being executed, check the execution plan. If it's really inefficient/indexes lacking etc, then that could be why the first run is noticeably slower with even a small amount of returned data.
Comment: I was under the impression that the reason these calls took so long was due to the time taken to convert linq into sql not the execution of the sql itself.
Comment: I don't actually know how much of a hit there is when converting linq to sql. Looking at CompiledQuery class, it states that compilation does only happen when the query is first executed, as you thought: http://msdn.microsoft.com/en-us/library/system.data.linq.compiledquery.aspx
Answer: jalf pointed out in the comments that this has nothing to do with SQL and everything to do with the fact that compiled queries are compiled at runtime not during compile time.
http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx
Answer: The server need to be the query plan on the first execuation, it then uses the cached plan for subsequent executions.
Answer: Sql Cashes data the first time wich will improve the other runs. . . You could make script that runs though the calls so that they will be cashed. You could ad this to the installation process. . . . That may work.
You could make a table that updates the information needed into it. That way when you need the information its readly available.  (if there are alot of processing on bringing the data together)


Understanding and transcribing rubato and rhythm in Tango

Question: I want to learn to play tango piano better and so I'm working on transcribing this version of Malena by Lucio Demare. Most often I see this song notated in 2/4 but I'm having trouble notating the rhythm for his playing. If I'm hearing it right, the first 20 seconds in particular seem to be in a rubato that stretches and contracts time greatly adding extra subdivisions to the beat. Is there any specific logic to this rubato approach to help me interpret the playing? I come from jazz and most often when you stretch time you come back where you were. (I'm thinking like Ahmad Jamal at the Pershing.)
I assume this version of Demare's is more of a performance version and not meant for dancing and so he is just taking more liberties with time?
Answer: It's lovely. Very expressive. It's like a sort of meditation on the tune. No - you couldn't dance to it !
I'm not sure why printed versions might render it in 2/4. 4/4 or 'cut common' seem more appropriate to me. (When I refer to bar-numbers below I'm thinking in 4 to a bar.)
In those first bars he is just reminding himself of the tune; feeling his way into it. I think this is an ancient practice, similar to (though certainly not influenced by) the alap of North Indian classical music: 'unmetered, improvised and unaccompanied'. In Europe no doubt similar mental processes led to the development of the toccata: the need of the lutenist to check his tuning and try and remember the tune someone's requested! It's certainly unmetered, and those bars are sort of unaccompanied: it's two-part writing really, with no chords in the right hand and only broken chords in the left.
Yes - those first few bars would be hard to notate in in any time signature. In Sibelius you would need to use considerable jiggery-pokery. It would be easier to notate them by hand because you could indicate how rapidly the notes were to be played graphically by putting as many of them as you liked into each bar and bunching them up closely or less closely. This is called space time notation, normal note values being replaced by the horizontal spacing of note heads on the staff. (Cage and Lutosławski do this sometimes. Sibelius doesn't!)
You're right about rubato. There are two types: your jazz type, where the stolen time gets repaid, and the type where everyone slows down or speeds up together and there is no catching up. Malena is the second type.
But no, there's no logic to his use of rubato. We could say he's interested in the expressive potential of the piece and that where the notes of the melody are poignant, or where the harmony is richer (the Fm6 for example), he finds more scope for invention. Where he can't see much potential he moves on quickly. In bar 8 [ignoring the intro bar] where a - somewhat ordinary - Cm is expected, he adds a b9 to the C7 and brings it forward to the beginning of the bar, keeping up the emotional energy. Repose is only allowed where it will provide contrast. And he's interested in the contrast between the major-key stuff (which is like a flashback to happier times) and the minor key of the main tune.
Those seem to be the 'rules'. There are really only suggestions of tango, aren't there? Rather fleeting ones. You've probably noticed there are bars of 3/4 in there occasionally. They're not rubato: they're 3/4!
If I were writing it out in order to learn it I wouldn't worry too much what it looked like, and it'd be full of instructions like 'Move on' and 'Hold back', á la Copland. And I'd include a reminder to use hardly any pedal: his use of it is amazingly subtle, isn't it?
Good luck. And thanks - I'm glad to have got to know that piece.
Comment: Thanks. Good to have a second ear to know I'm not going crazy. I'll probably just write it as makes sense so I can refer back to it and not try to fit it into something rigid.
Comment: You're welcome. Yes - I think that's what I'd do.
Answer: From me,  an old opera player: putting forward going arrows above the notes(= faster) or backward going arrows above the notes( = slowing down) or a sign wave kind of thing over the notes (which to me means a kind of blah blah blah: something is going on here, watch out). I wish someone could tell me where the rubatos in tangos tend to happen (like the info to play the off beats in a Strauss waltz with the 2nd beat slightly anticipated and the 3rd beat slightly delayed.) Ah well ....above the notes


Interupt a javascript redirect with a delay

Question: Im currently using a simple javascript redirect (called on load) with a delay to automatically redirect users from older articles to newer ones in a corporate wiki. However, Id like users to be able to stop the autoredirect so they can access the older data if needed.
How could I modify this code to achieve that?

Comment: Please, please, please change `"iiredirect()"` to `iiredirect`.
Comment: @PeterOlson: Why? Either seems to work: http://jsfiddle.net/simtali/P2ehw/
Comment: @Daniel They both will work, but passing a string parameter to `setTimeout` or `setInterval` does an eval of the code in the string, which is unnecessary when you can pass a function in directly.
Comment: Ah, I missed the string vs function bit and thought you were referring to function reference vs call.
Comment: @Daniel Passing a function call will immediately call the function. It passes whatever the function returns to `setTimeout`. If you used `setInterval` and passed a function call, you would notice that the function only runs once, and if you increased the delay in `setTimeout` passing in a function call you would notice that there is no delay.
Comment: Ah, that explains why my example seems to work properly (but doesn't).
Answer: clearTimeout(h) should do it. That will cancel the running timeout.
Answer: Assuming button is a reference to your cancel redirection button.
var timeout = setTimeout(function() {
    window.location = "that new location";
}, 2000);

button.addEventListener('click', function() {
    clearTimeout(timeout);
}, false);


Defining a function for velocity in terms of external variables?

Question: I want to make a machine move a distance, d, in a time period of, t. But its acceleration, a, and therefore its velocity, v, must change depending on an external variable, N.
I want the machine to slow down as N increases and to speed up as N decreases. This must imply that $a \propto - \Delta N$ and $v \propto 1/N$
Is it possible to create a function demonstrating how the velocity changes in this pre-set time period, t ? How would v be defined?
I am intending to write this for some code, but I would like to make the maths clearer for myself first.
Answer: The question as posed is unanswerable because it is both vague and self-contradictory. That would be the topic of a comment, but it's difficult to explain in the format of a comment just how vague and self-contradictory the question is, so here is an extended comment in a space that normally would be occupied by an answer.
The statement that $v \propto 1/N$ is a very specific statement about a particular relationship between $v$ and $N$, much more specific than the statement that $v$ increases as $N$ decreases and vice versa.
Literally, $v \propto 1/N$ says there is some constant $k$ such that
$$ v = \frac kN. $$
That implies that
$$
 a = \frac{\mathrm d}{\mathrm dt} v = \frac{\mathrm d}{\mathrm dt} \frac kN
  = -\frac1{N^2} \frac{\mathrm dN}{\mathrm dt},
$$
which doesn't look like $a \propto - \Delta N$ under any reasonable interpretation I can think of.
You might want to reconsider what you mean here:

I want the machine to slow down as N increases and to speed up as N decreases. This must imply that $a \propto - \Delta N$ and $v \propto 1/N$

There's no "must" about it; the first sentence does not imply either of the second two formulas at all (you could have something quite different) and the two formulas are mutually contradictory.
If you literally want the first sentence to be true, then $v$ is a function of $N$,
but it could be any decreasing function; if there is some reason that the choice of functions should be more limited than that, you'll have to articulate an idea of what that reason would be.
Alternatively, instead of defining $v$ directly as a function of $N,$ you could first define $a$ mathematically.
Slowing down as $N$ increases means $a$ is negative when $N$ is increasing;
speeding up as $N$ decreases means $a$ is positive when $N$ is decreasing.
That is, the sign of $a$ is opposite to the sign of $\frac{\mathrm dN}{\mathrm dt}.$
There are a lot of ways to define $a$ as a function of
$\frac{\mathrm dN}{\mathrm dt}$ that satisfy this requirement, for example,
$$
a = \begin{cases}
-1 & \text{if $\frac{\mathrm dN}{\mathrm dt} > 0$}, \\
\phantom{-}0 & \text{if $\frac{\mathrm dN}{\mathrm dt} = 0$}, \\
\phantom{-}1 & \text{if $\frac{\mathrm dN}{\mathrm dt} < 0$}, \\
\end{cases}
$$
but that's only one of a great many possible choices.
Note that with this particular choice, there are a lot of different ways to vary $N$ over a period of time $t = 0$ to $t = T$ and still come up with the same value of $v$ at time $T,$ and you can't determine $v$ at time $T$ just by looking at $N$ at time $T.$
On top of all this, if the machine must travel a particular distance in a particular interval of time, that's a constraint on $v$ that will be very hard to meet,
especially if $v$ is subject to the influence of some "external" variable $N$ that could vary unpredictably.
You need to seriously think about what you mean by
"move a distance, $d$, in a time period of, $t$"
and what you mean by
"depending on an external variable, $N$."
Why do you need both of these things?
These two things do not seem compatible within the framework of your question.
Comment: The comment above gives new information that is helpful. If the values of $N$ occur at fixed places along the path, we can consider the inverse of speed, time per unit distance traveled, which should be some kind of increasing function of $N$. Making this a continuous function might be a little more difficult. Also, it's going to be hard to determine the right speed in the early part of the path if you have no idea what values of $N$ you're going to encounter later. Do you know the $N$ values in advance? Values sampled at uniform distances with a known sum might work.
Comment: Thank you so much for your answer, I can see how my question is flawed.
I want to use this programme to make a machine move a permanent distance, taking the same time to cover that distance.
The machine will analyse a sample as it moves.  I want it to slow down at the points where $N$ is high and to pace up at points where N is low.
This implies that at higher N, v is lower, and vice-versa.
I thought that the acceleration between points a and b must also be slower if the change in N from point a to b is negative.
I was looking for an equation that would relate v or a to N and to t.
Comment: Thanks once again for the help. Indeed I have pre-determined the values $N$ at each time point. The data results in a slightly-deformed Gaussian-like distribution data set.
I still don't quite see how I can relate the quantities though......


Disabling reply link for comments not working

Question: I would like to disable reply to comment for anonymous user.
I saw on sereval topics that you have to unset

$variables['content']['links']['comment']['#links']['comment-reply']

So I ended up adding a preprocess to the .theme file (bartik.theme since I'm using Bartik. Btw I'm using Drupal 8.5.3)
function bartik_preprocess_comment(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

Despite that preprocess, I still have the reply link when I'm anonymous. Does anyone has an idea about what's going on ?
Answer: You can use hook_comment_links_alter() rather than THEME_preprocess_comment() .Where as hook_comment_links_alter() will render all the comments links before build:
function YOURMODULE_comment_links_alter(array &$links, Drupal\comment\CommentInterface $entity, array &$context) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($links['comment']['#links']['comment-reply']);
  }
}

Comment: Any clue about why the solution I used was not working ?
Comment: I suggest using #access = false instead of unsett `$links['comment']['#links']['comment-reply']['#access'] = FALSE;`instead of unset. Also you might want to implement some sort of access preventing Anon users from replying .. either access hook or form submit validation hook/event
Comment: @Tibo In your solution, it's only getting all the comment content with already rendered links. So in that hook links array will not be present and links will come as rendered under comment.


Scalable design for vsphere 4.1

Question: We have procured
1x C7000 Chasis
2xVirtual connect
2x9124 FC switch
5xBL460 G6 with Dual port HBA
1 NetApp Filer(FC) with Dual controller Active/Active
1xNetApp filer(SATA) with Single controller
We need to deploy scalable design with Vsphere 4.1
We will be using 3 blade for VMWARE Vsphere4.1 and 2 blade as Physical for other application
There will be 6 VMs including Vcenter
How should be the Virtual Connect connection to cater both Physical and Virtual environment within the same chasis
Answer: You've missed out a lot of information (specifically about your downstream LAN ports or any intermediary SAN switches) but let's break it down into chunks.
The easy one is the SAN, simply run however many ports you like from your 9124s into your NetApp, I'd be tempted to run them as point-to-point links if you have no intermediary switches and use NPIV rather than run them as ISL trunks (not sure if the NetApp can deal with ISL anyway). So you'll create two SAN networks, one per host port and just map them stright through - no need for VSANs/Zones etc.
The LAN question is a little trickier, and can't cover your physical servers as you've provided no network requirements - assuming your downstream ports are switches that can handle trunks then what I'd do for your ESX boxes is split each flexNIC into two vNICs, one at 2Gbps and the other at 8Gbsps, do this for both adapters giving your hosts 4 vNICs each, create a management/vMotion vswitch using both 2Gb vNICs and a VM traffic vSwitch with the both 8Gb vNICs. Create two VC networks, one for the two management/vmotion vNICs and one for the VM traffic vNICs, drop your real trunk ports into their port groups and you're away.
For both LAN and SAN use the hardware MACs/WWNs, no point using the pooled ones in this situation. Oh and let your VC do the VLAN tagging (unless you plan on separate trunks for both functions in which case just let the tags go through to ESX to break out).
This'll be fine for the ESX and probably good enough from the SAN perspectice for you physicals but as I said you've given us nothing to work on for the physical LAN ports.
Answer: This is a pretty awful line of questioning. Let's get started.

What do you even mean by "scalable?" There's all kinds of scalability. You need to clarify exactly what you're trying to scale, and what imposes scalability bottlenecks on your application.
There's no such thing as a one-size-fits-all scalable design. There is literally nothing we can tell you about making your applications scale if we have no idea what you're trying to do with the cluster. Even within the same application, different use cases have vastly different performance requirements. We can't guess what you need to stay scalable. You have to tell us. If you're not sure what numbers you're looking for, VMware Capacity Planner should help you. Install it on your physical servers, let it cook a week, and then come back to us.
What are you even accomplishing by running five virtual machines (excluding vCenter) on three physical systems? There's countless DR benefits to virtualization, but if you don't have a broader consolidation project it sounds like you could save a ton of money by just doing boot-from-SAN on all of your physical hosts.
You definitely don't want to run your cluster VMs within the same blade chassis, especially if you're relying on HA to keep things available in the event of a host failure -- your chassis introduces a single point of failure on your entire environment. If you only have one blade chassis, don't use blades for this. Buy 1U or 2U pizzaboxes. You'll be much happier.
I've never seen a SAN that couldn't keep up with VMware. I have, however, seen plenty of arrays within the SAN that can't, because the administrators didn't properly understand the I/O profiles of their application or how that affects the design of a physical disk array.

If you're in over your head, and you sound like you are because you don't know the questions you should be asking, you should really bring in a consultant or at least a VAR to help get you up and running. Virtualization without the expertise to configure or manage it will be a complete disaster for your organization.

Scalable design for vsphere 4.1


How to exercise my fingers in extreme bending when playing piano?

Question: I am learning a song on piano which has the following notes played simultaneously with the right hand: C Eb G C (my fingering: 1 2 3 5)
If it was E instead of Eb I could pull it off without a problem, but the way it is now I am unable to play either of C or Eb. When I take it very, very slowly and bend my wrist I can do it. I figure out it's a matter of my fingers being untrained in handling this - I tried to change the fingering and it wasn't better.
What exercises can I do to make it easier/possible for me to play chords like this?
Comment: I bet anything that D# is really an Eb...
Comment: For a beginner, i'd do that 1 2 3 5, not 1 2 4 5. 1 2 & 3 are more flexible than 4 or 5 when you're just learning. That should allow your 2 to more easily play any of D, D# or E.
Comment: @Tetsujin Bah. I had to walk to the piano to check and I was actually going 1 2 3 5, I just didn't have the keyboard handy when writing the post and remembered it wrong.
Comment: @Tim Yep, it is. I used D# because I didn't know how to express the Eb without special characters, heh.
Comment: aparente001 brings up a good question in the comments: how big are your hands, Maurycy? How much can they comfortably span? For example, I can barely hit a ninth if both notes are on white keys, but then I also hit adjacent notes. I can comfortably hit octaves in both hands, but I have trouble playing five notes with each hand while spanning an octave each. I think that's due to my small hand size.
Answer: The most likely problem is your hand position. A one-octave C-major chord should not require twisting or bending the wrist. (This answer deals with twisting, but the same solutios/ideas apply to a bend wrist, which should be kept neutral -- the way it would be if your arm was hanging relaxed at your side.)
Fingers over-curled
It's possible that you are playing too much on the tips of your fingers. This will force a wider stretch between fingers 2 and 3. (See Photo #1 and #2, below)
Flatten out your hand so you can take advantage of the length of finger 2 to help read the Eb.
Hand too close to the edge of the keys
When playing white-keys only, it's good to play close to the edge of the keys, because it afford better leverage/control. However, when playing black keys, the best strategy is to shift the hand toward the back of the keyboard (away from the body) to bring the fingers closer to the black keys. (See photo #2, below)
Don't twist
Twisting the hand should be avoided to the greatest degree possible. It leads to inefficient movement and is a common cause of injury to pianists. Leaving aside the rare exceptional case, use in/out movement, not twisting.
Correct hand position
See photo #3 below. Keep the hand more flat, shift toward the back of the keys, and keep your write neutral.

Illustrations
Photo #1: over-curled fingers create difficulty reaching black keys.

Photo #2: over-curling also increases the angle (stretch) between fingers.

Photo #3: flatter hand in forward position allows for no twist and least stretch between fingers.
Answer: so your thumb and pinky can't reach an octave?
might just be that you'll have to roll chords like that if your hand span just ain't too wide.
hit the first 3 with the hold pedal down and get to the top c as quick as you can.
Comment: They can reach the octave, I can easily pull An octave +1 note if it's just thumb and pinky. Because of the index finger being too much to the left though my fingers: a) have almost no strength so when I push down onto the keys they move b) I have hard time not accidentally pressing the neighboring keys with my thumb and pinky. I can almost make it, I just feel like I need to build up strength and agility in the fingers.
Comment: @Maurycy, I tried your chord.  I have to stretch and put my hand in some uncomfortable tension to play it.  Unfortunately a lot of piano music is written for people with big hands.
Answer: I'd recommend starting to practice the chords as arpeggios.
Here are some exercises that can help getting familiar with chord fingerings using an octave.

As long as you practice these with only white keys I recommend playing those exercises in different modes by moving up or down one step.
As soon as you start getting pretty fluent change the E to E♭ as asked in your question. I'm pretty sure that once you are practicing this you will come up with other variations. Just make sure that if you start swapping hands and practice the arpeggios with the left hand I'd recommend a fingering 5-4-3-1 as suggested in the left hand of Nr.4.


Can a rest count as a musical accent?

Question: I remember reading somewhere (I don't know where) that a rest counts as a musical accent. Is this true?
If so, then for example, when can I rest in 4/4 for an instrumental piece?
Comment: Well, depending on what meaning we give the words, a rest _is_ a definite thing, and by absence of sound there can be some emphasis (if the rest of the music is not toooo busy/noisy).
Comment: Welcome! This question is a bit confusing, and needs editing to be answerable. When you say "rest," do you mean [this idea](https://en.wikipedia.org/wiki/Rest_(music))? and by "accent," do you mean [this](https://en.wikipedia.org/wiki/Accent_(music))? For your second question: if you're reading notated music, rests are usually notated just like pitches. If you're creating your own, you can choose to include rests of any length at any time. Perhaps you're thinking about the idea of "metric accents," or "strong and weak beats"? Please use the "edit" button to tell us more.
Comment: FWIW, rests - including impromptu, unnotated, and ones that quite possibly shouldn't even be there - can create **agogic accents** on notes played immediately after them.
Comment: Can a rest create an agogic accent by having a long duration?
Answer: Second half of your question first.  "...when can I rest on a 4/4 instrumental...?"
Anywhere you like.  As witness any piece of notated music, where the solo part WILL contain rests.
Now we try to discover what "...a rest counts as a musical accent" means.   Maybe just that you keep counting, whether there are notes or rests.
Or maybe it's a bit more philosophical.   If there's a strong beat underlying the music, it can said to be be felt even when a note isn't actually played ON that beat.  "The silence was deafening."
When singers tend to run into the rests, I sometimes say 'Sing the rests louder!'
Comment: "it can said to be felt" — crucial musical idea. Kids, pay attention to this one.
Comment: Can a rest create an agogic accent by having a long duration?
Answer: An accent on a note makes that note played with more emphasis than the surrounding ones. So, from an actual situation, it would be impossible to make a rest sound more emphasised (louder) by writing it with an accent (>).
However, in the majority of music, we feel beat one as the usually more emphasised part of most bars - without that, it's pretty difficult to say what the time signature would be. So - if that particular part of a bar was missing sound - it was a rest - the listener would likely expect something there, thus making it a small period of time within that bar that was 'emphasised'. Rests are after all part of music, which will rarely be sound after sound after sound. Deafening silence?
That said, there is no deafinite place where rests (of any duration)  are supposed to be; they fit where they go, due to the whim or choice of the composer. But, they will always be part of the music (or lack of it), adding to the final effect.
Comment: There's a great video on YouTube of Jojo Mayer as a keynote speaker at an architecture college, where he uses a great analogy for his audience: just like a building that is just a solid block of concrete is not very interesting (you need both the concrete walls, stairs, etc. and the "missing concrete" rooms, windows, doors, hallways), music also needs both the notes and the space between the notes.
Comment: Can a rest create an agogic accent by having a long duration?
Answer: Rests count as silent units of time and rhythm in music depending on their duration just like their note counterparts (i.e. half note/half note rest) but they are not accents. They also don't have accents placed on them like notes can. After all, how can someone accent silence?
As far as where to rest on a 4/4 instrumental, the placement of rests are choices just like the placement of notes. There is no formula to say where they go, they can be placed anywhere one chooses. They are used in a way like commas, periods and paragraphs are used in language. The person who writes or improvises the music decides where they go.
Comment: Written punctuation maybe isn't the best analogy.   In speech, a comma DOES imply a hiatus in the time-line, a paragraph implies an even more definite one.   Musical equivalents would be a comma or a caesura.   We could extend  the analogy to a chapter end being like the break between two movements of a sonata.    I can't think of a direct analogy for musical rests, but that's OK.  If music could be described fully in words, we wouldn't need music!
Comment: When rests occur inside a phrase (so not multi bar rest, or widely spaced rest for breath, etc.) - something like a rest per 1 or 2 bars inside a phrase - it reminds me of _short sentences._ On the other hand, lines like _fortspinnung_, seem like long sentences of phrases strung together with commas.

Can a rest count as a musical accent?


Integrated DMCA badges are not show up on all pages

Question: I have integrated DMCA badge through the Wordpress plugin, but the badge is not showing for all pages.
Any solutions on how to fix it?
costoffliving.com
Answer: Sorry to hear you're having troubles with the plugin.

Can I ask which version of wordpress you're using?
Can you tell me which page you're having trouble with?

The DMCA.com Wordpress Badge plugin (https://www.dmca.com/WordPress/) works with the wordpress templating system.

You can choose which templates the badges show up on by clicking on
the "Settings" page
You can also always just copy and past the badge / embed code into an
html widget and drag and drop that wherever you want.

Screenshot of the dmca.com wordpress plugin settings:

Thanks
DMCA.com Support


Objects in anonymous functions

Question: Take a look at the 2 lines below.
foo = ({ data: { one, two }}) => {alert(one.type); alert(two.type);}
foo( /* What goes here*/ );

What would I put in the () on the second line to alert "Hello" in the first alert() and "World" in the second alert()?
Comment: foo({data: {one: {type: "Hello"}, two: {type: "World"}}})
Answer: You need to call the foo function with an object that has data key. Data also is an object with two keys one and two
foo({
    data: {
       one: {type: 'one'},
       two: {type: 'two'}
    }

})

What you need to understand is that the foo component is using object destructing

Objects in anonymous functions


haproxy and certificates mismatch

Question: I have been wrestling with Haproxy for a few hours now and I am probably missing something in my limited know-how.
I have two servers (ha1.domain.com and ha2.domain.com), both with keepalived and haproxy, that should manage failover between two other servers (mail1.domain.com and mail2.domain.com). There is one VIP (domain mailserver.domain.com).
When I connect to the public domain via browser I get an error that the certificate could not be verified as the domain (mailserver.domain.com) doesn't match the domain in the certificate (either mail1.domain.com or mail2.domain.com). What is the best strategy to avoid this issue?
My haproxy config:
global
    log 127.0.0.1   local0
    log 127.0.0.1   local1 debug
    maxconn   45000 # Total Max Connections.
    daemon
    nbproc      1 # Number of processing cores.

defaults
    timeout server 86400000
    timeout connect 86400000
    timeout client 86400000
    timeout queue   1000s

# [HTTP Site Configuration]
listen  http_web xxx.yyy.zzz.aaa:80
    bind *:80
    #bind *:443 ssl crt /etc/ssl/iredmail.org/iredmail.org.pem
    bind *:443 ssl crt /etc/haproxy/certs/ha2.domain.com.pem
    redirect scheme https if !{ ssl_fc }
    mode http
    balance roundrobin  # Load Balancing algorithm
    option httpchk
    option forwardfor
    cookie SRVNAME insert
    server mail1 bbb.ccc.ddd.eee:80 weight 1 maxconn 512 cookie SA check
    server mail2 bbb.ccc.fff.ggg:80 weight 1 maxconn 512 cookie SB check

# [HTTPS Site Configuration]
listen  https_web xxx.yyy.zzz.aaa:443
    mode tcp
    balance source# Load Balancing algorithm
    reqadd X-Forwarded-Proto:\ http
    server mail1 bbb.ccc.ddd.eee:443 weight 1 maxconn 512 check
    server mail2 bbb.ccc.fff.ggg:443 weight 1 maxconn 512 check

# Reporting
listen stats
bind :9000
mode http

# Enable statistics
stats enable

# Hide HAPRoxy version, a necessity for any public-facing site
stats hide-version

# Show text in authentication popup
stats realm Authorization

# URI of the stats page: localhost:9000/haproxy_stats
stats uri /haproxy_stats

# Set a username and password
stats auth Username:Password

Thanks
Comment: `listen  a   b`   is bad syntax on typical versions of haproxy. What version do you use?
Answer: As you don't intend to access the servers with the names mail1.domain.com or mail2.domain.com, the easiest is to get for both servers a certificate with the name mailserver.domain.com.
If you want to keep the servers accessible by their own names, get a certificate that has both names, the individual mail1.domain.com or mail2.domain.com, and the common mailserver.domain.com.

haproxy and certificates mismatch


How to correctly turn an imported SQL query into an expression string in SSRS

Question: Sorry to bother everyone with what should be a trivial question, but I need to import an SQL query into SSRS's Report builder, and then turn it into an expression (so that I can use its concatenation operator to join values of a parameter into search strings).
As a first stage, I copied and pasted my query (which I know works) into SSRS, and it ran smoothly.  However, as soon as I put the expression in quotes, and prefixed the whole thing with "=", I get some very unhelpful syntax error messages.
This is my (correctly functioning) query before importing into SSRS:
DECLARE @From Date='1/1/2015'
DECLARE @To Date='1/3/2020'
DECLARE @Doctors varchar(5)='ABC'
DECLARE @Intents varchar(20)='RoutineRad-Cat2'
DECLARE @DiagnosisTypes varchar(20)='ICD-10'

SET transaction isolation level read uncommitted;

SELECT
    x.Expression1 as 'Intent',
    x.IntentCategory,
    x.StartDateTime as 'Ready To Start Treatment Date',
    x.LastName as 'Surname',
    x.PatientId as 'Patient ID',
    x.DoctorId as 'Primary Oncologist',
    x.TreatmentStartTime as 'First RT Treatment Date',
    datediff(dd, x.StartDateTime, x.TreatmentStartTime) as 'Wait in days',
    x.TargetMet,
    x.Delayed,
    x.TxStartSortDate

FROM (VALUES('C50%'),('D05%'),('C61%'))

AS v (pattern)
  CROSS APPLY
  (
    SELECT
            lut.Expression1,
            p.PatientId,
            p.LastName,
            c.StartDateTime,
            d.DoctorId,
            rh.TreatmentStartTime,
            CASE
                WHEN Expression1 like '%Rad%' THEN 'Radical'
                WHEN Expression1 like '%Pall%' THEN 'Palliative'
                WHEN Expression1 = 'Emergency' THEN 'Emergency'
            ELSE 'Other'
            END
            as 'IntentCategory',

            CASE WHEN Expression1 like '%Delay%' THEN 1 ELSE 0 END as 'Delayed',
            CASE WHEN
            (
                (Expression1 like '%Rad%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 28)
                OR (Expression1 like '%Palliative%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 14)
                OR (Expression1 = 'Emergency' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 1)
                --catch any exceptions
                OR ((Expression1 not like '%Rad%') AND (Expression1 not like '%Palliative%') AND (Expression1!='Emergency'))
            ) THEN 1 ELSE 0 END as 'TargetMet',
            FORMAT(rh.TreatmentStartTime,'yyyyMM') as 'TxStartSortDate',
            FirstRadiationHstry.TreatmentStartTime as 'MinTreatStart',
            datediff(dd, c.StartDateTime, rh.TreatmentStartTime) as 'TreatDelay'

            FROM
            dbo.Patient p
            inner join Course c on (c.PatientSer = p.PatientSer)
            inner join CourseDiagnosis cd on (cd.CourseSer=c.CourseSer)
            inner join Diagnosis diag on (diag.DiagnosisSer=cd.DiagnosisSer)
            inner join PatientDoctor pd on (pd.PatientSer = p.PatientSer)
            inner join Doctor d on (d.ResourceSer = pd.ResourceSer)
            inner join dbo.PhysicianIntent phi on (phi.CourseSer = c.CourseSer)
            inner join dbo.LookupTable lut on (lut.LookupValue = phi.TreatmentIntentType and lut.ListSelector = 'COURSE_INTENT')
            inner join dbo.PlanSetup ps on (ps.CourseSer = c.CourseSer)
            inner join dbo.Radiation r on (r.PlanSetupSer = ps.PlanSetupSer)
            inner join dbo.RadiationHstry rh on (rh.RadiationSer = r.RadiationSer)
            inner join (
                            select distinct
                            min(rh_sub.TreatmentStartTime) over (partition by ps_sub.CourseSer) as 'TreatmentStartTime',
                            ps_sub.CourseSer
                            from
                            RadiationHstry rh_sub
                            inner join dbo.Radiation r_sub on (r_sub.RadiationSer = rh_sub.RadiationSer)
                            inner join dbo.PlanSetup ps_sub on (r_sub.PlanSetupSer = ps_sub.PlanSetupSer)
                            where
                            rh_sub.TreatmentDeliveryType like 'TREATMENT'
                        ) as FirstRadiationHstry on (FirstRadiationHstry.CourseSer = c.CourseSer)

    WHERE
            datediff(dd, @From, rh.TreatmentStartTime) >= 0
            and datediff(dd, rh.TreatmentStartTime, @To)>=0
            and diag.DiagnosisCode like v.pattern
            and d.OncologistFlag=1
            and d.DoctorId in (@Doctors)
            and rh.TreatmentStartTime = FirstRadiationHstry.TreatmentStartTime
            and lut.Expression1 in (@Intents)
            and diag.DiagnosisTableName in(@DiagnosisTypes)
            and lut.Expression1 not like 'Dummy Course'
  ) AS x
;

...and this is it after:
="SET transaction isolation level read uncommitted;

SELECT
    x.Expression1 as 'Intent',
    x.IntentCategory,
    x.StartDateTime as 'Ready To Start Treatment Date',
    x.LastName as 'Surname',
    x.PatientId as 'Patient ID',
    x.DoctorId as 'Primary Oncologist',
    x.TreatmentStartTime as 'First RT Treatment Date',
    datediff(dd, x.StartDateTime, x.TreatmentStartTime) as 'Wait in days',
    x.TargetMet,
    x.Delayed,
    x.TxStartSortDate

FROM (VALUES('C50%'),('D05%'),('C61%'))

AS v (pattern)
  CROSS APPLY
  (
    SELECT
            lut.Expression1,
            p.PatientId,
            p.LastName,
            c.StartDateTime,
            d.DoctorId,
            rh.TreatmentStartTime,
            CASE
                WHEN Expression1 like '%Rad%' THEN 'Radical'
                WHEN Expression1 like '%Pall%' THEN 'Palliative'
                WHEN Expression1 = 'Emergency' THEN 'Emergency'
            ELSE 'Other'
            END
            as 'IntentCategory',

            CASE WHEN Expression1 like '%Delay%' THEN 1 ELSE 0 END as 'Delayed',
            CASE WHEN
            (
                (Expression1 like '%Rad%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 28)
                OR (Expression1 like '%Palliative%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 14)
                OR (Expression1 = 'Emergency' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 1)
                --catch any exceptions
                OR ((Expression1 not like '%Rad%') AND (Expression1 not like '%Palliative%') AND (Expression1!='Emergency'))
            ) THEN 1 ELSE 0 END as 'TargetMet',
            FORMAT(rh.TreatmentStartTime,'yyyyMM') as 'TxStartSortDate',
            FirstRadiationHstry.TreatmentStartTime as 'MinTreatStart',
            datediff(dd, c.StartDateTime, rh.TreatmentStartTime) as 'TreatDelay'

            FROM
            dbo.Patient p
            inner join Course c on (c.PatientSer = p.PatientSer)
            inner join CourseDiagnosis cd on (cd.CourseSer=c.CourseSer)
            inner join Diagnosis diag on (diag.DiagnosisSer=cd.DiagnosisSer)
            inner join PatientDoctor pd on (pd.PatientSer = p.PatientSer)
            inner join Doctor d on (d.ResourceSer = pd.ResourceSer)
            inner join dbo.PhysicianIntent phi on (phi.CourseSer = c.CourseSer)
            inner join dbo.LookupTable lut on (lut.LookupValue = phi.TreatmentIntentType and lut.ListSelector = 'COURSE_INTENT')
            inner join dbo.PlanSetup ps on (ps.CourseSer = c.CourseSer)
            inner join dbo.Radiation r on (r.PlanSetupSer = ps.PlanSetupSer)
            inner join dbo.RadiationHstry rh on (rh.RadiationSer = r.RadiationSer)
            inner join (
                            select distinct
                            min(rh_sub.TreatmentStartTime) over (partition by ps_sub.CourseSer) as 'TreatmentStartTime',
                            ps_sub.CourseSer
                            from
                            RadiationHstry rh_sub
                            inner join dbo.Radiation r_sub on (r_sub.RadiationSer = rh_sub.RadiationSer)
                            inner join dbo.PlanSetup ps_sub on (r_sub.PlanSetupSer = ps_sub.PlanSetupSer)
                            where
                            rh_sub.TreatmentDeliveryType like 'TREATMENT'
                        ) as FirstRadiationHstry on (FirstRadiationHstry.CourseSer = c.CourseSer)

    WHERE
            datediff(dd, @From, rh.TreatmentStartTime) >= 0
            and datediff(dd, rh.TreatmentStartTime, @To)>=0
            and diag.DiagnosisCode like v.pattern
            and d.OncologistFlag=1
            and d.DoctorId in (@Doctors)
            and rh.TreatmentStartTime = FirstRadiationHstry.TreatmentStartTime
            and lut.Expression1 in (@Intents)
            and diag.DiagnosisTableName in(@DiagnosisTypes)
            and lut.Expression1 not like 'Dummy Course'
  ) AS x
;"

...but I just get the error message "Incorrect syntax near the keyword 'VALUES'.
Incorrect syntax near ')'."
I have no idea how to go about trying to iron this out, as I know my SQL is fine.  I've tried importing the query into Scite and looked at the line endings / special characters, but this looks OK as well.
Can someone please help me?
Best wishes
C J
Comment: Considering you're using a completely unsupported version of SQL Server, you aren't, perhaps, using 2005 compatibility are you?
Answer: It seems that you will need to wrap EACH LINE with quotes and link with & to make this work. I haven't been able to figure out why. I also use a Line Feed to break the lines up in the resulting query.
="SET transaction isolation level read uncommitted; " & VBCRLF
" " & VBCRLF
"SELECT " & VBCRLF
"    x.Expression1 as 'Intent', " & VBCRLF
"    x.IntentCategory, " & VBCRLF
…

In Notepad++ you can Find \r\n and replace with " & VBCRLF & \n" to add them automagically - though you'll need to do the first and last ones.
Source: Couldn't find any - trial and error.
Comment: Thanks!  This works nicely, but you definitely shouldn't have to use this sort of hack just to get a query to work.  But thanks for your effort, and giving me the solution!


Whether or not $X_1$,...,$X_n$ are independent and exchangeable

Question: For some n = 1,2,..., let $Y_1$,...,$Y_{n+1}$ denote iid real-valued random variables.
Define $X_j$ = $Y_j$$Y_{j+1}$, $\hspace{10mm}$j=1,...,n
a) Are $X_1$,$X_2$,...,$X_n$ independent?
b) Are $X_1$,$X_2$,...,$X_n$ exchangeable?
Attempts:
a) No.
Counterexample: Let Y be a Bernoulli (0,1) distribution, with p = 1/2, where $Y_1$ = 0 and $Y_2$ = 1.
Then $X_1$ = $Y_1$$Y_{2}$
Now $E(Y_1*Y_2)%$ = $E(0*1)$ = $E(0)$ = 1/2
However, $E(Y_1)%$$E(Y_2)%$ = 1/2*1/2 = 1/4
Since $E(Y_1*Y_2)%$ $\neq$ $E(Y_1)%$$E(Y_2)%$, the $X_i$'s are not independent.
b) Not sure.
Comment: Answers: a) Not in general (but this requires an explicit counterexample). b) Not in general (but this requires an explicit counterexample). Hint: Try Bernoulli {0,1}-valued random variables.
Comment: Your reasoning on a) is not valid; expressing $X_2$ in terms of $X_1$, $Y_1$, and $Y_3$ does not establish a dependence among $X_1$ and $X_2$ alone.
Comment: Ok. Is the resulting product of two IID variables also IID?
Comment: I don't actually know the solution; on gut intuition I suspect they're not exchangable in general, since the way the $Y_i$'s are linked together by the $X_i$'s is not symmetric up to permutation.
Answer: Your reasoning on a) is not valid yet the good idea is there. Let's keep your example with the $X_{i}$'s being independant Bernouilli variables with $p=0.5$.
Then, $\mathbb{E} X_{1}X_{2} = \mathbb{E} Y_{1}Y_{2}^{2} Y_{3} = \mathbb{E}Y_{1} \mathbb{E}Y_{2}^{2} \mathbb{E}Y_{3}$ because of the independance of the $Y_{i}$s.
Since $\mathbb{E}Y_{2}^{2} = p$, we have $\mathbb{E} X_{1}X_{2} = p^{3}$.
On the other side, it is easy to see that $\mathbb{E}X_{i} = p^{2}$.
If $X_{1}$ and $X_{2}$ were independant, we should have $ p^{3} = \mathbb{E} X_{1}X_{2} = \mathbb{E} X_{1} \mathbb{E}X_{2} = p^{4}$, which is not true.
What do you mean by "exchangeable variables ?" Here is my definition : $X_{1}, ... , X_{n}$ are exchangeable if, for every measurable function $f : \mathbb{R}^{n} \to \mathbb{R}_{+}$, and for every permutation $\sigma \in \mathfrak{S}_{n}$, we have :
$$\mathbb{E}f(X_{\sigma(1)}, ..., X_{\sigma(n)}) = \mathbb{E}f(X_{1}, ..., X_{n}).$$
Let's try with $n=2$. We have $f(X_{1}, X_{2}) = f(Y_{1}Y_{2}, Y_{2}Y_{3}) = f \circ g (Y_{1}, Y_{2}, Y_{3})$, where we defined $g : \mathbb{R}^{3} \to \mathbb{R}^{2}$ by :
$$g : (x,y,z) \to (xy,yz) $$
Then, $f \circ g$ is measurable and since $(Y_{1}, Y_{2}, Y_{3})$ is i.i.d., we have :
$$\mathbb{E}f f(X_{1}, X_{2}) = \mathbb{E}f \circ g (Y_{1}, Y_{2}, Y_{3}) = \mathbb{E}f \circ g (Y_{3}, Y_{2}, Y_{1}) = \mathbb{E}f (Y_{3}Y_{2}, Y_{2}Y_{1}) = \mathbb{E}f(X_{2}, X_{1})$$
Therefore,  $X_{1}$ and $X_{2}$ are exchangeable. I'm not sure the same result holds with $n > 2$, but you should try to adapt the proof (which might reveal tricky).
edit. Okay, here is a counterexample with $n=3$.
Let's have $f(x,y,z) = xz$, nd $\sigma = (2,3,1)$. We have :
$$\mathbb{E}f(X_{\sigma(1)}, X_{\sigma(2)}, X_{\sigma(3)}) = \mathbb{E}f(X_{2}, X_{3}, X_{1})  = \mathbb{E}Y_{2}Y_{3}Y_{1}Y_{2} = p^{3}$$
On the other side, we have :
$$\mathbb{E}f(X_{1}, X_{2}, X_{3}) = \mathbb{E}Y_{1}Y_{2}Y_{3}Y_{4} = p^{4}$$
In conclusion, $X_{1}, X_{2}$ and $X_{3}$ are not exchangeable. The $n=2$ cas was deceptive !


Does a Jordan chain always start with an eigenvector?

Question: Does a Jordan chain always start with an eigenvector? If so when computing a Jordan chain for a particular matrix do you have to start with an eigenvector, $v_0$ for particular eigenvalue then just go up the chain with $(A-\lambda I)v_{i} = v_{i-1}$?
Answer: Yes, a Jordan chain necessarily starts with an eigenvector, because $(A-\lambda I)v_0$ should be zero (otherwise, you could "extend" the chain further down).
When you have a Jordan canonical basis, the initial vectors of the chains corresponding to $\lambda$ will form a basis of the eigenspace corresponding to $\lambda$.