Restricting view to content associated with user profile

Question: On my site some users have the permission to see others' profile.
I'm looking to show a view in a block containing a food content type. It will be displayed on the profile page of the users (user/*). The block will contain content associated with that user (somehow I need to tell that when I am creating the content).
For example: Content "rice" belongs to user1; content "potatoes" belong to user2.
When I enter the user1's profile I see "rice"; when I enter user2 profile I see "potatos". It's the same block with the information changing according to the user profile I am seeing.
Answer: What you're wanting is a contextual filter for your view. Create a node view with a block display and in the Advanced section under Contextual Filter click the Add button.
From there you can add Content: Author uid which will tell the view to filter by author UID. On the popup modal, under the WHEN THE FILTER IS NOT.... fieldset, select Provide default value with Type of Raw value from URL and Path component of 2. This essentially tells the view to pull the UID from Drupal's internal path (i.e. the XXX in /user/XXX when viewing a user page).
After saving the view, you should be able to place it your region to display against user profile pages.


Função nodejs, funcionamento

Question: app.get('/', function(req, res){
    res.send('Ola Mundo');
  });

No caso deste código simples só para ilustrar temos uma função em nodejs com 2 parâmetros a requisição e a resposta, eu queria saber se alguém consegue me explicar melhor como isto funciona na integra, afinal o meu conceito de função em outras linguagens e frameworks, quando se tem 2 parâmetros, significa que a função deve receber tais parâmetros.
Como em um caso onde:
function area(a, b) {
 c = a.b
 return c
}

Ao receber a e b temos o resultado final retornado c, porém no node não é isso que acontece pelo menos a minha perspectiva, o parâmetro REQ de fato é uma requisição do cliente, mas o parâmetro RES normalmente é manipulado dentro da função como um parâmetro de retorno e não de entrada, é como se o requisitante pedisse algo e já desse a resposta, e a gente só trata-se isso e devolve-se o que ele já tem.
Ficou claro a dúvida?
É bom conceitual espero que alguém entenda e consiga me tirar essa dúvida que tá apertando minha mente...
Answer: Começo por dizer que app.get é uma função normal que recebe dois parâmetros: Um caminho na forma de string e um callback. Logo pode visualizar esta função assim:
app.get(caminho, callback);

No seu o exemplo o caminho é '/' e o callback é function(req, res){res.send('Ola Mundo');}.
Após este primeiro ponto, callbacks é provavelmente um tópico que irá querer aprofundar, e que será grande parte da confusão. O motivo pelo qual recebe um callback é porque a função é assíncrona e apenas será chamada mais tarde quando um pedido HTTP for feito.
Aproveito para fazer um pequeno contra-exemplo da sua função de area com callbacks, mas não sem primeiro a corrigir:
function area(a, b) {
  let c = a * b;
  return c;
}

Esta mesma função poderia ser escrita com um callback ainda que não fizesse muito sentido pois não é assíncrona. Mas ficaria da seguinte forma:

function area(a, b, callback){
  let c = a * b;
  callback(c);
};

area(10, 5, function(resultado) {
  console.log(resultado);
});

Neste exemplo o callback é uma função que recebe o resultado e faz qualquer coisa com ele, e faria sentido se fosse assíncrona.
Vamos então modificar este exemplo incluindo um setTimeout:

function area(a, b, callback){
  let c = a * b;
  setTimeout(() => callback(c), 2000); //só processa o resultado passado 2 segundos
};

area(10, 5, function(resultado) {
  console.log(resultado);
});

console.log("Calculo leva 2 segundos a ser feito");

Repare que em ambos os exemplos não existe return pois a função é assíncrona.
Voltando agora ao Node e Express, o function(req, res){ é na verdade o callback, ou seja a função com o código que você quer que execute quando aquela rota for chamada. Esta pode ser chamada por vários métodos, tais como get, post, patch, delete, entre outros e isso é codificado como string no primeiro parâmetro. O callback é chamado com dois parâmetros que são objetos e normalmente levam o nome de req e res respetivamente, embora possam ter qualquer outro nome que queira.

o parâmetro REQ de fato é uma requisição do cliente

O parâmetro req é um objeto com várias das informações do pedido que o cliente fez, tais como:

body - contem pares chave valor do corpo do pedido
params - contem os parâmetros do pedido que são a parte dinâmica do endereço
ip - o endereço ip de onde partiu o pedido

E o res é também um objeto que representa a resposta e tem vários métodos para controlar a mesma, tais como:

status - alterar o código http da resposta
send - enviar a resposta com o respetivo corpo
redirect - para redirecionar para outra rota

Aconselho também a dar uma olhada e explorar um pouco a documentação do Express para ficar mais dentro do que representam estes objetos e todas as funcionalidades suportadas
Comment: Muito bom, me passei ali no  a.b, tava digitando sem nem pensar já, Vou dar uma olhada nas documentações e o conceito mais aprofundado de call back.

Função nodejs, funcionamento


Probability that exactly $3$ compartments have a passenger: what's wrong with my solution, how was the textbook answer obtained?

Question: Exercise:
train car has $9$ compartments, each compartment has $4$ beds. There are $7$ passengers in the car. Find the probability that exactly $3$ compartments have a passenger.
My solution:
size of the event space is $C_{36}^{7}=\frac{36!}{7! \ 29!}.$ There are three ways for three compartments to be occupied: $7=1+2+4=1+3+3=2+2+3:$ one person in a compartment, two people in an other compartment, four people in yet another compartment, and the same for the next two decompositions of $7$.
Let's look at the first decomposition: the first person can choose any of the nine compartments, and any of the for four beds: $9\cdot4.$ The pair can choose out of eight remaining compartments, and a combination is needed to see in how many ways they can choose the beds: $8 \cdot C_{4}^{2}$. For the four people: $7\cdot 4$. Combining, we get $9\cdot4\cdot8\cdot C_4^2 \cdot7\cdot3$.
We do the same for the remaining two decompositions of $7$, and the answer is:
$$
\frac{9\cdot4\cdot8\cdot C_4^2 \cdot7\cdot 4 + 9\cdot 4 \cdot 8\cdot 4 \cdot 7\cdot 4 + \ 9\cdot C_4^2 \cdot 8\cdot C_4^2 \cdot 7\cdot 4}{C_{36}^7} = \frac{532}{28 985}.
$$
Textbook answer:
$$
\frac{C_9^3C_12^7 - C_9^2 C_8^1}{C_{36}^7} = \frac{46}{5797}.
$$
How did they get the textbook answer?
What is wrong with my solution?
Answer:
"The pair can choose out of eight remaining compartments, and a combination is needed to see in how many ways they can choose the beds: $8⋅C^2_4$. For the three people: 7⋅4"

You mean ".... for the four people". It's 1+2+4, not 1+2+3.
Also, for the combination 1+3+3, you need to break it down this way:

The solo passenger can pick any of the 9 compartments, and any of the 4 beds, that's $9\times 4$
The first trio can choose any of the 8 compartments, and there are 4 ways to pick their beds.
The second trio can choose any of the 7 compartments, and there are 4 ways to pick their beds.
But this double-counts the combinations, since there's no difference between (for example) "the first trio picks compartment A and the second picks Z" and "the first trio picks compartment Z and the second picks A", so you need to divide by $2!$

Alternatively,

The solo passenger can pick any of the 9 compartments, and any of the 4 beds, that's $9\times 4$
There are $C^2_8$ ways to choose two compartments for the two trios, and then $4\times 4$ ways for them to choose their beds.

As an aside: the more standard notation for (say) $C^4_{52}$ is ${}^{52}C_4$
You've similarly overcounted the 3+2+2's.
As an aside, the textbook answer seems to approach the problem like so:
Let's pick 3 cabins for them: there's ${}^9C_3$ ways to do that. Then let's pick beds for them out of the 12 beds: there's ${}^{12}C_7$ ways to do that.
Unfortunately, some of those combinations have everyone packed into just two (or maybe fewer) cabins, so we need to subtract those combinations.
Let's pick 2 cabins: there's ${}^9C_2$ ways to do that. Then let's pick beds: there's ${}^8C_7$ ways to do that.
So the number of ways to pack them into exactly 3 cabins is ${}^9C_3\times{}^{12}C_7-{}^9C_2\times{}^{8}C_7$.
Comment: For what it's worth, (a) I feel a little uneasy about the textbook's method, but can't put my finger on why (b) the two methods are giving different answers, and (c) I wrote a program to literally go through all possible combinations, and I get:
* 288 ways they can be in 2 cabins
* 64512 ways they can be in 3,
* 1048320, 3548160, 3096576 and 589824 ways they can be in 4, 5, 6 and 7 cabins

for a total of 8347680 = 36 choose 7 ways they can choose the beds.
Comment: If you want to argue with the teacher / textbook author, solve the case where there are 2 people, the train has 3 cabins with 2 beds each. And we want the number of combinations where there are 2 occupied cabins.

Your method gives 12. The textbook's method gives 15, which is nonsense, since there are only 15 ways to allocate 2 people to 6 beds. Literally drawing pictures of all the combinations gives 12.
Comment: I know what's wrong with the textbook's method now.

When they say "choose 3 cabins, and distribute the people amongst the 7 beds" they're thinking that gives "how many ways to have the 7 people in 3 or fewer cabins". So they then subtract the number of ways to "choose 2 cabins, and distribute the people amongst the 7 beds".

But their method massively overcounts some combinations: eg, if I choose cabins A,B,C, and sleep the people in A1,A2,A3,A4,B1,B2,B3, I'll end up counting that combo again when I choose cabins A,B,D, and then A,B,E, and so on.
Comment: Clear and helpful. Thank you.
Answer: The question is very vague as to which entities are identical and which are distinct, and as Michael Hartly has pointed out in comments, the text book computations, too, are awry.
The best clue we get is from $^{36}C_7$ in the denominator which means that the matching numerator must be the number of ways that $7$ distinct berths have been occupied in exactly $3$ distinct compartments.
I am  giving the simplest  way to compute the numerator combinatorially, which Michael Hartley has  worked out through a program.
The three compartments can be chosen in $^9C3$ ways, and  there are three patterns of possible berth allotments, $4-2-1$ with $6$ permutations, $3-3-1$ with $3$ permutations and $3-2-2$, again with $3$ permutations.
Thus the required # of ways
$= \small{{}^9C_3\left({}^4C_4\cdot{}^4C_2\cdot{}^4c_1\cdot6 + {}^4C_3\cdot{}^4C_3\cdot{}^4C_1\cdot3 + {}^4C3\cdot{}^4C_2\cdot{}^4C_2\cdot3\right)} = 64512$
and $Pr = \dfrac{64512}{{}^{36}C_7} =\dfrac{224}{28985}$


requestAnimationFrame looping causes velocity to increase when it says it's 0

Question: This is the best way I could frame the question. I have two squares on the screen, and am trying to program collision detection. This is vanilla javascript and my code has detailed comments, please take a look, I have been stuck on this for some time.
To be specific, I set the square.yVelocity to 0 when touching any point within the top width of square2(also did this with x and sides). Even with this being set, and showing in the console when logged, square continues to move through square2.
Here is my code:

const context = document.getElementById("canvasmulti").getContext("2d");

canvasmulti.width  = window.innerWidth;
canvasmulti.height = window.innerHeight;

//CHARACTER:
const square = {
    height: 75,
    jumping: true,
    width: 75,
    x: canvasmulti.width - 75,
    xVelocity: 0,
    y: canvasmulti.height / 2,
    yVelocity: 0
  };

  const square2 = {
    height: 75,
    jumping: true,
    width: 75,
    x: 0,
    xVelocity: 0,
    y: canvasmulti.height / 2,
    yVelocity: 0
  };

//MOVEMENT:
const controller = {
    left: false,
    right: false,
    up: false,
    keyListener: function (event) {
      let key_state = (event.type == "keydown") ? true : false;
      switch (event.keyCode) {
        case 37: // left arrow
          controller.left = key_state;
          break;
        case 38: // up arrow
          controller.up = key_state;
          break;
        case 39: // right arrow
          controller.right = key_state;
          break;
      }
    }
  };

  const controller2 = {
    left: false,
    right: false,
    up: false,
    keyListener: function (event) {
      let key_state = (event.type == "keydown") ? true : false;
      switch (event.keyCode) {
        case 65: // left arrow
          controller2.left = key_state;
          break;
        case 87: // up arrow
          controller2.up = key_state;
          break;
        case 68: // right arrow
          controller2.right = key_state;
          break;
      }
    }
  };

  const loop = function () {

    //controller one
    if (controller.up && square.jumping == false) {
      square.yVelocity -= 30;
      square.jumping = true;}
    if (controller.left) {
      square.xVelocity -= 0.5;}
    if (controller.right) {
      square.xVelocity += 0.5;}

    //controller two
    if (controller2.up && square2.jumping == false) {
        square2.yVelocity -= 30;
        square2.jumping = true;}
    if (controller2.left) {
        square2.xVelocity -= 0.5;}
    if (controller2.right) {
        square2.xVelocity += 0.5;}

      //controller one
    square.yVelocity += 1.5;// gravity
    square.x += square.xVelocity;
    square.y += square.yVelocity;
    square.xVelocity *= 0.9;// friction
    square.yVelocity *= 0.9;// friction

    //controller two
    square2.yVelocity += 1.5;// gravity
    square2.x += square2.xVelocity;
    square2.y += square2.yVelocity;
    square2.xVelocity *= 0.9;// friction
    square2.yVelocity *= 0.9;// friction

    // if square1 is falling below floor line
    if (square.y > canvasmulti.height - 75) {
      square.jumping = false;
      square.y = canvasmulti.height - 75;
      square.yVelocity = 0;
    }

    // if square2 is falling below floor line
    if (square2.y > canvasmulti.height - 75) {
        square2.jumping = false;
        square2.y = canvasmulti.height - 75;
        square2.yVelocity = 0;
    }

    // if square1 is going off the left of the screen
    if (square.x < 0) {
      square.x = 0;
    } else if (square.x > canvasmulti.width - 75) {// if square goes past right boundary
      square.x = canvasmulti.width - 75;
    }

    // if square2 is going off the left of the screen
    if (square2.x < 0) {square2.x = 0;}
    else if (square2.x > canvasmulti.width - 75) {// if square goes past right boundary
        square2.x = canvasmulti.width - 75;
    }

    // Creates the backdrop for each frame
    context.fillStyle = "#394129";
    context.fillRect(0, 0, canvasmulti.width, canvasmulti.height); // x, y, width, height

    // Creates and fills square1 for each frame
    context.fillStyle = "#8DAA9D"; // hex for cube color
    context.beginPath();
    context.rect(square.x, square.y, square.width, square.height);
    context.fill();

    // Creates and fills square2 for each frame
    context.fillStyle = "#781818"; // hex for cube color
    context.beginPath();
    context.rect(square2.x, square2.y, square2.width, square2.height);
    context.fill();

    // Collision detection of square1 with square2

    if (square.x <= square2.x + square2.width &&
        square.x >= square2.x + square2.width - square2.width/2 && square.y >= square2.y &&
        square.y <= square2.y + square2.height)
        {square.xVelocity = 0;}; // left square1 touching right square2

    if (square.x + square.width >= square2.x && square.x + square.width <= square2.x + square2.width/2 &&
        square.y >= square2.y &&
        square.y <= square2.y + square2.height)
        {square.xVelocity = 0;}; // right square1 touching left square2

    if (square.x <= square2.x + square2.width &&
        square.x >= square2.x && square.y + square.height >= square2.y )
        {square.yVelocity = 0;}; // bottom left square1 touching top square2

     if (square.x + square.width <= square2.x + square2.width &&
         square.x + square.width >= square2.x && square.y + square.height >= square2.y )
        {square.yVelocity = 0;}; // bottom right square1 touching top square2

    // Collision detection of square2 with square1

    // call update when the browser is ready to draw again
    window.requestAnimationFrame(loop);

  };

  //square1
  window.addEventListener("keydown", controller.keyListener)
  window.addEventListener("keyup", controller.keyListener);
  //square2
  window.addEventListener("keydown", controller2.keyListener)
  window.addEventListener("keyup", controller2.keyListener);

  window.requestAnimationFrame(loop);
<canvas id="canvasmulti"></canvas>
Comment: My best guess is that the order of different things is what is causing the issue, but I can't seem to find the correct order.
Comment: The run code button works now. It got rid of my canvas for some reason.
Answer: The reason, I believe, is because you have already added the vector. So if you're going to make the velocity 0, you may want to set the position manually or subtract the velocity before clearing it.
for example:
if (square.x <= square2.x + square2.width &&
  square.x >= square2.x + square2.width - square2.width/2 && square.y >= square2.y &&
  square.y <= square2.y + square2.height)
  {
    // left square1 touching right square2
    square.x = square2.x + square2.width; // <== set it to a position where they don't overlap
    square.x -= square.xVelocity; // <== OR just subtract it
    square.xVelocity = 0;
  }

it gets a bit more complicated with the y vector, since you need to consider the gravity too, so setting the value may work better than adjusting it.
Comment: THIS WORKS!!! The setting it option you gave works much better for me :) , thank you so much.


Wordpress short codes display the codes itself not the elements

Question: I installed a carousel plugin which provided a short code for me to use
which is "wcf" before the gallery keyword , but unfortunately - no short codes works with me at all

I tried to edit the home page - I used the text tab to insert the following codes

but this not work
[wcfgallery ids="149,148,147,146,145,144,138,132,133,139,140,141,135,136,142,143,137"]

this also not work
[gallery ids="149,148,147,146,145,144,138,132,133,139,140,141,135,136,142,143,137"]

it display the code itself on the page
Comment: its from text widget?
Comment: @Tim , thanks - I removed the tag
Comment: did you installed it correctly? maybe compiler is missing, like visual composer is a compiler
Comment: You put it directly on the code or in the editor ?
Comment: @AlexVand - in the text tab not the visual editor
Comment: Add your shortcode in "text-editor". And make sure your plugin activated properly.
Comment: Try to paste it in the visual editor
Comment: @ManishaVasani - Yes I actually add it in the text editor tab
Comment: @AlexVand it is the same - no difference
Comment: So you missed something else. Can you describe the step you've done in your question ? From the installation to the moment it don't work.
Comment: I edited the question - tried to provide info as much as I can
Comment: What does this have to do with WCF (Windows Communication Foundation)?
Answer: Add this script in functions.php if you are using shortcode in text widget.
// Adding Shortcodes to the_excerpt() function
add_filter('the_excerpt', 'do_shortcode');

// Enable shortcodes in widgets
add_filter('widget_text', 'do_shortcode');

Replace the_content() to this <?php echo apply_filters( 'the_content', $post->post_content ); ?>
Comment: I copied your exact codes and pasted it in functions.php , unfortunately the same results
Comment: can you post your home page script?
Comment: where's this script ? - so I can copy it for you
Comment: I don't have a function called the_excerpt()
Comment: replace `the_content()` to this `post_content ); ?>` line number #20
Comment: unfortunately , the same results - the edits on this page "template-parts/content-page.php"
Comment: homepage is a template or default template?
Comment: I am not sure - I don't have a good experience with wordpress - anyway - I may detected my issue - it works when I add my short_code to custom html widget - but in text/visual editor will not work


How are user.tokens.inc and other similar files included?

Question: I notice that many core modules in Drupal 7 implement hook_token_info and hook_tokens in a hook.tokens.inc file, but I can't figure out how this file is included. Should I be doing the same with my own module? How can I be sure it will be loaded?
Answer: They do it by way of hook_hook_info():

Defines one or more hooks that are exposed by a module.
Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.

As luck would have it, the example from the docs shows exactly how the Token module does it:
function hook_hook_info() {
  $hooks['token_info'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens'] = array(
    'group' => 'tokens',
  );
  return $hooks;
}

Should I be doing the same with my own module?

Totally up to you - it certainly can't hurt, other modules that need to implement your hook will just have an extra option for storing the hooks. But if you don't, they can still implement your hooks in the .module file anyway.
Comment: By "should I be doing the same", I meant should I put tokens in a separate file like that?
Comment: Ah ok - same response really, totally up to you :) This sort of thing will come in more useful as your module grows and you start implementing a lot of hooks. By then you'll probably want to trim the main .module file down, and the reason this hook exists will be very clear
Comment: Well, between eight hook implementations, one API function, and four "private" helper functions, totaling more than 500 lines, shaving off the token components (which are the largest implementations) does make it a bit easier to manage. Now that I know how that $module.tokens.inc file gets loaded I can take advantage of it. I was not aware of hook_hook_info; thanks for the answer!


How to mock mongo with python

Question: How to create a mocked mongo db object to test my software using python?
I tried https://pytest-mock-resources.readthedocs.io/en/latest/mongo.html but got error.
First, i tried the code below:
def insert_into_customer(mongodb_connection):
    collection = mongodb_connection['customer']
    to_insert = {"name": "John", "address": "Highway 37"}
    collection.insert_one(to_insert)

from pytest_mock_resources import create_mongo_fixture
mongo = create_mongo_fixture()

def test_insert_into_customer(mongo):
    insert_into_customer(mongo)

    collection = mongo['customer']
    returned = collection.find_one()

    assert returned == {"name": "John", "address": "Highway 37"}

test_insert_into_customer(mongo)

I got the error below:
Traceback (most recent call last):
  File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 19, in <module>
    test_insert_into_customer(mongo)
  File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 11, in test_insert_into_customer
    insert_into_customer(mongo)
  File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 2, in insert_into_customer
    collection = mongodb_connection['customer']
TypeError: 'function' object is not subscriptable

And then i tried the code:
def insert_into_customer(mongodb_connection):
    collection = mongodb_connection['customer']
    to_insert = {"name": "John", "address": "Highway 37"}
    collection.insert_one(to_insert)

from pymongo import MongoClient
from pytest_mock_resources import create_mongo_fixture

mongo = create_mongo_fixture()

def test_create_custom_connection(mongo):
    client = MongoClient(**mongo.pmr_credentials.as_mongo_kwargs())
    db = client[mongo.config["database"]]

    collection = db["customers"]
    to_insert = [
        {"name": "John"},
        {"name": "Viola"},
    ]
    collection.insert_many(to_insert)

    result = collection.find().sort("name")
    returned = [row for row in result]

    assert returned == to_insert

test_create_custom_connection(mongo)

and got the error:
Traceback (most recent call last):
  File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 30, in <module>
    test_create_custom_connection(mongo)
  File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 14, in test_create_custom_connection
    client = MongoClient(**mongo.pmr_credentials.as_mongo_kwargs())
AttributeError: 'function' object has no attribute 'pmr_credentials'

It looks like mongo is a function not a MongoClient.
How can i use the library pytest_mock_resources to mock mongo?
Is there a better library to mock monodb to test with pytest?
Comment: Does this answer your question? [How to mock mongodb for python unittests?](https://stackoverflow.com/questions/42239241/how-to-mock-mongodb-for-python-unittests)
Answer: import mongomock
client = mongomock.MongoClient()
database = client.__getattr__(database_name)
collection = database.__getattr__(collection_name)

You can define as many as client, database and collections you need at the same time.

How to mock mongo with python


Google Spreadsheet Script to selectively protect certain cells?

Question: Long time viewer of this site, first time poster.
I have this spreadsheet that is public and runs off of crowd sourced information.
Every time a new person enters data, I like to protect the data they have submitted so that is not erased or changed by others. This has proved to be a somewhat lengthy task once a good bit of data has been added.
My question is, is there a script that I can run that works like: if value in any cell > 0, then protect cell?
This would allow me to open up the spreadsheet and see that all the values entered are legitimate, then protect all the cells with values with one click.
Thanks in advance!
Will
Answer: Unfortunately, it's not currently possible to manipulate the 'Protect Range' with Google Apps script. There's currently an open issue with this here, which you should star for traction and to receive updates on if this is resolved.
Currently you can only protect an entire page, which looking at your sheet, won't do you much good I think.


React Parent and Child component data flow

Question: At loss when it comes to a reusable component I am making in React. The purpose of the component is to get API data and send it to parent where the data in mapped in cards. The component should also be able to receive a function call from the parent that is used to 'load more' data and props which to set whether I search old / new data.
I haven't been able to figure the best way to achieve this or whether I should do it that I through props.children I would display the cards inside the child, hence no need to send data upwards.
Parent:
function Page() {

    const [eventData, setEventData] = useState([]);

    const EventCardUpcoming = () => {
        const filterRef = useRef(null);

        const handleClick = () => {
            filterRef.current.callLoad();
        };

        const setData = () => {
            setEventData()
        }

        return (
            <InfiniteScroll
                pageStart={0}
                hasMore={true || false}
                loadMore={handleClick}
            >
                <button onClick={handleClick}>Load more</button>
                <Row className="py-4">

                        <EventFiltering
                            OrganizerId={"1"}
                            ref={filterRef}
                            sendData={setData()}
                        />

                    {eventData ?

                        {eventData.map((v, i) => (
                            <Col key={i} xs={12} sm={12} md={6} lg={4} xl={3}>

                                    <>
                                        <EventCard eventData={v} />
                                    </>

                            </Col>
                        ))}

                    : null}
                </Row>
            </InfiniteScroll>
        );
    };
    return (
        <Container>
            <EventCardUpcoming />
        </Container>
    );
}

export default Page;

Filtering child component:
const Filtering = forwardRef((props, ref, { sendData }) => {

    const staticOrganizer = props.OrganizerId; //API configurable option

    const paramLimit = 4;
    const [eventData, setEventData] = useState([]);

    let params = {
        org: staticOrganizer,
        limit: paramLimit,
    };

    useImperativeHandle(ref, () => ({
        callLoad() {
            handleLoadMore(); //load more data from function called in parent
        },
    }));

    useEffect(() => {
        sendData(data); //send data to parent when more is fecthed
    }, [eventData]);

    const handleLoadMore = () => {
        APIGet("getData", params).then((res) => {
            if (res.data.body.length > 0) {
                setEventData((eventData) => eventData.concat(res.data.body));
            }
        });
    };

        return (
            <Container>

                    <Dropdowns />

            </Container>
        );
    }
);

export default Filtering;

Comment: **The purpose of the component is to get API data and send it to parent** - sounds like a hook, not a component to me
Comment: Hi! Bit more complex than that because it as the  component through which the user can set several filters to what kind of data to get. I omitted it from code as it functions without and issue and the question is how to receive and send data, props and function.
Answer: Lose the parenthesis
sendData={setData}

update setMethod to accept data as param
  const setData = (data) => {
      setEventData(data)
  }


Vite with Redoc Left Panel Missing

Question: I'm developing an React application with vite and redoc. For some reason the left panel with the quick links is just not appearing when I generate the spec. I've verified it isn't the specs. Imaged demonstrating the expected versus actual behavior is below. Any idea why the left panel could be missing?
Relevant dependencies in package.json:
"@mui/material": "^5.11.12",
"core-js": "^3.31.1",
"mobx": "^6.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.3",
"redoc": "^2.0.0-rc.72",
"styled-components": "^5.3.5",
"vite-plugin-node-polyfills": "^0.9.0"

My vite.ts:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslint from 'vite-plugin-eslint';
import { nodePolyfills } from 'vite-plugin-node-polyfills';

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    manifest: true,
  },
  plugins: [react(), eslint(), nodePolyfills({ globals: { process: true }, protocolImports: true })],
});

Thanks,
Answer: After a painstaking few days, finally got this working.
When running npm install redoc, one of its dependencies mobx-react^7.2.0 was automatically installed. My organization's private npm repository's latest mobx-react version is 7.2.1. Turns out email@example.com is incompatible with this version of redoc (which shouldn't have been the case, but maybe there's been an update since then) but firstname.lastname@example.com is compatible.
Moral of the story, try downloading from a public registry to see if something works, and narrow down the broken dependency structure from there!

Vite with Redoc Left Panel Missing


How to Generate a Series for Each Week between 2 Dates (1 year)

Question: I have a login history table in my database that records every time someone successfully logs in to my app.
I am trying to create a view that will return counts of active user logins by week (Every 7 days) from 730 days ago to 365 days ago.  Basically, 365 days before the last 365 days.  So for example, the current date is April 21, 2022.  I'd like to generate a series of integers 1-53 (53 instead of 52 because of the 1 extra day) between the dates April 21, 2020 and April 20, 2021.  Each integer represents the week number.  Because of this, simply doing a to_char on the dates with 'WW' won't work.  Bringing in the need to perform counts for each of these weeks is also a challenge, and I can't seem to figure out how to write the view query.
A very simplified version of my login history table basically looks like the following
<code> user_id | logged_in_on
---------|---------------------
 1       | 2020-04-21 13:22:14
 2       | 2020-04-21 17:38:11
 1       | 2021-04-28 16:32:21
 5       | 2021-04-18 04:33:45
</code>
So the results I would like the view to contain should look something like the following
<code> week | login_count
------|-------------
 1    | 2
 2    | 1
 3    | 0
 .
 .
 .
 51   | 0
 52   | 1
</code>
The resulting view should contain a record for each week, or period of 7 days, from 730 days ago to 365 days ago.  It doesn't necessarily have to contain week numbers.  It can also be 2 date columns that contain the start and end dates of each week.  As long as each record in the view represents a week would be fine for me to use.
Is it even possible to create a single query that's able to return this data?
Answer: I figured it out.  The following query should generate a series of dates, each date representing the first date of each set of a week (7 days) starting from 730 days ago and ending at 365 days ago from the current date.
<code>SELECT
   to_char(i::date, 'YYYY-MM-DD') AS week_start_date
FROM
   generate_series(CURRENT_DATE-INTERVAL '730 day', CURRENT_DATE-INTERVAL '365 day', '1 week') i;
</code>


Reusing LINQ expressions created in a Portable Class Library

Question: Is it possible to create a LINQ expression inside a Portable Class Library and reuse the expression in other parts of the application? One handy use case for me would be to utilize these expressions in CompiledQuerys across platforms instead of copy/pasting the same code multiple times.
All my attempts so far ended up in throwing some more or less meaningless runtime exception (NullReferenceException, Column not found..). I'm guessing LINQ expressions in a PCL are handled differently than for example in a WP application?
public class SomeClassNotInPCL
{
    private static readonly Func<Context, int, MyClass> CompiledQuery =
        CompiledQuery.Compile(ClassFarAway.MethodInsidePCL());
}

public class ClassFarAway
{
    private static Expression<Func<IContext, int, MyClass>> MethodInsidePCL()
    {
        return (context, id) => context.MyClass.FirstOrDefault(m => m.Id == id);
    }
}

Comment: Expression as in Linq Expressions or Regular Expressions?
Comment: Good point. I'm interested in System.Linq.Expressions.Expression.
Comment: Sample code can help out greatly. Is this L2SQL? L2EF? L2O?
Answer: How about something like this?
var commonExpressions = new Dictionary<CommonRegEx, Regex>();

public enum CommonRegEx{
   Phone,
   Email,
   SSN
}

Comment: Thanks for the feedback. I see absolutely nothing wrong with your example and it likely will work like a charm, however, I'm looking to reuse Linq Expressions between multiple platforms.


Bounding expectation of stopping time

Question:
Let $(X_{t})_{t\ge0}$ be adapted to $(\mathcal{F}_{t})_{t\ge0}$ with continuous trajectories. Assume that $X_{0} = 0$ and $X_{t}^{4} - 3t^{2}$ is a martingale with respect to $(\mathcal{F}_{t})$. Let
  $$\tau = \inf\left\{t>0 : |X_{t}| = \sqrt[4]{(t^2+9)}\right\}.$$
  Prove that $\mathbb{E}\tau^2 < \infty$ and compute $\mathbb{E}\tau^2$.

I know that if $\mathbb{E}\tau^2 < \infty$ then by Doob we get $\mathbb{E}\tau^2 = 4.5$. The problem is that I cannot prove $\mathbb{E}\tau^2 < \infty$. I was thinking of a function $g(t) = |X_{t}| - \sqrt[4]{(t^2+9)}$ which is continuous a.s. and $g(0) < 0$. Then if I find any $t_{0}$ such that $g(t_{0}) > 0$ it will be proved. Is there any other way of doing that?
Answer: The optional stopping theorem shows that $$M_t :=X_{t \wedge \tau}^4-3 (t \wedge \tau)^2, \qquad t \geq 0; $$ is a martingale; in particular, $\mathbb{E}(M_t)=0$ for all $t \geq 0$, i.e. $$\mathbb{E}(X_{t \wedge \tau}^4) = 3 \mathbb{E}((t \wedge \tau)^2).$$ Since $X_{t \wedge \tau}^4 \leq (t \wedge \tau)^2+9$  for all $t \geq 0$, this gives $$2 \mathbb{E}((t \wedge \tau)^2) \leq 9.$$ Applying the monotone convergence theorem, we conclude that $\mathbb{E}(\tau^2) \leq 9/2< \infty$.

Bounding expectation of stopping time


Why would file services only be setup for TCP 139?

Question: I am learning a legacy system where the security team only opened TCP port 139 between web servers and a file server (both Windows 2008 R2) for file access.  I have usually used TCP port 445 for such access.  Why would the recommend using port 139 only?  Are there benefits from using Port 139 over port 445 or vise versa?
Answer: This is explained in Q204279.
In short: earlier Windows versions (pre Windows 2000) used "NetBIOS over TCP/IP" (with 137/udp, 137/tcp, 138/udp and 139/tcp) to offer the SMB protocol. Newer versions can skip the NetBIOS part and can communicate directly with other hosts via 445/tcp and NetBIOS can be disabled.
Oh, and as to why anyone would use one or the other: 139/tcp would be used if older Windows clients are in use that don't know about direct SMB. But in general 445/tcp would be preferable, as it's easier to configure just one port as 4 different port/protocol configurations in e.g. a firewall.
Comment: In NetBIOS, port 138 is for UDP, so telnet would not be able to connect to that port. Same for port 137, although Q204279.names 137/tcp also, I've never seen port 137 configured for TCP, only UDP.
Comment: Found this PowerShell command to check UDP connection.  If returns without error it was able to connect.  Use at own risk:
(New-Object Net.Sockets.UdpClient).Connect("",)
Comment: Nice, but it returns w/o error for every UDP connection, because of...well, UDP really. One has to watch the other end if something has actually been sent over the wire.
Comment: True, but if the port isn't open, e.g. blocked by firewall, it will error.  It's at least a smoke test without having to load software on either side.
Comment: Not here, "PS> (New-Object Net.Sockets.UdpClient).Connect("some-host",1234)" always comes back w/o errors, although there's really nothing listening on 1234/udp. For TCP connection, your command works just fine and it errors out when it's unable to connect.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12624/discussion-between-brettski-and-ckujau)
Comment: Just as I was thinking.  I appreciate you confirming for me. The strange part is that it seems only TCP 139 is open from web to file server.  Using telnet I was unable to connect on 137 or 138. Strange setup.


run a url on command line without using curl or wget content on same server

Question: The background to this is I have a function on a website i wish to run once a day, the cron and website or on the same server. My website is using cloudflare and my cron runs the curl command to run the function. This works about 50% of the time, the other 50% i get a 522 cloudflare error. So I need to bypass cloudlfare really to run this.
So lets say my curl was https://my-site.com/index.php?action=do-task and the path on the server to the index.php file is var/www/html/index.php
how is the best way to do this so the do-task action is passed into the index.php file?
i'm thinking something like
php /var/www/html/index.php

might work but can't work out how i would pass the action = do-task part
thanks
Craig
Comment: you can do `curl http://localhost/index.php?action=do-task` this way it doesn't go outside the server.
Answer: If the page is already using $_GET then check for command line arguments, make them into a query string and parse them into $_GET:
if(isset($argv)) { parse_str(implode('&', $argv), $_GET); }

Then call your script like this:
php /var/www/html/index.php action=do-task

$_GET will contain:
Array
(
    [index_php] =>
    [action] => do-task
)

For more parameters just separate with a space:
php /var/www/html/index.php action=do-task foo=bar


Need Help with Trumpet Lesson and Piano Chords

Question: Not sure how to explain my problem so please bear with me.
I'm studying IIm7-V7 Etude from a Trumpet book called "Amazing Phrasing".  It's called Idea #11 if anyone happens to have the book. It's a Hal Leonard book written by Dennis Taylor and Steve Herrman.
Anyway I'm guessing it's written for Bb Trumpet.   And this is going to get really confusing unfortunately.   It's actually playing on a II-V-I progression.  But this exercise is using IIm7-V7-Imaj7.  The chords are called out as Cm7-F7-Bbmaj7.  Then on the staff the notation is written in the key of C (i.e. no key signature), however during this phrase they actually flat the B and E notes.  So it sure seems like the Trumpet is playing in the key of B flat.
I even have a CD recording of the exercise that came with the book.  The chords are being played by a piano and the Trumpet is playing the notes as written on the score.
Here's my problem.  When I go to my keyboard to play these chords they don't sound right at all.   And it's even weirder than this.  The Cm7 chord does sound ok for the first chord.  But then when I play the F7 chord it sounds way off.  Actually if I play an Eb7 that sounds right.  Then the I chord is supposed to be Bbmaj7, but once again that sounds absolutely horrible when played on my keyboard.  The only thing that sounds right is to go back and play another Cm7 chord.
So I end up playing Cm7 - Eb7 - Cm7 on the keyboard, which still doesn't sound right, but it sounds far better than anything else I play.
I'm at the end of my rope here.  So much so I'm wondering if the book contains some sort of misprint?  It's driving me crazy.
I wanted to create my own backing track on the keyboard so I can change up the tempo and rhythm.  But I can't seem to get the harmony to come out right.
I wish I could show what I'm actually doing.  But this is getting really frustrating.
By the way for more technical info here's the trumpet part with piano chords: (as written in the book)
(first half measure)
Piano Chord: Cm7 --
Bb Trumpet notes: C Eb G Eb
(second half measure)
Piano Chord: F7 --
Bb Trumpet notes: F Eb C A
(last measure of phrase)
Piano Chord: Bbmaj7 --
Bb Trumpet notes: Bb A Bb C D rest.
~~~~~
Are the Piano Chords written in concert Bb?  Or am I missing some transposition here?
I'm just totally confused.  I just can't make this sound right.  It sounds ok on the backing track.  Unfortunately I can't separate the piano from the trumpet on the backing track.  So I can't hear the piano chords without the trumpet playing over them.
But the best I can come up with is Cm7 Eb7 and back to Cm7.  That can't be right?  And it doesn't sound right either.  But if I try playing Cm7 F7 Bbmaj7 it sounds horrible.
I'm totally lost and confused.
I just want to practice the trumpet but I can't figure out the correct chords to play on the keyboard.  I'm not having any problems at all playing the trumpet melody.  I got that much down pat.
Can anyone help me out here?
Comment: You should probably go to the Hal Leonard web site and contact them through the form (https://www.halleonard.com/contactus.do) about this
Comment: You should probably go to the Hal Leonard web site and contact them through the form (https://www.halleonard.com/contactus.do) about this
Comment: Try the chords - Bbm7, Eb7, Abmaj7. The numbers aren't too important, so Bbm, Ebm, Ab should work. If it's for a Bb trumpet - the most common - the notes played come out a tone lower than they're written.
Answer: That's one of my favourite study books. (Especially Idea #23, because to play it your metronome has to tick on 2 and 4)
Anyway, in Idea #11, the chords written above the stave show you the chord you're outlining with the arpeggio figure. So in the first bar, the chord says Cm7 and the notes below are C Eb G Eb.
But remember the trumpet is a transposing instrument. The accompaniment track is playing chords a tone lower than those named in the trumpet part. The accompaniment part starts with these concert pitch chords:
Bbm7 / Eb7 / | Abmaj7 / / / | Am7 / D7 / | Gmaj7 / / / | etc.
Comment: Ok, that's it.  I can't believe I was that stupid.  I swear I had tried Ab on the piano and it still sounded horrible.  But today it sounds perfect.  So  evidently I was doing something wrong the other day.


Test to determine whether coin is fair or not

Question: A coin is tossed 10 times. How can we determine whether it is fair or not?
My approach:
This seems to be like a Binomial experiment.
I know that for a fair coin, the fraction of heads should be 0.5.

Null Hypothesis: fraction of Head is 0.5
Alternative Hypothesis: fraction of Head is not 0.5

But how do you calculate any statistic ?
The mean, I guess, is $n \times p$. The std. dev. is $\sqrt{(np(1-p))}$.
If some knows the answer please tell me. Also please let me know if my approach is right or wrong.
Comment: The null hypothesis is formulated in terms of the unknown parameter, not the data. In this case the unknown parameter is p.
Comment: @BruceET, can we use normal approximation here ? Just asking because I read somewhere that if sample size is less than 30 then use T-test instead of Z-test. Also here tossing a coin 10 times and counting heads is the event does that mean sample size is 1 ?
Comment: Read this : https://translate.google.com/translate?sl=fr&tl=en&u=https://fr.wikipedia.org/wiki/Test_Z%23Exemple_:_test_sur_la_proportion_d%27une_loi_binomiale
Comment: You have the correct null and alternative hypotheses. Also a hint of a start towards doing an approximate normal version of this binomial test.
Answer: Another way to extract probabilities is to simulate :
Imagine a fair coin.
Toss it 10 times and write down the number of heads.
According to the central limit theorem, the number of heads in 10 tosses will follow a Normal-like distribution with mean
Then do it all over again. And again. And again. N times (maybe N = 1000000 times)
Then calculate the 2.5th and 97.5th percentiles of the distribution of the N simulated number of heads.
Now you toss your real coin ten times and write the number of heads.
If you got less heads than the 2.5th percentile, or more heads than the 97.5th, then you decide that the coin is not fair.
Don't forget that this time when you tossed your real coin 10 times and rejected the hypothesis of the fair coin, could be among the 5% of identical experiments where the result would have been extreme enough to get rejected despite the coin being fair.
Answer: Ten tosses of a coin. Test $H_0: p = 1/2$ against $H_0: p \ne 1/2.$  Comment at the start: there is not a lot of information in only ten tosses of a coin, so in order to reject $H_0$ we will have to observe very few heads (0 or 1) or very many (9 or 10).
Normal approximation: Under $H_0,$ Number $X$ of heads see in $n = 10$ independent tosses has $X \sim\mathsf{Binom}(n=10,p=1/2,$ which
has $\mu = E(X) = np = 5,$ and $\sigma = \sqrt{np(1-p)} = \sqrt{2.5} = 1.581139.$ Then $Z = \frac{X=\mu}{\sigma} \stackrel{aprx}{\sim}
\mathsf{Norm}(0,1).$ So we reject $H_0$ at about the 5% level by
rejecting for $|Z| \ge 1.96.$
Example: Suppose you observe $x = 3$ heads in $n = 10$ tosses.
then $|Z|=|\frac{3-5}{1.5811}| = |-1.265| < 1.96,$ so you do not
have sufficient evidence to reject $H_0$ at the 5% level of significance.
Exact binomial test. This two-sided test rejects $H_0$ when
$X$ is sufficiently far from the expected value $\mu=5$ under $H_0.$
For observed value $x,$ the P-value is $P(X \le x)+P(X \ge n-x).$
Example: Same as above: $x = 3.$
We seek $P(X \le 3) + P(X \ge 7) = 0.3438 > 0.05 = 5\%,$ so we do
not reject $H_0$ at the 5% level of significance.
sum(dbinom(c(0:3, 7:10), 10, .5))
[1] 0.34375

This exact binomial test is implemented in R as 'binom.test', which gives the same P-value $0.3438$ that we obtained from the binomial distribution above.
binom.test(x=3, n=10, p=.5)

     Exact binomial test

data:  3 and 10
number of successes = 3, number of trials = 10, p-value = 0.3438
alternative hypothesis:
  true probability of success is not equal to 0.5
95 percent confidence interval:
 0.06673951 0.65245285
sample estimates:
probability of success
                   0.3

Notes: (a) Back to the comment at the beginning. For the exact
binomial test the rejection region for $H_0: p=.5$ against
$H_a: p \ne .5$ is to observe $0,1,9,$ or $10$ Heads, so
this is really a test at about the 2% level. (Including $2$ and $8$ in the rejection region would make it a test at about the 11% level. Because of the discreteness of binomial distributions a straightforward test at the 5% level is not
possible.
sum(dbinom(c(0,1,9,10), 10, .5))
[1] 0.02148437
sum(dbinom(c(0,1,2,8,9,10), 10, .5))
[1] 0.109375

Thus the power to detect as biased a coin with P(H) = 0.3
is only about 15%.
sum(dbinom(c(0,1,9,10), 10, .3))
[1] 0.149452

(b) There are two difficulties with an approximate normal test in this situation. (i) $n = 10$ is not quite large enough
to guarantee a good approximation to binomial probabilities.
(ii) The approximate test may make it appear that a test at the 5% level is possible, but with $n=10, p=0.5$ values of $|Z|$ near
1.96 are not possible, so the actual significance level
is closer to 2% than 5%.
Comment: I understood the Normal approximation way of solving. But I have read that if the sample size is smaller than 30 we should use T-test. In this case what is sample size ? Is it 10 or since the event itself is tossing coin ten times so that makes sample size as 1 ?
Comment: $n = 10$ is at very lower edge of sample sizes that might work with normal approximation. One common rule is that you can use normal approx if $np$ and $n(1-p)$ are both at least five. So for $p=.5$ you just barely meet the criterion. // IMHO, you should always be wary about $n=30$ quoted as sample size limit. Often bogus. // I used normal approx in 1st part of my Answ because I guessed that might be what's expected of you. I used exact binomial in 2nd part because I try to use exact binomial methods when I can. // Most important for you now: understand basics of CIs and hypothesis testing.
Comment: I have hard time understanding what Binomial distribution for this question exactly is ? Is it frequency distribution of hugh collection of  no. of heads in 10 tosses of coin ? If it is this then according to the question sample size is 1, right because in question the coin is tossed 10 times. For sample size to reach 30 to use Normal approximation the experiment of tossing coins 10 times and counting head should be repeated 30 times and then and average number of heads in those 30 repetition is lets say 3 then we do the z test and find out whether we can reject null hypothesis or not ?
Comment: If you can help me in this please help me. I am not from statistics background.
Comment: "Not having a statistics background' is not a permanent condition. // If you toss a coin $n = 10$ times and you assume (as in $H_0,)$ that $p = 1/2,$ then the number $X$ of Heads has distribution $\mathsf{Binom}(n-10, p=1/2)$ with PDF $f(x) = {10 \choose x}(1/2)^x(1/2)^{10-x}$ $= {10\choose x}/2^{10},$ for $x = 0, 1, 2, \dots, 10.$ This distribution is approximately $\mathsf{Norm}(\mu = np = 5, \sigma=\sqrt{np(1-p)} = \sqrt{5/2}).$ // For general $p$ in $(0,1)$ you have $X\sim\mathsf{Binom}(n-10, p)$ with PDF $f(x) = {n\choose x}p^x(1-p)^{n-x},$ for $x = 0, 1, 2, \dots, 10.$
Answer: The formula to calculate the approximate confidence limits for a binomial test is:
$z_{alpha/2}*\sqrt{p*q/n}$
In your case for a fair coin p = q = 0.5 and using $z_{alpha/2}=1.96$ for a 95% confidence limit.
The range of heads for 10 flips is expected to be between
$ 10*(0.5 \pm 1.96*\sqrt{0.025})$ or 1.9 to 8.1 heads
with a 95% confidence level.
Or to rearrange to calculate the test statistic:
$test statistic = \frac{(observed - n*p_{expected})}{\sqrt{n*p*q}}$
In R use binom.test(5, 10, p=0.5)
Answer: The Red Bead experiment and Deming is where I start.
An unfair coin is a special or assignable cause of variation. When should we look for a special cause? When we see something beyond 3 standard deviations.
10 flips might not be enough.
.5 +/- 3 times sqrt of (.5*.5/N), where N is number of flips.
More than ~ 9.743 H or Ts might be worth looking at. But can you have .7 of a head? No. So you should round 9.7 to 10, in which case probably not meaningful to investigate if 10 flips in a row is all you have.
But a better approach might be to assume the coin is unfair and follow Von Neumann who described a procedure like this:

Toss the coin twice.
If the outcome of both coins is the same (HH or TT), start over and disregard the current toss.
If the outcome of both coins is different (HT or TH), take the first coin as the result and forget the second.


How to block PROPFIND (or any other method) on Apache

Question: How can I block PROPFIND (or other methods, such as PUT or DELETE) on my whole site with Apache?
Answer: Use the Limit or LimitExcept directive. One example might be:
<Location />
<LimitExcept GET POST HEAD>
Order Allow,Deny
Deny from all
Satisfy all
</LimitExcept>
</Location>

Answer: Simpler. Limit just one method instead of trying your shot in the dark about what methods are really needed to except.
<Limit PROPFIND>
Order Deny,Allow
Deny from all
</Limit>


Service not firing event when installed on another machine

Question: I have created one windows service using C#.
All is working fine. I have tested it on my machine. I have used Timer that fired after every one minute. all are working fine on my machine
 but when I have installed it on another two machines to test its not working. its not firing event after 1 minute.
What could be issue ?
Comment: Well, what kind of timer? I think it's uneasy that the problem is in the timer itself (if the service is running without errors). The problem **may be** in the code you execute when the even is fired. Log log log...
Answer: Try running it on the machine that's failing with a higher privilege: Log on as Local System Account.  That should allow you to test whether this is a permissions issue.  If you're setting up logging at the start of your service's launch, you may be failing out because of lack of access to the event logs you expect to write to.
Related to https://stackoverflow.com/a/510225
Comment: its resolved now. I have checked in log and it was Dll not registered issue on other machine.....


Colocar texto lado a lado

Question: Não sei se é possível, mas eu gostaria de saber se eu consigo por um texto dividido em duas colunas?
Answer: Sim, é possível. Basta definires a propriedade column-count no CSS com o número de colunas que queres dividir o texto:

.newspaper {
    -webkit-column-count: 2; /* Chrome, Safari, Opera */
    -moz-column-count: 2; /* Firefox */
    column-count: 2;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius.

Fonte: w3schools
Comment: Obrigado era isto mesmo que eu queria. :D

Colocar texto lado a lado


Number of failures until first r^th success - Expectation, Variance, Probability

Question: I was given the following problem:
Given:
For the r.v $\displaystyle F=number\ of\ failures\ before\ first\ success$.
$\displaystyle E[ F] \ =\ \frac{1-p}{p}$ and $\displaystyle Var[ F] \ =\ \frac{1-p}{p^{2}}$.
Let's now define $\displaystyle X=number\ of\ failure\ before\ r^{th} \ success$, calculate the $\displaystyle E[ X] ,\ Var[ X]$.
My solution was:
Let's notice that if $\displaystyle X=the\ number\ of\ failures\ till\ r^{th} \ success$, then we can define it using the previous question. We have $\displaystyle r$ successes, each success has an $\displaystyle i$ number of falilures before it, for $\displaystyle 0\leqslant i\leqslant k$.
So we can define:
$\displaystyle X\ =F_{1} +F_{2} +F_{3} +...+F_{r}$.
Where each $\displaystyle F_{i} =the\ number\ of\ failures\ after\ the\ ( i-1)^{th} \ success\ and\ before\ the\ i^{th} \ success$.
For example:
$\displaystyle F_{1}$ will be the number of failures before the $\displaystyle 1^{st}$ success.
$\displaystyle F_{2}$ will be the number of failure between the $\displaystyle 1^{st}$ and $\displaystyle 2^{nd}$ success.
$\displaystyle F_{3}$ will be the number of failure between the $\displaystyle 2^{nd}$ and $\displaystyle 3^{rd}$ success.
etc.
Note that each $\displaystyle F_{i}$ is simply the number of failures before some first success, meaning, it is exactly the random variable $\displaystyle F$ we were given.
Expectation:
$\displaystyle E[ X] =E[ F_{1} +F_{2} +F_{3} +...+F_{r}] =E[ F_{1}] +[ F_{2}] +[ F_{3}] +...+[ F_{r}] =r\cdotp \frac{1-p}{p} .$
Variance:
As per the $\displaystyle Var[ X]$, I'm having some trouble calculating it.
I can't use linearity with Variance, and I fail to understand wether I can simply say that:
$\displaystyle Var[ X] \ =\ Var[ rF] =r^{2} Var[ F]$.
Or, I should prove that each $\displaystyle F_{1} +F_{2} +F_{3} +...+F_{r}$ is indepentent, and so deduct that:
$\displaystyle Var[ X] \ =rVar[ F]$.
Which one of the two is correct? And how would I prove that the $\displaystyle F_{i}$ are independet?
Answer: The $(F_k)$ are a sequence of identically distributed random variables, but they not identical.  Thus $\mathsf{Var}(\sum_{k=1}^r F_k)$ does not equal $\mathsf {Var}(k F)$.
So, once you have successfully argued that they are also independent, then you may use:$$\begin{align}\mathsf{Var}(\sum_{k=1}^n F_k)&=\sum_{k=1}^n \mathsf{Var}(F_k)\\[1ex]&=n\,\mathsf{Var}(F)\end{align}$$

And how would I prove that the Fi are independent?

Independently from the count for failures and successes that have preceded any success, the trials after that will still form a sequence of independent Bernoulli random variables with the identical success rate.
Answer: You are correct. This is the negative binomial distribution and if you think a bit, you'll realise that any failure will be independent of the previous succeses that have occurred so the variance would be the $r\frac{1-p}{p^2}$


How to run php file

Question: I have added this to path:C:\xampp\php. separate by semi colon, & when I put this address (localhost/myfiles/hello.php) on the browser the file was opened properly, so, why cant it be opened in cmd?& I always get this message:Windows cant open this file.
Comment: You need to go into the php directory using `cd` through cmd to get to it and use DjDarkViper's answer.
Comment: Not necessarily, because he did mention he added the path to the PHP executable to his `PATH` global environment variable. This allows him to run any executable in that directory, from anywhere on the system (in this case, php.exe, which Windows CMD automatically adds the `.exe` aspect, allowing you to just say `php`)
Comment: @DJDarkViper good point, didn't see that there
Comment: The same reason why `c:\progra~1` doesn't work, but `cd c:\progra~1` works
Answer: command is looking for an absolute path to the file, not an address
$ php ../path/to/myfiles/hello.php
edit
Upon re-reating your question, I could also assume your forgetting to add the php command to the command. Adding the path to PHP in XAMPP allows you to execute the php executable through the command line interface.  So you run php and then the switch configs and then the filepath.
Comment: OK, I put this command you gave & get this:couldnt open this file.
Comment: if you type `php -v` what do you see?
Comment: PHP 5.5.11 (cli) (built: Apr 8 2014 15:07:14)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
Comment: Now I sucseeded opening files by writing this syntax:php C:\xampp\htdocs\myfiles\jim.php  my syntax was wrong, Thank you
Comment: And yes I was forgetting to add php command to the command. Thank you
Comment: Glad everything got resolved :) Mind check-marking my answer for me? :)

How to run php file


An AppBar application not working correctly in Windows 8.x/10 (desktop working area does not get reduced for multiple appbars)

Question: I have an application that functions as an "Application Desktop Toolbar", or appbar for short. It is implemented in WPF, and appbar functionality is added by following this guideline: https://msdn.microsoft.com/en-us/library/windows/desktop/cc144177(v=vs.85).aspx.
Everything works fine in Windows 7, but in Windows 8.1 (or likely in Windows 8.x) the following happens:

The first appbar docked on a display's side is displayed correctly, and Windows desktop's working area is reduced accordingly, so that the appbar does not overlap any windows.
The second appbar docked on the same side of the display as the first one is displayed in the right position, but Windows desktop's working area is not reduced. So the second appbar is now overlapping other windows.
The third appbar docked on the same side of the display acts identically with the second one
The fourth (and all appbars after it) get placed over/under the previous three, so effectively appbars start to disappear

What happens in step 2 codewise is this (debugged in Windows 8.1):
Calling
SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);
returns the correctly adjusted coordinates for the new appbar. But then calling
SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);
does not seem to "go through", meaning that it executes ok, and later the window will be set in the correct position (defined in barData). But the working area is not reduced, which should to my understanding happen by this function call.
What happens in step 4 is, that SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData) starts to return incorrect coordinates, such that are the same as already existing appbars. The result being that appbars get overlapped with each other.
The same problem occurs in Windows 10, but seems that with more serious side-effects: my appbar application crashes with multiple appbar instances quite quickly, putting the whole Windows OS to a halt for a few minutes.
I have searched the web quite extensively, but have not found a solution. Did find this article though https://github.com/PhilipRieck/WpfAppBar/issues/4 where the symptoms experienced are quite similar to the ones with my app.
Any help would be greatly appreciated. My guess is that this is a bug with the SHAppBarMessage API in Windows 8.x/10. But won't stop looking until it is confirmed to be so, or even better, a fix is found.
Comment: Hi Jone, Any luck on this issue? I am also facing the same. We have WPF AppBar application which works fine in Win 7 and got issues in Win 10 surface machines.
Answer: In windows 8 and windows 10 ABM_QUERYPOS is not always returning the correct position at first call. But, calling ABM_QUERYPOS again, obtains from Windows the correct position. Depending on the number of app bars.
As a sample, this code obtains the correct position:
<code>        APPBARDATA abd = new APPBARDATA();
        abd.cbSize = Marshal.SizeOf(abd);
        abd.hWnd = this.Handle;
        abd.uEdge = (int)ABEdge.ABE_TOP;
        abd.rc.left = 0;
        abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
        abd.rc.top = 0;
        abd.rc.bottom = Size.Height;

        // Query the system for an approved size and position.
        int top = abd.rc.top;
        for (;;)
        {
            SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);
            if (top == abd.rc.top)
                break;
            top = abd.rc.top;
            abd.rc.bottom = abd.rc.top + Size.Height;
        }
</code>
Desktop area is not always correctly modified in Windows 8 or Windows 10 as it is in Windows 7.
For the moment, the desktop area can be adjusted with the next code. In windows 10 avoid using
SPIF_SENDWININICHANGE, is not working.
<code>    private const Int32 SPIF_change = SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE;

        MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top,
            abd.rc.right - abd.rc.left, abd.rc.bottom - abd.rc.top, true);

            RECT final_working_area = new RECT();
            result = SystemParametersInfo(SPI_GETWORKAREA,
                                                  0,
                                                  ref final_working_area,
                                                  SPIF_change);
            // Verify working area was adjusted
            if (final_working_area.top < abd.rc.bottom)
            {
                final_working_area.top = abd.rc.bottom;
                result = SystemParametersInfo(SPI_SETWORKAREA,
                                                      0,
                                                      ref final_working_area,
                                                      SPIF_change);
            }
</code>
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/12880536)
Comment: Thank you, I am trying to help, and provide a hint, I hope an expert with enough reputation provide the final solution.I also think there are some bugs related to ABM_QUERYPOS, and to SPI_SETWORKAREA.
Comment: @pslzr : Thank you for your hints. True, calling ABM_QUERYPOS a few times will indeed end up Windows finally giving the correct position. But the biggest problem is with the working area that is not accommodating.

It would be a daunting task to try to handle the working area by explicitly setting it in code, as there may be any number of appbars docked on any side of the display. I think it would be impossible to manage it robustly.

The more hours I have put into this, I am almost certain this is a Windows bug. I really hope for a fix, as this is a huge problem for my app usage.


Perl accessing and printing data from a html folder in a parent folder

Question: so I have a Folder called DATA, and it includes the following: part1.html, part2.html, part3.html, HTML.htm,  plain.html, and jojo.jsp.
Now i use the following commmand to open the DATA folder and extract the files containing .htm
opendir(DIR,'DATA');
my(@dir) = grep /\.htm/, readdir (DIR);
closedir(DIR);

It successfully prints out the name of the files containing the extensions .html . Now i wish to use the html file that are filtered and print the data out into the cygwin terminal. I tried to use the files and stored it to a variable, and use a foreach loop to open the first html file using Filehandler and printing out the data init. The loop will repeat itself and do the same for all the other html files. But i seemed to run into the error! Please help!
my $value = join(@dir);
print "$value\n";

foreach(@dir){
my $movies =  my $value;
open (FHD,  $movies) || die " could not open $movies\n";
my @movies = <FHD>;

my $value2 = join(', ', @movies);
print "$value2\n";

Answer: What's with this line?
my $movies =  my $value;

You're making this a lot harder than it needs to be.
Just use glob to read the directory as that will automatically include the path information on your found files.
use strict;
use warnings;
use autodie;

for my $html (glob('DATA/*.htm*')) {
    print "File: $html\n";

    open my $fh, '<', $html;
    print <$fh>;
}


What is this "trick" for finding posterior distributions?

Question: I am new to Bayesian statistics. I am trying to understand a certain passage in my course notes.
Excerpt:

Discussion:
I don't understand much about the above excerpt. I think that the goal here is to compute something along the lines of $\pi(\theta | x) = \frac{f(x | \theta) \pi(\theta)}{f(x)}$, where $f(x) = \int f(x | \theta) \pi(\theta)d\theta$. We are trying to turn our model for the data and the parameter into a posterior distribution for the parameter given the data.
I do not see what the trick is. What I see is that, for example, if $\theta | x \sim \text{Beta} (\alpha, \beta)$, then $\pi (\theta | x) = \frac{\theta^{\alpha - 1}(1 - \theta)^{\beta - 1}}{\text{B}(\alpha, \beta)}$, where the denominator is a constant (I think) so it follows that $\pi(\theta|x) \propto \theta^{\alpha - 1}(1 - \theta)^{\beta - 1}$.
I believe the same procedure works for the other two examples, in which you set up the equation for the known form of the density, strip out the constants, replace $=$ with $\propto$, and Bob's your uncle.
Or maybe the point is that if $\pi(\theta | x) = \frac{f(x | \theta) \pi(\theta)}{f(x)}$ where the denominator is a nasty integral, then it's simpler to write $\pi(\theta | x) \propto f(x | \theta) \pi(\theta)$. So maybe the upshot is that we perform the multiplication $f(x | \theta) \pi(\theta)$, see if it similar to a known distribution, and this gives us information about the type of distribution the posterior has.
I think the subsequent example in the notes seems consistent with my expectations. (Sorry, these notes seem sloppily written.)

I appreciate any help.
Comment: When prior and likelihood are 'conjugate' (mathematically compatible), one can notice the kernel (density without norming constant) of the posterior by looking at the product of prior and likelihood. In such cases, it is not necessary to evaluate the integral in the denominator of the posterior. // Your beta=binomial is a simple example of that.
Comment: @BruceET Thanks for the comment. That seems a lot simpler to understand than what my notes were trying to explain.
Answer: This is a "trick" that applies more broadly than Bayesian statistics.  It occurs whenever you know that a probability density function is proportionate to some known functional form.  For example, suppose you have some non-negative function $g$ and you have a density function given by:
$$p(\theta|x) \propto g(\theta).$$
In this case, the norming axiom of probability means that there is only one possible solution for the density function --- it is the density that is proportionate to stipulated function and integrates to one:
$$p(\theta|x) = \frac{g(\theta)}{\int g(\theta) d\theta}.$$
Because there is a unique density function that is proportionate to any non-negative function $g$, this means that you can find densities just by "recognising" their proportionate forms (i.e., what they look like without their constant of integration).  Here are a few of the continuous distributions:
$$\begin{matrix}
\text{Normal density}
& \text{N}(\theta|\mu, \sigma^2) \propto \exp \Big( -\frac{1}{2} (\frac{\theta - \mu}{\sigma})^2 \Big)
& \text{ for } \theta \in \mathbb{R}, \\[6pt]
\text{Student T density}
& \quad \text{St}(\theta|\nu) \propto \Big( 1 + \frac{\theta^2}{\nu} \Big)^{-(\nu-1)/2} \
& \text{ for } \theta \in \mathbb{R}, \\[12pt]
\text{Gamma density}
& \text{Ga}(\theta|\alpha, \lambda) \propto \theta^{\alpha-1} \exp (- \theta/\lambda) \quad
& \text{ for } \theta \geqslant 0, \\[16pt]
\text{Weibull density}
& \quad \text{Wei}(\theta|\alpha, \beta) \propto \theta^{k-1} \exp (- (\theta/\lambda)^k) \quad \ \
& \text{ for } \theta \geqslant 0, \\[16pt]
\text{Beta density}
& \quad \text{Be}(\theta|\alpha, \beta) \propto \theta^{\alpha-1} (1-\theta)^{\beta-1} \quad \quad \
& \quad \ \ \ \text{ for } 0 \leqslant \theta \leqslant 1. \\[12pt]
\end{matrix}$$
In the context of Bayesian statistics, it is common to use proportionality to simplify the derivation of posterior densities, using the kind of working shown in your question.  In this context we generally ignore constant multiplicative terms and just find what function the posterior is proportionate to.  We then either "recognise" this as a standard distributional form, or if it is not a standard form we determine the constant of proportionality by integrating the function over its full range.  (Sometimes there is no closed-form expression for the constant of integration, in which case we use numerical methods to estimate this constant, or we generate values from the posterior using MCMC methods.)  By ignoring multiplicative constants in our working, and then bringing them back in in the last step, we greatly simplify Bayesian analysis.
Note that the above result is a general probability rule that applies more broadly than Bayesian statistics, but it is particularly helpful in this context because of the standard result that the posterior is proportionate to the product of the likelihood and prior.


Drop rows containing specific value in PySpark dataframe

Question: I have a pyspark dataframe like:
A     B        C
1     NA      9
4     2         5
6     4        2
5     1     NA
I want to delete rows which contain value "NA". In this case first and the last row. How to implement this using Python and Spark?

Update based on comment:
Looking for a solution that removes rows that have the string: NA in any of the many columns.
Comment: Also, NA could also be present in another column, not necessarily in column B so that row should also be dropped.
Comment: Yes, so spark has labeled them as String because of "NA" present there. I want to remove "NA" so that the columns could be labeled as Integer. One way would be to replace "NA" with 0 everywhere. I am not able to implement it with correct syntax.
Comment: You should add a minimum example and what you've tried so far. A simple filter will do the job
Comment: What does NA mean? Does it mean a missing value for you? Or is it like that in your DataFrame? In that case your column B will be a String! Kindly confirm.
Comment: NA is not  a missing value. It's a string keyword. I want to drop all the rows that contain string "NA".
Comment: NA and 2 are different type, is the 2 or 4 a string as well? What is your DF definition pls?
Comment: Can you show your structure. I prototype in Scala and keep on getting Any
Answer: Just use a dataframe filter expression:
l = [('1','NA','9')
    ,('4','2', '5')
    ,('6','4','2')
    ,('5','NA','1')]
df = spark.createDataFrame(l,['A','B','C'])
#The following command requires that the checked columns are strings!
df = df.filter((df.A != 'NA') & (df.B != 'NA') & (df.C != 'NA'))
df.show()

+---+---+---+
|  A|  B|  C|
+---+---+---+
|  4|  2|  5|
|  6|  4|  2|
+---+---+---+

@bluephantom: In the case you have hundreds of columns, just generate a string expression via list comprehension:
#In my example are columns need to be checked
listOfRelevantStringColumns = df.columns
expr = ' and '.join('(%s != "NA")' % col_name for col_name in listOfRelevantStringColumns)
df.filter(expr).show()

Comment: What if hundreds of columns?
Comment: I have updated my post. I think it is the best way to use a string expression for the filter method.
Comment: Agree, for sure.
Comment: What I am thinking is how do we get this to work and stop if the the first encountered match is found? I am looking nto it from Scala side
Comment: You want to stop after the first row based or the first column based match? Maybe it makes sense to open a new question to discuss this.
Comment: I am trying if and will present as a scala answer. Cannot find something like an array search for all cols.
Comment: I posted an intermediate solution as an alternative.
Answer: In Scala I did this differently, but got to this using pyspark. Not my favourite answer, but it is because of lesser pyspark knowledge my side. Things seem easier in Scala. Unlike an array there is no global match against all columns that can stop as soon as one found. Dynamic in terms of number of columns.
Assumptions made on data not having ~~ as part of data, could have split to array but decided not to do here. Using None instead of NA.
from pyspark.sql import functions as f

data = [(1,    None,    4,    None),
        (2,    'c',     3,    'd'),
        (None, None,    None, None),
        (3,    None,    None, 'z')]
df = spark.createDataFrame(data, ['k', 'v1', 'v2', 'v3'])

columns = df.columns
columns_Count = len(df.columns)

# colCompare is String
df2 = df.select(df['*'], f.concat_ws('~~', *columns).alias('colCompare') )
df3 = df2.filter(f.size(f.split(f.col("colCompare"), r"~~"))  == columns_Count).drop("colCompare")
df3.show()

returns:
+---+---+---+---+
|  k| v1| v2| v3|
+---+---+---+---+
|  2|  c|  3|  d|
+---+---+---+---+

Answer: In case if you want to remove the row
df = df.filter((df.A != 'NA') | (df.B != 'NA'))

But sometimes we need to replace with mean(in case of numeric column) or most frequent value(in case of categorical). for that you need to add column with same name which replace the original column i-e "A"
from pyspark.sql.functions import mean,col,when,count
df=df.withColumn("A",when(df.A=="NA",mean(df.A)).otherwise(df.A))

Comment: Instead of |  it should be &
Comment: & will be used if both columns have 'NA' values in row, here | is used to filter if there is any of both has 'NA' value


Tuning my ukulele strings

Question: I just got my first ukulele and as I was tuning the strings I noticed it didn't sound right. On my tuner it says e when I play the c string and c when I play the e string. Someone please tell me how to fix this.
Comment: See also https://music.stackexchange.com/questions/3333/having-trouble-tuning-my-ukulele?rq=1 and https://music.stackexchange.com/questions/35958/difficulties-tuning-c-string-on-ukulele?rq=1
Answer: Well, you have to tune them!
Rotating a tuning peg one way tightens the string, raising the pitch. If your E string is playing a C, rotate that tuning peg until your tuner shows E.
If your C string is playing an E, you want to rotate the tuning peg the other way; this loosens the string and lowers the pitch.
Comment: also might be helpful to get a tuner that also plays a reference pitch for each string. there are free apps available that do this.  this will help you determine which octave you will be aiming for, if your ears are good enough for that.
Answer: Actually, I hate to say this, but are you holding it correctly?
If you are a right-handed ukulele player, the C string is going to be the 3rd closest to the ground string (headstock is pointing to left). It's possible that you are holding a right-handed ukulele in a left-handed manner, or vice versa. If so, the G string and A string would also be switched in a similar fashion, and tuning them opposite might not be easy to differentiate.
The standard way for right-handed ukuleles to be played is for the headstock and neck to point to your left, and for left-handed ukuleles, to point to the right. This said, you don't necessarily need to switch if you've reversed the two; the string tensions are very similar, and tuning a C string to an E isn't going to rip apart the instrument or anything. In fact, some left-handed players use right-handed instruments turned upside-down.
If you are holding it correctly (or in whatever way that you desire), then I'll defer to Richard's answer.
Comment: I'm a left-handed player. I just hold mine as you said and read the fingering charts backward :P
Comment: Glad to be of assistance, @CaptainAmerica16.

Tuning my ukulele strings


How to calculate the similarity of two arrays accurately in python

Question: I am involved in a difficulty in the case of classification. I have two arrays, the first is 'Actual', and the second is 'Predicted'. There are 3 class here.
A=np.array([1,1,1, 2,3])
P=np.array([1,1,2,3,3])

the above arrays mean that the third and fourth elements have not been accurately predicted. I am wondering when I calculate the mean accuracy between two arrays by the following code, It shows _ 0.59_:
np.mean(A==P)
>out: 0.59

But, when I calculate the accuracy for each class by the following code, it shows 0.57:
count1=[]
for label in range(1,4):
    count1.append(np.mean([(x == y)  for x, y in zip(A,P) if x==label]))
count1
>out: [0.666666666667,0.0,1.0]
np.mean(count1)
>out:0.54

The difference goes up further when the number of classes goes up.
Comment: You can't compute an overall average by averaging sub-averages.
Answer: This doesn't really have to do with programming, but with calculating averages.
Suppose you have just two classes, and your data is  like this:

Actual: [1, 1, 1, 1, 2]
Predicted: [1, 1, 1, 1, 1]

The accuracy in predicting class 1 is 100% and the accuracy in predicting class 2 is 0%.  The overall accuracy is 80%.  Now suppose your data is like this:

Actual: [1, 2, 2, 2, 2]
Predicted: [1, 1, 1, 1, 1]

The accuracy in predicting class 1 is again 100% and the accuracy in predicting class 2 is again 0%.  But your overall accuracy is now 20%.  Clearly there is no way to derive the overall accuracy just from the accuracy percentages of the two classes.
You cannot compute an overall average accuracy just by knowing the per-class accuracy rates (i.e., percentages).  You need to know how many values were in each class, and weight the overall average accordingly.
You can of course compute the per-class accuracies and report them as separate information, and this may be useful.  In your case since you already know how to compute the overall accuracy, it's not clear why you need to use the per-class method to compute it at all.  Just compute the overall accuracy in the direct way, which already works.
Comment: Thank you for the explanation. So, if I want to report the accuracy per class, the above code that I am doing is correct or nor?
Comment: Meanwhile, finally I will so cross validation. Hence, the point that you mentioned will be solved. I am wondering why the overall accuracy is not the same as the average of each classes.


Iniciar servidor php com livereload com gulp

Question: Iniciei meus estudos com gulp e adorei o livereload, porém consegui somente com arquivos estáticos como nesse link. O meu objetivo é iniciar o gulp, porém no servidor php embutido (localhost -s Localhost:8000) ou no servidor com Xampp ou Lampp, ao invés do servidor node. Vi algumas pessoas comentando uma solução com browsersync e outra com gulp-connect-php mas não consegui implementar ambas.
Caso conheçam alguma solução e que não seja um plugin para o navegador fico agradecido.
Answer: Depois de alguns dias consegui resolver o meu problema usando o gulp-connect-php e browser-sync no gulp. Na documentação oficial mostra exatamente um exemplo como é feito. Vejam como ficou o meu arquivo gulpfile.js:
<code>var gulp        = require('gulp');
var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var connectPHP  = require('gulp-connect-php');

var paths = {
      php:['*.php'],
      css:['*.css']
    };

gulp.task('php', function(){
    gulp.src(paths.php)
    .pipe(reload({stream:true}));
});

gulp.task('watcher',function(){
    gulp.watch(paths.css).on('change', function () {
      browserSync.reload();
    });
    gulp.watch(paths.php).on('change', function () {
      browserSync.reload();
    });
});

gulp.task('php', function() {
  connectPHP.server({}, function (){
    browserSync({
      proxy: 'localhost:8000'
    });
  });
});

gulp.task('default', ['php', 'watcher']);
</code>
Pra quem tiver problema na implantação criei um repositório no Github como exemplo para quem tiver dificuldade.


Remover virgula fora dos colchetes - Regex

Question: Estou tentando remover a virgula que está localizada fora dos colchetes do seguinte trecho:
2||Azul||Cor||["#1983ff", "#1983ff"],3||Amarelo||Cor||["#fff73d"]

Preciso que o retorno, esteja dessa forma:
2||Azul||Cor||["#1983ff", "#1983ff"]3||Amarelo||Cor||["#fff73d"]

Algum ninja em regex pode me dar uma mão nisso? (O trecho acima não possui variação, sempre vira dessa maneira) Obrigado.
Comment: Você quer uma Expressão regular que selecione tudo menos a vírgula fora dos colchetes, ou selecione a vírgula fora dos colchetes e elimine a mesma?
Comment: @R.Santos Que selecione a vírgula fora dos colchetes e elimine-a.
Comment: E o padrão de pesquisa sempre será o do exemplo?
Comment: Sim, será o mesmo.
Comment: Você vai conseguir respostas mais corretas se nos disser o que no trecho que você postou varia. Quem sabe mais alguns exemplos?
Comment: Editei a pergunta, na verdade não tem muito o que acrescentar. Basicamente seria isso.
Answer: Partindo o princípio que seu retorno terá esse formato, você pode simplemente:
var retorno =  string.replace("],","]");

Comment: Boa, agora ficou resolvido `+1`. `.split('],').join('')` também daria.
Answer: Uma maneira mais simples de remover a vírgula, ignorando a regra dos colchetes na sentença, utilizando expressão regular, conforme abaixo, ele substitui: (vírgula + número) / primeira casa,
pelo (número) / segunda casa:
var string = '2||Azul||Cor||["#1983ff", "#1983ff"],3||Amarelo||Cor||["#fff73d"]';

var rtn = string.replace(/(,)([0-9]+)/gi,'$2');

console.log(rtn);


unable to setup swagger UI in WEB API .net framework project

Question: i have SwaggerConfig Setup like this
<code>public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "My.API");
                })
            .EnableSwaggerUi(c =>
                {
                });
    }
}
</code>
and WebApiConfig setup like this
<code>    public static class WebApiConfig
{
    /// <summary>
    /// Register Method for Configuration Settings.
    /// </summary>
    /// <returns>Returns a HttpConfiguration which is a complex object which represents a configuration of HttpServer.
    /// </returns>
    public static HttpConfiguration Register()
    {
        var config = new HttpConfiguration();

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.MessageHandlers.Add(new CancelledTaskBugWorkaroundMessageHandler());

        // SetupOData(config);

        // require authentication for all controllers
        config.Filters.Add(new AuthorizeAttribute());
        config.Filters.Add(new HostAuthenticationAttribute("Bearer"));

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "GetPagedData",
            routeTemplate: "{controller}/{pageNumber}/{pageSize}"
        );

        // Web API configuration and services
        config.EnableCors();

        // pulling out the XML for now -teg
        config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
            Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
            new MediaTypeHeaderValue("application/json-patch+json"));
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
            new MediaTypeHeaderValue("text/html"));

        var logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .CreateLogger();

        config.Services.Add(typeof(IExceptionLogger), new MedefisExceptionLogger(logger));
        config.Filters.Add(new CommonExceptionFilterAttribute());

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Services.Replace(typeof(IDocumentationProvider),
             new XmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/Medefis.API.XML")));
        return config;
    }
}
</code>
in the Startup.cs i am calling SwaggerConfig.Register() and few lines later i am also calling WebApiConfig.Register()
<code> public class Startup
{
    /// <summary>
    /// Configuration for IAppBuilder on MedefisAPIUri
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        SwaggerConfig.Register();
        var logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .CreateLogger();

        logger.Information("Api Startup");

        AutoMapperConfiguration.Configure();
        //CreateFoldersOnFileSystem();

        app.UseCors(CorsOptions.AllowAll);
        JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
        AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityServer3.Core.Constants.ClaimTypes.Subject;

        if (ConfigurationManager.AppSettings["UseIdentityServer"] == "True")
        {
            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = MedefisConstants.MedefisSTSConfig,
                    RequiredScopes = new[] { MedefisConstants.Scopes.api },
                    ClientId = MedefisConstants.Scopes.api,
                    ClientSecret = MedefisConstants.Secrets.InternalAPIClientSecret
                }
            );
        }

        // https://stackoverflow.com/questions/15637491/how-to-inject-httpcontextbase-using-autofac-in-asp-net-mvc-4
        builder.Register(c => new HttpContextWrapper(HttpContext.Current)).As<HttpContextBase>().InstancePerRequest();
        builder.RegisterType<ContactEmailRepository>().As<IContactEmailRepository>().InstancePerRequest();
        builder.RegisterType<EmailMedefisUsersHelper>().As<IEmailMedefisUsersHelper>().InstancePerRequest();
        builder.RegisterType<AgencyBiddingProfileService>().As<IAgencyBiddingProfileService>().InstancePerRequest();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<UploadDocumentHelper>().As<IUploadDocumentHelper>().InstancePerRequest();

        builder.RegisterModule(new ValidationModule());

        //Service
        //builder.RegisterType<..... // su registerations goes here

        //Setup
        var config = WebApiConfig.Register();
        builder.RegisterWebApiFilterProvider(config);
        builder.RegisterInstance(config).As<HttpConfiguration>().SingleInstance().PropertiesAutowired();

        var container = builder.Build();
        config.EnableDependencyInjection();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.Use(typeof(WebApiAuthUserMiddleware));
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });

        config.EnsureInitialized();
    }
}
</code>
the problem is that when i call http://localhost:xxxx/swagger it redirects to /swagger/ui/index but i get the error

No type was found that matches the controller named 'swagger'

please not the i am using Swashbuckle.Net45 version 5.2.1
Update
after prefixing the paths with "api/" in routeTemplate: "api/{controller}/{id}""
i was able to load the UI but none of paths and definitions are empty.
Answer: Solution was not to use SwaggerConfig.Register() separately instead do this configuration inside WebApiConfig.


Evento ao atualizar uma tabela

Question: Bom dia pessoal, tenho um datatables que busca alguns dados por ajax, nesta mesma tela eu tenho um botão que eu gosto de deixar desabilitado e somente habilitar quando a tabela terminou de ser carregada, para isto eu utilizo o evento initComplete, vide abaixo:
// dados da tabela principal
$ ("#tabela_sensores_entradas").DataTable
({
        responsive: true,
        paging: false,
        language:
        {
            url: "https://cdn.datatables.net/plug-ins/1.10.20/i18n/Portuguese-Brasil.json"
        },
        ajax:
        {
            url: "../ajax/sensores_entradas.php",
            dataSrc: "sensores_entradas",
            data:
            {
                acao : "buscar"
            }
        },
        columns:
        [
            // 0
            {data: "id_sensor_entrada"},
            // 1
            {data: "descricao"},

        ],
        initComplete: function ()
        {
            // habilita o botão somente quando a tabela está totalmente carregada
            $ ("#botao_novo_sensor_entrada").prop ("disabled", false);
        }

Porém eu me deparei com um problema, quando eu faço uma atualização dos dados, utilizando o ajax.reload (), este initComplete não executa (obviamente), porque a tabela já foi iniciada. Existe algum outro evento que eu poderia adicionar ou substituir para que seja executado sempre que a requisição ajax finalizar?
Obrigado por enquanto pessoal.
Answer: Crie uma função própria para isso. Por exemplo, crie a função:
function habilitaBotao(){
   $("#botao_novo_sensor_entrada").prop("disabled", false);
}

E chame ela no initComplete (sem os ()):
initComplete: habilitaBotao

No callback do Ajax, você chama a função (com os ()). Por exemplo:
success: function(data){
   habilitaBotao();
}

Comment: Adicionei um success ao ajax somente para ver se ele executava, desabilitou o botão corretamente mas os dados não carregaram para a tabela, devo adicionar mais alguma coisa à função?
Comment: Opa, no lugar de initComplete eu encontrei o evento drawCallback, ele faz exatamente o que eu preciso.
Comment: O ajax.reload tem um callback, que você pode chamar a função: `table.ajax.reload(habilitaBotao);`

Evento ao atualizar uma tabela


Como usar o debug no Eclipse?

Question: Estou tendo um problema muito chato com um erro java.lang.NullPointerException e gostaria de saber se com o debug ele mostra qual elemento é null, ao invés de dizer somente em que linha está o erro.
Answer: Primeiro, marque um breakpoint na linha de código que você tem o problema. No seu caso é na linha 34, correto? :)
Para inserir o breakpoint dê dois cliques no lado esquerdo da indicação do número da linha:

Vai ficar uma bolinha azul. Depois, ao invés de clicar na seta branca dentro do círculo verde para rodar o programa, clique no bug (inseto) a sua esquerda.

Seu programa vai rodar normalmente até o momento que a execução atingir uma linha que estiver marcada com um breakpoint. Se for a primeira vez que roda no modo debug, o Eclipse lhe perguntará se deseja mudar a perspectiva para Debug, conforme a tela abaixo.

Clique em Yes. Se preferir marque a caixa de seleção para ele lembrar da sua escolha.
Toda vez que a execução se deparar com um breakpoint, ela será momentaneamente interrompida e você poderá ver o conteúdo das variáveis naquele momento.
Para ver o conteúdo das variáveis você pode pairar o cursor por cima do nome de cada uma delas, ou pode também adicioná-las à janela Expressions para ver o conteúdo de várias variáveis ao mesmo tempo. Para adicionar uma variável a essa janela, selecione a variável e clique com o botão direito do mouse sobre ela, depois clique em watch.

Ela(s) aparecerá(ão) assim:

A partir do momento que a execução do código se deparar com um breakpoint você poderá continuar a execução linha-por-linha, pode entrar ou não em métodos, ou mesmo saindo de métodos, a partir de então. Existem as opções correspondentes na barra de tarefas. Veja abaixo:

Ao clicar no primeiro símbolo, que é a seta verde, você vai passar o comando para seu programa rodar até encontrar outro breakpoint. O quadrado vermelho interrompe por completo a execução do seu código. A primeira seta amarela (cuja tecla de atalho é o F5) vai executar linha por linha do seu código entrando nos métodos quando houver um, inclusive mudando a tela para mostrar a classe correspondente, acredito que essa pode ser uma boa opção para o seu caso. A segunda seta amarela é quando você deseja executar linhar por linhas mas sem entrar em um método quando encontrar um. Já a última seta amarela é a opção de cair fora do método atual.
O console vai te dar mais detalhes quando a exceção ocorrer, fique de olho e bom debug.
Comment: @MarcosGuimarães Certifique-se de que a perspectiva está no modo Debug, depois clique em Window > Show View > Expressions.
Comment: Obrigado! Agora consigo ver os valores das variáveis.
Comment: Muito obrigado mesmo, há muito tempo que estou com esse erro e o debug rapidamente me apontou a variável que estava Null.
Comment: No meu eclipse não tem a aba expression. Oque fazer?

Como usar o debug no Eclipse?