How do I get a list of members in a Python module, or how should I create plugins?

Question: I'm writing a sort of dashboard-esque program in Python to make tasks that I do frequently here at work a little better/easier.
What I currently have set up is an actions module. actions contains an actionlist that is a list of classes. Each of my classes has a .title, .icon (base-64 encoded string for use with tkinter.PhotoImage), and a .action function.
Using tkinter I create a new button for each of these actions, with the appropriate icon, text, and the command of the button set to the .action. So far it works quite nicely, but if I want to create a new action, I have to go into my actions module, create a new class, and then put that class in my actionlist.
What I would like to do is be able to dynamically generate this actionlist based on what files are present in my module. So I would like to have something like this:
actions/
        __init__.py
        someaction.py
        do_another_thing.py
        do_all_the_things.py
        chop_down_the_tree_with_a_herring.py

And whenever I would like to create a new action, I just put a .py script in my actions folder and then it would automagically generate the list of actions for me, however I can't seem to find any good way of creating this list. I've thought of using something like os.listdir to get the list of files, but neither that or the other methods of introspection (dir, and inspect.getmembers) seemed to have quite what I wanted. Of course, it's possible that I just missed the features that I need.
In any case, pointers in the right direction would be great. Thanks!
SOLUTION:
Lennart's solution, with some slight adaptations worked for me.
Inside my __init__.py I have the following code:
plugins = []
__all__ = [
           'do_all_the_things',
           'do_another_thing',
           'someaction',
           'chop_down_the_tree_with_a_herring',
           'seek_the_grail',
          ]

Then inside each of my plugins I have something like this:
from actions import plugins

class SeekTheGrail:
    def __init__(self):
        self.text = 'We Seek The Grail'
        self.icon = b'R0lGODlhkABJAPcAABsVGH6DWWaElDxIdU1LM8mxc2RnQ3iFaLi8mLmQZqxpOy4rPq28y41NNTMvJIujl5qbakpMTdubSWJoV4KhxOfTnkBYoL+EQ26FgF84LtzZyaRoTFdbPLm/sK+hnHF5WbqGUbmgbeLEglxnbyUdJEBALHFMM6ivg4aRasfMybyQUa+gfVleUKGxnXV4S9Wzf6t6Q5NYRDQwL4+df2GEv2FFPM3EsohoSIFpVNKgao+Lgqp6UNrClT89PVJojk9tp4l7Vy0mJickG45eOZ6nhJ6zwUZYd01MQIehsWdwW8zQ3ZWHZVZgXmxNPZ2SaEgxLrxpPr+6iNbY3dKH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eM+uAed+eEnU3IcSfZgEAaAFWpgEGiCGBZbGqwoIADs='
    def action(self):
        print('I am Arthur, King of the Britons!')

plugins.append(SeekTheGrail())

and now I just have to modify the __all__ collection when I want to add or remove the actions from loading.
Answer: The way to create plugins is to have a plugin registry, and register plugins there. This can be done from the amazingly simple, like just defining a global list in a module:
plugins = []

And then registering the plugins with:
class APlugin(object):
    blahblah

from themodule import plugins
plugin.add(APlugin())

This can be made more flexible by having types of plugins and registering them with a name etc. But then you are on the path to complexity, and then you might want to take a look at the Zope Component Architecture, which simply speaking is a very powerful system for making your application pluggable.
It should be noted that in any case it's best to have a list of what plugins should be activated instead of auto-discovering them. This can be as simple as a list in a text file or a setting in a config file. This enables you to easily activate and disactivate the plugins.
Answer: You can use something like this:
actions = {}
for filename in os.listdir('somepath/actions'):
    actions[filename] = __import__('actions.'+filename)
for name,class in actions:
    createButton(name,class)

Where in the createButton you create your tk_inter button and assign it the functions from the class. The important bit i suppose is that you can use __import__ to import a class using its string name and save it as a variable.


Inner Join com Where e múltiplas tabelas

Question: Estou montando uma query, onde preciso fazer join entre duas tabelas (pois o dado estará na principal B mas não na complementar BC) e uma terceira tabela que obrigatoriamente preciso dos dados, que sempre estarão na tabela principal B.
Tentei conforme abaixo, mas retorna erro de sintaxe. Pesquisei aqui mesmo e não encontrei um exemplo, alguma sugestão?
select DATE_FORMAT(b.dt_lancamento, '%d-%m-%Y') as dt_lancamento_F,
                      DATE_FORMAT(b.dt_abertura, '%d-%m-%Y') as dt_abertura_F,
                      DATE_FORMAT(b.dt_finalizacao, '%d-%m-%Y') as dt_finalizacao_F,
                      DATE_FORMAT(b.dt_prim_producao, '%d-%m-%Y') as dt_prim_producao_F,
                      DATE_FORMAT(bc.dt_solicitacao, '%d-%m-%Y') as dt_solicitacao_F,
                      DATE_FORMAT(bc.dt_alergenico_ti, '%d-%m-%Y') as dt_alergenico_ti_F,
                      DATE_FORMAT(bc.dt_auto_avaliacao_ti, '%d-%m-%Y') as dt_auto_avaliacao_ti_F,
                      DATE_FORMAT(bc.dt_cert_halal, '%d-%m-%Y') as dt_cert_halal_F,
                      DATE_FORMAT(bc.dt_cert_kosher, '%d-%m-%Y') as dt_cert_kosher_F,
                      DATE_FORMAT(bc.dt_cert_brc, '%d-%m-%Y') as dt_cert_brc_F,
                      DATE_FORMAT(bc.dt_cert_fssc, '%d-%m-%Y') as dt_cert_fssc_F,
                      DATE_FORMAT(bc.dt_cert_ifs, '%d-%m-%Y') as dt_cert_ifs_F,
                      DATE_FORMAT(bc.dt_controle_pragas, '%d-%m-%Y') as dt_controle_pragas_F,
                      DATE_FORMAT(bc.dt_apro_fornecedor, '%d-%m-%Y') as dt_apro_fornecedor_F
                      u.admin NIVEL, BC.*,B.*
                 FROM USUARIOS U,
                      BRIEFING B
                LEFT JOIN BRIEFING_COMPRAS BC ON bc.cod = b.cod
                WHERE B.responsavel = u.nome_completo
                  AND B.COD = 551

Comment: Qual o erro de sintaxe? Informe qual o erro que ocorre.
Answer: Faltava uma vírgula depois da declaração de um dos campos:
SELECT DATE_FORMAT(b.dt_lancamento, '%d-%m-%Y') as dt_lancamento_F,
       DATE_FORMAT(b.dt_abertura, '%d-%m-%Y') as dt_abertura_F,
       DATE_FORMAT(b.dt_finalizacao, '%d-%m-%Y') as dt_finalizacao_F,
       DATE_FORMAT(b.dt_prim_producao, '%d-%m-%Y') as dt_prim_producao_F,
       DATE_FORMAT(bc.dt_solicitacao, '%d-%m-%Y') as dt_solicitacao_F,
       DATE_FORMAT(bc.dt_alergenico_ti, '%d-%m-%Y') as dt_alergenico_ti_F,
       DATE_FORMAT(bc.dt_auto_avaliacao_ti, '%d-%m-%Y') as dt_auto_avaliacao_ti_F,
       DATE_FORMAT(bc.dt_cert_halal, '%d-%m-%Y') as dt_cert_halal_F,
       DATE_FORMAT(bc.dt_cert_kosher, '%d-%m-%Y') as dt_cert_kosher_F,
       DATE_FORMAT(bc.dt_cert_brc, '%d-%m-%Y') as dt_cert_brc_F,
       DATE_FORMAT(bc.dt_cert_fssc, '%d-%m-%Y') as dt_cert_fssc_F,
       DATE_FORMAT(bc.dt_cert_ifs, '%d-%m-%Y') as dt_cert_ifs_F,
       DATE_FORMAT(bc.dt_controle_pragas, '%d-%m-%Y') as dt_controle_pragas_F,
       DATE_FORMAT(bc.dt_apro_fornecedor, '%d-%m-%Y') as dt_apro_fornecedor_F,
       u.admin NIVEL,
       BC.*,
       B.*
  FROM USUARIOS U
 INNER JOIN BRIEFING B ON B.responsavel = u.nome_completo
  LEFT JOIN BRIEFING_COMPRAS BC ON bc.cod = b.cod
 WHERE B.COD = 551

Comment: Tive que tirar a vírgula depois da tabela Usuarios, ai deu certo. Muito obrigado!


How can I use the SQLServerDriver in IntelliJ when I run/debug a file's main()?

Question: I am able to use the SQLServerDriver when I run my project through maven and can successfully read/write to my db. I'm testing some changes in a specific file and I'm trying to test that individual file by right-clicking the file and running the file.
When it gets to run the setup code it throws an exception (java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver).
The code:
        Connection conn = null;
        Class.forName(dbDriverMsSQL);
        conn = DriverManager.getConnection(dbConnectionString);

with this separately defined:
public static String dbDriverMsSQL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
I'm using the following dependency in my pom.xml:
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>7.4.1.jre8</version>
            <scope>test</scope>
        </dependency>

Is there some additional setting that I have to configure to be able to read/write from my main()?
Comment: Your dependency scope is test - do you use this code in a Test? If not this might cause the error. You can also try Class.forName(SQLServerDriver.class); If IntelliJ can't find the import you have a problem with your depenencies.
Comment: didnt even consider that! I removed the scope and that was it. its working! Thanks for your help!
Answer: Posting @TomStroemer 's comment to mark this resolved:

Your dependency scope is test - do you use this code in a Test? If not this might cause the error. You can also try Class.forName(SQLServerDriver.class); If IntelliJ can't find the import you have a problem with your depenencies.
  I removed the scope and I could run successfully.


"#define" define uma variável global?

Question: Eu sempre utilizei alguns defines, mas agora surgiu essa dúvida, quando utilizo um #define estou criando uma variável global? Há algum prejuízo nessa utilização? Exemplo:
fazer programa para ler 10 números:
Eu coloco #define quantidade 10 e uso quantidade nos parâmetros do for.
Answer: Não, nem perto disso.
#define apenas diz que um texto é o mesmo que outro texto, mais nada além disso. Então em todo lugar que seu código tiver esse primeiro texto depois do processamento inicial é trocado pelo segundo texto.
Não tem nada de variável. Nem mesmo constante é, embora pareça com uma. Portanto não cabe falar em escopo também. Aquele nome não existe de fato para o código que é compilado. A troca é feita em todo o código onde estiver valendo o #define, ou seja, do momento onde ele é encontrado no código até o fim daquela unidade de compilação.
Na forma como está usando se parece com uma constante, então você tem um nome que é mudado para um valor, literal, o valor só existe ali naquele local, novamente não tem nada de escopo.
Para código mais modernos não se recomenda usar praticamente nada do pré-processador, incluindo o #define. Não que deva ser usado nunca, mas é melhor evitar.
Veja:

Quando usar const e quando usar #define?
Variável static e #define

Coloquei no GitHub para referência futura.

"#define" define uma variável global?


How to set up mailboxes or mail forwarding for IIS SMTP?

Question: I've got a Windows 2008 R2 Server with IIS7, and the A record of my domain (mydomain.com) is pointing to my server.
Now, my users don't need their own mailboxes set up; they just need email forwarding so that email@example.com will forward to email@example.com, for example.  But for the life of me, I have no idea how to set that up!
Firstly, I installed SMTP Server, but couldn't find any SMTP server interface in IIS7.  After googling about that, it seems that you have to do SMTP management through an IIS6 interface!  Is that really true?  I find that difficult to believe - why would Microsoft have made you split your IIS management over 2 versions pf the same product?
Secondly, I've looked high and low for any kind of mailbox management options... couldn't find a thing.  Is it hiding somewhere?  Or do you have to buy or install some additional tools?
Answer: The reason for the split management is because the SMTP service is now part of the Exchange team's responsibilities whereas it used to be under the IIS team at Microsoft.  IIS6 is the only way that I know of to manage the SMTP service.  Here's a bit of info for you (specifically Wendy Henry's post): http://social.msdn.microsoft.com/Forums/en/servervirtualization/thread/af4a8a7c-8d6d-4300-ba7f-e8cd0bcf431f
You will not be able to forward specific e-mail addresses out to another email address with Windows SMTP service.  Furthermore, if you wanted to run POP3 email on your Windows 2008 server, you're out of luck since they removed the native POP3 service capability.  There is also no IMAP.


Make variables created in preprocess_page hook available to content type templates

Question: I'm attempting to render a block plugin programmatically in a content type template. I understand how to render the block programmatically in a page template. like so
mytheme.theme
function mytheme_preprocess_page(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();

page.html.twig

{{ myblock }}

However in
node--contenttype.html.twig

{{ myblock }}

Produces nothing. Is there another hook I should be using? Or is there a better way to do this entirely?
Answer: I was able to accomplish this by placing the code into the preprocess node hook instead of the preprocess page. Like so
mytheme.theme
function mytheme_preprocess_node(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();

Comment: Correct. Variables are not shared between those functions.


Angular Adal how to retrieve the username or email

Question: I have written an angular js app that I am using angular-adal.js to authenticate against Azure AD. I have configured all routes to requireADLogin and also added
extraQueryParameter: 'nux=1,scope=openid'

in the init method.
My question is where can I pull the logged in username or email etc from to store against the records they are creating after they've logged in. Because I am not manually authenticating in code I don't have a token object or anything to play with. Any pointers would be appreciated as although I've searched all the exmaples seem to be when you are making the calls yourself rather than letting UI Router do the authentication.
I'm sure this must be a common thing to do though!!
Thanks in advance!
Comment: Did you solved the issue ?
Comment: if dalAuthenticationService.userInfo is not giving both username & email, try to use Graph API. But, you need to add Graph API in azure-ad who has access
Answer: After we sign-in the Angular application using ADAl library, it provides userInfo object which we can get the information about the user. And we can get the userName from this object directly.
Here is the code and figure for your reference:
$scope.printUserName = function () {
                    console.log(adalAuthenticationService.userInfo.userName);
                };

The Microsoft also provide a code sample for the Angular application, you can refer it from here.
Comment: Many thanks!! I was looking in that sample project you linked to but couldn't find an example of getting the username when not making the call directly! This is very useful!
Comment: Do you also know a way to do it in Angular 2 with adal-ts?
Comment: I want to get email field. Any idea ?
Comment: @Anas, check this.adalService.userInfo.userName field this.adalService.userInfo.profile.email field. It will be somewhere. If not properly open total console.log(this.adalService.userInfo) and check inside profile.... The total response. If not, we can do Graph API to retrieve. Let me know what happens?But, you need to add Graph API in azure-ad who has access


Remove all previous cart if have same product creator

Question: Thanks a lot joshmiller, but I need this rule on before add product to cart react event, not after save commerce order.
I need when user (buyer) klick second button add to cart (for multi order), system check the product creator id first, if the product creator id for the second order clicked is same with previous (where is actually on cart) system cancel the previous clicked order.
With this scenario I want to limit order only from same product creator for one times order. So if buyer want to continue order from different product creator they have to do after first order completed.
Any suggest how to solve this using rule?
Answer: You simply need to create a rule that reacts on order creation, searches for existing orders for that user, and cancels those orders.

Next, add the condition to make sure you won't pull all anonymous orders. If you allow anonymous orders, you might have to implement some sort of custom session searching for orders.

Next, add an action that brings in a list of entities (we're going to pull a list of orders based on owner).

Then, select Commerce Orders

This is what the full action looks like when you've set it up for selecting by order owner's user id:

Next, you want to add a loop based on the orders you've pulled:

Next, you want to add an action inside that loop that changes the status of the orders:

Finally, set the order status to canceled:

Here's an export of the rule:
<code>{ "rules_cancel_previous_orders" : {
    "LABEL" : "Cancel previous orders",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_order", "entity" ],
    "ON" : { "commerce_order_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:uid" ], "op" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "commerce_order",
            "property" : "uid",
            "value" : [ "commerce-order:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "canceled" } }
          ]
        }
      }
    ]
  }
}
</code>


Why does unqualified name lookup find all overloaded declarations

Question: Here is an example which I'm trying to understand how does unqualified name look up work for overloaded declarations:
int foo(char a){ return 0; }

namespace A
{
    int foo(int a){ return a; }
    int foo(){ return 2; }
    extern int j;
    extern int i;
}

int A::j=foo('a'); //97
int A::i=foo(); //2

It means that int foo(char); does not found by unqualified name look up but int foo(int); and int foo() can be found. So I assume that unqualified name look up for overloaded declaration ends as soon as all overloaded declarations is found for the name. I can't find this into the standard, I can find only the following (sec. 3.4.1):

name look up ends as soon as a declaration is found for the name.

This quote doesn't say anything about overloaded declaration look up.
Comment: "... Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a set
 of overloaded functions (13.1)..." (C++11 §3.4/1)
Answer: You're mixing up name lookup with overload resolution. There is no such thing as "unqualified name look up for overloaded declaration". Name lookup and overload resolution are separate.
Name lookup means determining which scope the name is found in. Once that is completed, overload resolution determines which of the declarations visible in that scope should be used.
In your code, name lookup determines that foo means A::foo. Then overload resolution selects between A::foo() and A::foo(int).  The ::foo is not considered for overload resolution because it is not a definition of A::foo.
Another example:
namespace C { void f(); }
namespace B { void f(); void f(float); }
namespace C { void f(long); }

using namespace C;

int main()
{
    f(1.0);
}

When processing the line f(1.0), name lookup sees void f(); and stops. The result is that f means C::f.
Then overload resolution kicks in, and all declarations of C::f are considered for overload resolution. void f(long) is chosen.
Answer:
In a declaration in which the declarator-id is a qualified-id, names used before the qualified-id being declared
     are looked up in the defining namespace scope; names following the qualified-id are looked up in the scope
        of the member's class or namespace.

(C++11 §3.4.3/3)
So in both of
int A::j=foo('a');
int A::i=foo();

the name foo is looked up in the scope of A just because you have A::j and A::i to the left, in the declarator.
Note that if you do
int k = foo();

only the global foo will be found, and you'll get an error.
Comment: I know what scopes is searched during unqualified lookup. I asked quite another.
Comment: @DmitryFucintv I left a comment on the question. I'm not going to edit this answer because I think the details in the answer will be useful for other people who will see the question.
Answer: You said

It means that int foo(char); does not found by unqualified name look up but int foo(int); and int foo() can be found. So I assume that unqualified name look up for overloaded declaration ends as soon as all overloaded declarations is found for the name.

A similar question was asked in another SO post
There is from 3.4.1/14:

If a variable member of a namespace is defined outside of the scope of its namespace then any name that appears in the definition of the member (after the declarator-id) is looked up as if the definition of the member occurred in its namespace.

Your posted code is equivalent to:
int foo(char a){ return 0; }

namespace A
{
    int foo(int a){ return a; }
    int foo(){ return 2; }
    extern int j;
    extern int i;
}

namespace A
{
  int j=foo('a');
  int i=foo();
}

When the definitions and initializations are put under the namespace, it becomes clear why functions used to initialize the variables are looked up in namespace A first. If an unambiguous match can be found for a function in namespace A, the search for it stops. That means, when compiling the line,
int A::j=foo('a');

The lookup for foo starts in namespace A, is resolved to int A::foo(int); and the search for foo stops.
Hope this clears the confusion.
Answer: In the standard (§3.4/1)

Name lookup shall
  find an unambiguous declaration for the name (see 10.2). Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a set
  of overloaded functions (13.1). Overload resolution (13.3) takes place after name lookup has succeeded.
  The access rules (Clause 11) are considered only once name lookup and function overload resolution (if
  applicable) have succeeded.

Which means the steps are as follows for methods:

First collect all the matching names
Do overload resolution
Check for accessibility

For method, name lookup does not return after finding first match, rather it searches for all matching names. It is clear from the statement Name lookup may associate more than one declaration with a name if it finds the name to be a function name.
Comment: But name lookup ends as soon as a declaration is found for the name.
Comment: In the case of overloading name lookup does not ends if we found declaration for the name. It it continue to find all overloaded declarations.
Comment: You said that the first step is to collect all mathced names. But from the quote `name lookup ends as soon as a declaration is found for the name` implies that only one declaration can be matched for the name. I'm confused...
Comment: @DmitryFucintv, what is your question exactly? `int foo(char);` can not be found because it does not exist, nothing related to scope or name lookup. and your question about overload resolution is answered
Comment: @DmitryFucintv, *name lookup ends as soon as a declaration is found for the name* is a general case, the specific case for method lookup is also clearly described in the standard. *This quote doesn't say anything about overloaded declaration look up* is wrong
Comment: When we're finding `foo`'s declarations in the `namespace A` scope the `int foo()` will be found after the `int foo(int a)` will be found. But when `int foo(int a)` will be found unqualified name lookup must be end because `name lookup ends as soon as a declaration is found for the name`. But unqualified name lookup can found all overloaded declarartions in the current scope.
Comment: _the specific case for method lookup is also clearly described in the standard._ Where is it described? Can you give me a reference?


Proof by induction: summation inductive step

Question: Disclaimer: This question is just a practice question and is not for marks.
I am trying to prove the following statement (I'm skipping right to the inductive step here since the base case is trivial):
$\forall n \in \mathbb{N}, \hspace{3pt} $$\sum_{i=1}^{n} \frac{1}{i(i+1)} = \frac{n}{n+1}$
Inductive Step: Let P(k) be $\forall k \in \mathbb{N}, \hspace{3pt} $$\sum_{i=1}^{k} \frac{1}{i(i+1)} = \frac{k}{k+1}$. We will prove $\forall k \in \mathbb{N}, \hspace{3pt} $$\sum_{i=1}^{k+1} \frac{1}{i(i+1)} = \frac{k+1}{k+2}$ is true.
$\sum_{i=1}^{k+1} \frac{1}{i(i+1)} = \sum_{i=1}^{k} \frac{1}{i(i+1)} + \frac{1}{k(k+1)}$
I'm not sure whether the above step is correct, or how to progress with this proof. Also, is there a cookie cutter proof structure for this type of question? Thanks in advance for the assistance.
Comment: The part with $\frac{1}{k(k+1)}$ is wrong. When you replaced the $i$ in $\frac{1}{i(i+1)}$ with $k+1$, that's not quite what you should get.
Comment: Yes, you have to replace the $i$ with $k + 1$ there. What do you get then?
Comment: Should it be $(k +1)$ instead? Edit: Oh, now I see, my substitution was wrong.
Comment: Thanks for pointing that out. I didn't notice that mistake
Answer: Note that $$\sum_{i=1}^{k+1} \frac{1}{i(i+1)} = \sum_{i=1}^{k} \frac{1}{i(i+1)} + \frac{1}{(k+1)(k+2)}\\=\frac {k}{k+1}+\frac{1}{(k+1)(k+2)}.$$
As an alternative, observe that  $$\sum_{i=1}^{k} \frac{1}{i(i+1)}=\sum_{i=1}^{k}\frac1i-\frac1 {i+1} $$.


URL Rewrite in case of verbs PUT and DELETE with iisnode

Question: This is a follow-up question to my previous one, focused on the fact that I'm getting a 404 error when I try to call a DELETE or a PUT verb for an Node.JS application on IIS configured with iisnode and URL Rewrite as follows:
<handlers>
  <add name="iisnode" verb="*" path="app.js" modules="iisnode" />
</handlers>

<rewrite>
  <rules>
    <rule name="my app rule" stopProcessing="true" patternSyntax="Wildcard">
    <match url="*" />
    <action type="Rewrite" url="app.js" />
  </rule>
  </rules>
</rewrite>

The script app.js is not even called, the url is not rewritten.
Is it a well known bug or what else am I supposed to do?
No issues for GET and PUT verbs instead (and of course I've already implemented a workaround using the latter).
Answer: That was due to the Request Filtering of IIS (tab HTTP Verbs)
Added there the missing verbs as shown in the screenshot below and problem solved.

As text, directly inside the system.webServer of the web.config:
<security>
    <requestFiltering>
        <verbs>
            <add verb="PUT" allowed="true" />
            <add verb="DELETE" allowed="true" />
        </verbs>
    </requestFiltering>
</security>


Item do menu sempre aberto

Question: Tenho um menu lateral que quando o usuário clica altera a cor de um item selecionado no menu atravens de um codigo javascript, contudo quando acontece uma atualização na tela a classe é removida. Alguém teria alguma dica de como deixar com a cor selecionada após atualização da tela?
Queria que tivesse o mesmo comportamento do sbadmim https://blackrockdigital.github.io/startbootstrap-sb-admin-2/pages/index.html

   var selector2 = '.menu-section-list li';

    $(selector2).on('click', function () {
        console.log("s");
         $(selector2).removeClass('active');
        $(this).addClass('active');
    });
Comment: da uma lida aqui:
http://stackoverflow.com/questions/30060155/saving-website-styles-in-cookies
Answer: Note que no sbadmin cada opção do menu carrega uma página diferente que é exibida na url, com isso fica fácil verificar em que estado de tela está apenas verificando a url, que pode ser obtida com window.location.href.
Dito isto vale a pena dizer que o sbadmin utiliza o metisMenu.js e você pode estudar como isto está implementado ou simplesmente usá-lo também.

Item do menu sempre aberto


Lower semicontinuous risk measure

Question: I am looking for some risk measures that hold the lower semi-continuous property.
I am not sure whether Expected Shortfall is a such a measure or not. Can anyone give me some help?
Thanks.
Comment: It would be interesting to find a coherent risk measure which is not lower semi-continuous. To the best of my knowledge, all standard risk measures - coherent or not - are lsc: expected shortfall, mean-upper-semideviation, expectiles, quantiles, etc.
Answer: The literature is replete with relevant examples. The expected shortfall is, indeed, a lower semi-continuous risk measure on $\mathcal{L}_p(\Omega, \mathcal{F}, \mathrm{P})$, $p\in[1,+\infty]$.
Recall that $\operatorname{AV@R}_\alpha[Z]$ is defined as
$$
\operatorname{AV@R}_\alpha[Z] = \inf_{t\in\mathbb{R}}\{t + \mathbb{E}[Z-t]_+ \},
$$
that is, it is the inf-projection of the function
$$
\phi(t)=t + \mathbb{E}[Z-t]_+,
$$
which is proper, convex and lower-semicontinuous. Average value-at-risk (aka expected shortfall) is a coherent risk measure.
There are many such risk measures you can find in: A. Shapiro, D. Dentcheva and A.Ruszczynski, Lectures on stochastic programming: modeling and theory, MPS-SIAM series on optimization, 2009.
Another such risk measure is the very simple mean-variance risk measure
$$
mv[Z] = \mathbb{E}[Z] + c\mathrm{Var}[Z],
$$
which, however, fails to be coherent (it is not positively homogeneous).
Yet another example is the Mean-Upper-Semideviation of order $p$ which is well-defined and finite for $Z\in\mathcal{L}_p(\Omega, \mathcal{F}, \mathrm{P})$. This is defined as
$$
\mathrm{MUS}_p[Z] = \mathbb{E}[Z] + c \left(
\mathbb{E}[Z-\mathbb{E}[Z]]_+^p
\right)^{1/p}.
$$
This risk measure is coherent.
All well-established risk measures I know of are lower-semicontinuous.

Lower semicontinuous risk measure


android studio 2.2 layout editor refresh button

Question: can someone help me find the refresh layout button which was there before studio 2.2 to refresh the layout changes?
Have searched every where but cannot find it.The problem is sometimes drawables are not refreshed and reflected in the preview window.
Comment: there is no refresh button in stable version of android studio 2.2 for preview or for that you need to downgrade to 2.1.2 version.
Answer: It's pretty simple to refresh.
Click on the preview screen, make sure that the preview window has the focus, and press R. It should display the progress in the top-right corner while refreshing.
If it doesn't work for any reason, switch to the design tab and press R. It refreshes the layout instantly.
Comment: I don't get why they remove the Refresh button. The Layout Editor is always buggy.
Comment: Works just fine :) Thanks for the tip
Comment: Be sure to select an element in the *Layout Editor* in case pressing `R`  doesn't refresh the layout.
Answer: I think it is a small bug, but I find a hack solution to resolve the problem.
You can change a resource id to a wrong name. For example, you have a resource named ic_launcher. When you input ic_launcher1, you can find the interface like this:

Next, click the refresh link (sometimes, it says 'clear cache').
I tried changing the orientation, but it does not work when I replace an existing image file.
Comment: Change orientation sometimes do not work. This worked for me, thanks. Why they removed this button? Pointless...
Comment: @Subho I have replace an image and modify some words
Comment: actually this is what i found and have been using
Comment: Worked for me. Cool.
Comment: Nothing worked for me. Sticking with closing the layout file and re-opening it :P
Comment: It's not a solution. It's a workaround. This is the right way of how to refresh layout: https://stackoverflow.com/a/42059284/2557258
Comment: I solve it by building app again. after a build UI back to normal.
Answer: Toggle the Orientation button in Editor, it is refreshing the changes.
Comment: Doesn't update ImageViews if I change images in drawables directories. Android Studio 2.2.3
Answer: Can't seem to find the refresh layout button too, it's as if it is deliberately removed.
However, I found a temporary refresh layout solution: On the screen orientation button, click the dropdown and then change the Night Mode. See this page for reference on where to find the screen orientation button. Hope this helps.
Comment: night mode does nothing for me
Answer: Close edited layout file and reopen.
You can do this with following shortcuts:

Ctrl+F4 (close tab)
Ctrl+Shift+E (open Recently edited files)
Enter
(select recent file to open, your layout file should be already
highlighted if edited last)


Where is the circle of fifths mentioned for the first time?

Question: How and when was the Circle of Fifths invented, and who is responsible for the discovery of this musical godsend?
Answer: I've found this picture:

I've encountered this picture recently here:
https://www.musical-u.com/learn/how-to-use-circle-fifths/
It says:
Russian composer and music theorist Nikolay Diletsky set this whole wheel rolling in the late 1670's. He intended his book Grammatika as a guide to composition, but with the rules of music theory in mind.
Answer: from the Wikipedia article

In the late 1670s a treatise called Grammatika was written by the Ukrainian composer and theorist Mykola Dylets'kiy. Diletskii's Grammatika is a treatise on composition, the first of its kind, which targeted Western-style polyphonic compositions. It taught how to write kontserty, polyphonic a cappella, which were normally based on liturgical texts and were created by putting together musical sections that have contrasting rhythm, meters, melodic material and vocal groupings. Diletskii intended his treatise to be a guide to composition but pertaining to the rules of music theory. Within the Grammatika treatise is where the first circle of fifths appeared and was used for students as a composer's tool.

After further Wikipedia diving I found out that the first mention of the Circle of Fifths in Western musical literature was by Johann David Heinichen 50ish years later in his 1728 treatise Der Generalbass in der Composition.
Comment: Wiki tells actually the same as I've found. Interesting informations about an unknown origin.
Comment: Additionally, although the first known _graphical_ representation is in Heinichen, in [1697](https://books.google.co.uk/books?id=AU7VGFbWg8YC&pg=PA144) Andreas Werckmeister mentions the "Circul der quinten oder quarten" in his _Hypomnemata musica_. The relation between the Germanic school and that of Dylets'kiy / Diletskii is quite interesting history.
Comment: Diletsky actually has the first image of the Circle.
I can't actually find the Circle of Fifths in the Heinichen manuscript and searching for "Kreis" and "quinten" does not yield anything that seems relevant. Does anyone have a page number?


Permissions deselected, but user can still edit content

Question: Reproduce:

Create new content type with uid:1
In admin/people/permissions you can see that permissions are not given to Administrator role, they are deselected/unticked by default for the new content type.
E.g. create new user and give him Administrator permissions.
The new Administrator user (non-uid:1) can still edit/create/delete the new content type contents although the permissions are deselected?

How's that?
Comment: You need disabled option "view, edit, delete any content"
Answer: You need disabled option "view, edit, delete any content". If this option is checked, next options not used.


How to copy data automatically once certain data is input in Microsoft Excel 2010

Question: I need to copy certain amounts of data in Microsoft Excel 2010. I have 2 different sheets, i.e. "Master" and "Delivery". In the "Master" sheet, I am making a unique set of ids by concatenating two different cells. These unique ids may or may not exist in the "Delivery" sheet.
I would like to copy certain cells (transport name and d.o.d) automatically for those ids that exists in both "Master" and "Delivery" sheets. Those in the master sheet that do not exist in the delivery sheet should be display "#N/A". Perhaps there are some formulas in the excel that may be able to solve the problem.
Example of the sheets:
Master sheet
job no      no.      desc      unique id    id in delivery  transport name  d.o.d

1acf23    452036     pen      1acf23452036      Y

1acf23    786952     disc     1acf23786952      Y

1acf25    786952     disc     1acf25786952      N

2rfg45    462230     box 1    2rfg45462230      Y

3rfg45    415789     eraser   3rfg45415789      Y

Delivery Sheet
d.o.d   transport name  job no  no  desc    unique id   id in master

01.08.14    brand1  1acf23  452036  pen     1acf23452036    Y

02.07.14    brand1  1acf23  869632  file    1acf23869632    N

20.03.13    brand1  1acf23  786952  disc    1acf23786952    Y

16.06.14    brand1  1acf23  999021  cutter  1acf23999021    N

17.08.13    brand3  2rfg45  462230  box 1   2rfg45462230    Y

01.01.14    brand2  3rfg45  415789  eraser  3rfg45415789    Y

09.05.14    brand3  2rfg45  415789  eraser  2rfg45415789    N

09.05.14    brand3  2rfg45  462230  box 1   2rfg45462230    Y

01.01.14    brand2  1acf23  263246  pencil  1acf23263246    Y

09.05.14    brand3  5thy12  102364  casing  5thy12102364    Y

Answer: I hope I have your columns right.
For transport name in Master:
=INDEX(Delivery!B:B,MATCH(Master!D2,Delivery!F:F,0))

and for d.o.d
=INDEX(Delivery!A:A,MATCH(Master!D2,Delivery!F:F,0))

Greetings
Axel
Answer: Have a look at the Excel function vlookup. You'll probably want to use the flag that makes it look for exact matches only.
Comment: VLOOKUP can not look to the left, just to the right.


Creating and updateable block on home page of site

Question: I have a 'featured resource' block on the home page of my site. I'd like my very non-technical folks to be able to update this block with a new node every week. Note that it would just display the teaser of the node, with a 'read more' link.
Ideally, it would be easy for them to do this (for example, by just checking a box on the node creation/edit page to add it to the featured resource block).
Anyone have recommendations for the best/easiest way to do this?
Answer: Drupal allows a node to be marked as "Promoted to front page" when editing the page (it's at the bottom, under "Publishing options").
You can make your block from a View

Enable the Views module.
Add a new view admin/structure/views/add
Create a block (untick create a page)
Click "Continue & edit"
Add a filter by "Promoted to front page"
Alter "Use pager" to display 1 item.
You should already have a sort by post date.
Save changes.
Add the block to your home page (it sounds like you already know how to do this, but ask if not).

This view will show the most recent item with promoted to front page set.


How do racing cars use aerodynamic ground effect?

Question: My understanding is that ground effect works when the ground or other surface interrupts the downdraft thereby reducing aerodynamic drag.
With cars, it seems that the explanations I've found describe using the car's body itself as a wing and creating a venturi between the bottom surface of the car and the track. However, with a car the aerofoil's "downdraft" is going upwards so there's no surface to interact with it. In this case there wouldn't be any ground effect.
Am I misunderstanding this? How does ground effect work in a car which is producing downforce rather than a aircraft where it produces additional lift?
Answer: A simplistic way to think about this is that the wing is shoving air from one side to the other.  This creates higher and lower pressure regions around the wing that cause lift (higher pressure below on a plane, higher pressure above on a car).
If you put the ground under an airplane wing, the air "builds up" under the wing because it can't disperse as easily.  This allows the pressure to build up higher than it would otherwise.  The greater difference means greater lift over the area of the wing.
If you put the ground under a car wing, the low-pressure region can't be filled in by air easily because the ground is in the way.  This lets the pressure be lower than it would in a free-stream flow.  The "lift" generated from the pressure differential is greater.
Comment: No, I don't think so.  It can help in either direction.  If toward the ground, the air can't "get out of the way" and the high pressure is increased.  If away from the ground the air can't flow in to replace, and the low pressure is made lower.    If someone wants to give the other direction a different name on principle, fine, but I don't see a reason they can't both be called "ground effect".  This seems more like a point of language than one of physics or one of sport.
Comment: That all makes sense but in the example of a car it's not "ground effect" as I understand it.
Comment: Airplane ground effect is when the wing is within a wingspan of the ground and the non-freestream effects are significant.  I've got no problem describing a F1 car's aerodynamics as being in ground effect.  Not sure if there's some technical reason that someone wouldn't like that description.
Comment: I get that but I thought the whole point was the air displacement had to be TOWARD the ground for it to work?
Comment: if the effect is empirically equal in both directions that answers my question I think


How to solve simple differential equation

Question: Solve the initial value problem
$$y' = \frac{1 + y^2}{x};\ y(1)=1;\ x>0$$
by separation of variables.
Comment: What have you tried, and where did you get stuck?  We will be able to help you more if you post your work.
Comment: @anorton, I fail at integration part.
Answer: write $y' = \frac{dy}{dx}$ and you get $\frac{dy}{dx} = \frac{1+y^2}{x} \implies \frac{dy}{1+y^2} = \frac{dx}{x}$ and integrate both sides. use $y(1) = 1$ to find the value of constant after integration.
Comment: So we integrate both sides from 1 to something? And can you please give an explanation of integrating 1/(1+y^2)?
Comment: No no ... just plain indefinite integration. $\int \frac{dy}{1+y^2} = \int \frac{dx}{x}$
Comment: Are you sure we're not supposed to integrate from 1 to y or from 1 to x respectfully?
Comment: No ... this is indefinite integration that results in integral constant $C$, and we use that initial condition to find the value of this $C$
Comment: ok, so then I should end up with y=tan(ln(x)+1). Can you confirm?
Comment: $y = \tan \left( \ln x + C \right)$ put $y(1) = 1$, we get $1 = \tan(\ln 1 + C) $ so the latter $1$ you wrote must be $\pi \over 4$
Comment: oh, ok, now I see (I just substituted C with y(1)). Thanks!


Profiling depositado no Repositório de Versionamento(GitHub)

Question: Estou fazendo alguns testes com um código experimental que faz contagem de ciclistas na ciclofaixa, para estes testes estou usando o gprof e gcov que geram diversos arquivos de análise, um destes aquivos gerado pelo gprof estou enviando para o repositório de versionamento para manter um histórico relativo a melhoria do código.
Os demais arquivos devo enviar também? Qual estrutura de arquivos devo usar para tal histórico de optimização e relatórios de profiling.
Answer: Delfino,
Via de regra, o normal não é você colocar dados coletados de um build, por exemplo, ou de resultados de teste; no controle de versão.
Normalmente esse tipo de dado entra em banco de dados OLAP, ou como input de um ferramenta.
Eu não conheço esses tipos de arquivos, porém, imagino que você irá usar alguma ferramenta para ler esses dados, se ela irá pegar do controle de versão, seria interessante criar um novo repositório somente para esses dados, ou irá onerar o repositório de código, fazendo que os desenvolvedores baixem arquivos desnecessários ao desenvolvimento e de tamanho grande. Se a fonte para a análise não for nem o repositório git, esse arquivo não deve ser colocado lá. Seria uma má prática.
Comment: o arquivo é um txt comum com diversas anotações, os arquivos raw não penso em colocar são realmente binários e gerados localmente, apesar que podem ser unificados para uma analise posterior. Pensei em colocar como submódulo, mas cai na mesma questão de ter material em excesso para baixar, um banco de dados remoto não é viável, e uma ferramenta de compartilhamento de arquivos como dropbox não sei se resolveria pois não iria controlar bem múltiplos usuários atualizando os mesmos arquivos.
Comment: Por que um banco de dados remoto não é viável? Ou mesmo um local, sendo sincronizado manualmente
Comment: Eu não tenho o banco de dados, e o arquivo não passa de um arquivo TXT, e o uso de cloud não dá abertura para que todos alterem com versionamento os arquivos, Sugestões são bem vindas.


How can I get tasks of a group which I belong to (jBPM 6.2)

Question: I'm trying to create a BPM using jBPM 6.2. The process looks like:
User creates a request. His manager will evaluate to accept or reject. In the case his manager accepts, the IT dept's guys will implement that request
But I cannot get task from the group which I belong to. In my BPM, The human task was assigned to IT group. I tried to use account: salaboy, jack (in IT dept) but I don't see any tasks associated with those account
Below is the screenshot of my process and you can see the group ID is IT

I didn't change any configuration of the server. The roles look like:
admin=admin,analyst,kiemgmt
krisv=admin,analyst
john=analyst,Accounting,PM
mary=analyst,HR
sales-rep=analyst,sales
jack=analyst,IT
katy=analyst,HR
salaboy=admin,analyst,IT,HR,Accounting

The code to test is that:
public static void main(String[] args) {
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();
    KieBase kbase = kContainer.getKieBase("kbase");

    RuntimeManager manager = createRuntimeManager(kbase);
    RuntimeEngine engine = manager.getRuntimeEngine(null);
    KieSession ksession = engine.getKieSession();
    TaskService taskService = engine.getTaskService();

    ksession.startProcess("com.sample.bpmn.hello");

    // let john execute Task 1
    List<TaskSummary> list = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    TaskSummary task = list.get(0);
    System.out.println("John is executing task " + task.getName());

    taskService.start(task.getId(), "john");
    taskService.complete(task.getId(), "john", null);

    // let mary execute Task 2
    list = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK");
    task = list.get(0);
    System.out.println("Mary is executing task " + task.getName());
    taskService.start(task.getId(), "mary");
    Map<String, Object> params = new HashMap<>();
    params.put("output", true);
    taskService.complete(task.getId(), "mary", params);

    // let salaboy execute Task 3

    list = taskService.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");
    task = list.get(0);

    System.out.println("salaboy is executing task " + task.getName());
    taskService.start(task.getId(), "salaboy");
    taskService.complete(task.getId(), "salaboy", null);

    manager.disposeRuntimeEngine(engine);
    System.exit(0);
}

private static RuntimeManager createRuntimeManager(KieBase kbase) {
    JBPMHelper.startH2Server();
    JBPMHelper.setupDataSource();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa");
    RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.Factory.get()
        .newDefaultBuilder().entityManagerFactory(emf)
        .knowledgeBase(kbase);
    return RuntimeManagerFactory.Factory.get()
        .newSingletonRuntimeManager(builder.get(), "com.sample:example:1.0");
}

If I assign the Implement task to salaboy, it works like a charm
Please let me know if you have any suggestions
Thanks
Comment: Thank you so much Mike, I just updated my post with more information. Can you please take a look and advise. As you can see in my post, I use TaskService to get tasks. What is the different between RunTimeDataService and TaskService?
Comment: It would probably help if you showed us some code examples. In theory is you use the RuntimeDataService.getTasksAssignedAsPotentialOwner method it should return the a Collection of tasks that the user could claim/start. Did you verify that the users are actually in the role? Is the UserGroupCallback properly setup? Is the GroupID specified for step?
Comment: I noticed that Salaboy is an admin, and you aren't. My thoughts would be that you're not set up with the appropriate role in the user roles table in the database.
Comment: Well, as far as i know, default configurarion of users and roles is in properties file. And i didn't change anything, just added a new project to play around so i don't think this is a reason. Anyway, i will take a look on it to double check. Is there a GUI to check roles of user
Comment: I think you might be confusing John and Jack.
Comment: Looks like this issue occurs again, I will spend time to investigate if I have a chance https://developer.jboss.org/thread/167132?start=0&tstart=0
Comment: Can you add the code for whatever class implements the UserGroupCallback interface? It looks like you are copying the roles out of the properties file; however, the role matching will occur in the class that implements the UserGroupCallback. I have a feeling that the default implementation of the role mapping does not exactly map with the properties file you copied.
Comment: Thanks Mike, I will try again tomorrow. Today I already checked to see if I made a mistake in properties file, but it seems correct. I tried to query H2 database and saw new user which I added in properties file exists in Organization Entity table
Comment: It seems that the process doesn't work correctly because of Eclipse. I tried to create a similar process by Workbench (Web version) and it works like a charm
Answer: We should use Workbench (Web version) instead of Eclipse.


Querying Active directory

Question: I want to query user credentials against an Active Directory without the user entering his credentials. i.e The user logs into his corporate system(Intranetwork) i need to use these credentials to verify against an AD and retrieve his email address if the user exists.(NO single sign on required)
Answer: Of course, It is too late to answer, but ... someone like me can search same answer...
I'm just not sure why do you need to verify user credentials?
If user already logged-in then ... credentials are verified.
Getting his email (and other info from AD) is possible by using Windows powershell.
public class TestWindowsAD {

public static void main(String... args) throws Exception {

    System.out.println("Current user e-mail: " + getCurrentUserEmail());

}

private static String getCurrentUserEmail() {

    String cmd = "powershell \"Add-Type -AssemblyName System.DirectoryServices.AccountManagement;[System.DirectoryServices.AccountManagement.UserPrincipal]::Current.EmailAddress;\"";
    String userEmail = "";
    if (!System.getProperty("os.name").toLowerCase().startsWith("win")) { throw new RuntimeException(
            "We are not in Windows! OS is " + System.getProperty("os.name")); }
    Runtime rt = Runtime.getRuntime();
    Process pr;
    try {
        pr = rt.exec(cmd);
        pr.waitFor();
        BufferedReader bf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String nextLine = null;

        while (true) {
            nextLine = bf.readLine();
            if (nextLine == null) break;
            userEmail = nextLine;
        }
        bf.close();
    } catch (Exception e) {
        System.err.println("Failed to get user email: " + e.getMessage());
        throw new RuntimeException(e);
    }

    return userEmail;
}

P.S. if you need more info just run in command prompt:
powershell "Add-Type -AssemblyName System.DirectoryServices.AccountManagement;[System.DirectoryServices.AccountManagement.UserPrincipal]::Current"

and pick what you need.

Querying Active directory


Como atualizar uma página web automaticamente logo após de uma inserção de registro no banco de dados? Usar NodeJs?

Question: Este é o cenário:
Tenho um usuário central, o gerente de um hotel que vai ficar monitorando 24 hs o status dos quartos em tempo real.
Os quartos possuem 3 status:
1-Em uso.
2-Em manutenção (limpeza).
3-Disponível.
A atualização desse status pode vir de um ou vários usuários, por exemplo serventes que acabaram de entrar no quarto para iniciar uma limpeza.
O gerente precisa saber o que está acontecendo com os quartos em tempo real.
Para isso bastaria fazer o refresh da página do Gerente, cada vez que um servente inserisse algum registro no banco de dados (como acontece com o facebook por exemplo). Caso nada seja inserido no banco de dados, a pagina não precisa se atualizar.
Tudo que tenho em mente é o refresh automático da página, mas ele acontecerá a cada segundo estipulado, haja inserção no BD ou náo. Para isso eu faria:
1 - dentro do , usar a seguinte tag Meta
<Meta http-equiv="refresh" content="x" />

Onde "x" é o tempo. expl x=1 (1s).
2 - Poderia usar javascript setTimeout() para a página chamar a si mesma a cada x segundos.
3 - poderia fazer uma combinação de setTimeout() com ajax.
Acho que existem técnicas mais modernas para alcançar o mesmo objetivo, se não me engano.
Como sou novato no nodeJS gostaria de saber se seria mais apropriado usar o nodeJs nesse cenário, em detrimento das técnicas citadas anteriormente e que já domino, e se for o caso de usar o node, como implementaria o código para atualizar a pagina do gerente respondendo ao evento insert no banco de dados feito por outro usuário?
Comment: Refresh é gambiarra de qualquer maneira, não importa o que use no servidor. Monitorar pelo navegador não deixa de ser "gambiarra" também, apesar de estar na moda. Se mesmo assim quer fazer pelo navegador, é exatamente o que o @JoséX. afirmou, o lado do servidor não faz diferença, o problema é a tecnologia do lado cliente, e ele listou as alternativas no comment acima. Ideal mesmo seria uma aplicação nativa.
Comment: não sou desenvolvedor web, então não posso responder com autoridade,mas acho que é irrelevante se vai usar node.js ou qualquer outra tecnologia no servidor, o importante é qual tecnologia real time você vai usar, se long polling, server sent events, websockets, etc
Comment: na verdade as minhas abordagens (1, 2 ou 3) resolvem o problema. Porém fazer o refresh da pagina mesmo se nada foi modificado no bd, eu acho isso meio gambiarra. Queria saber se nodeJs é a alternativa correta sem gambiarra, e como seria essa implementação.
Comment: Boas não uso o node.js mas tive um projeto no trabalho mais ou menos nessa características e o que eu fiz foi usei php criei as queries que queria e sim também usei meta para fazer o refresh, talvez fosse mais eficaz e facil só usares php embutido no html
Answer: Tive que passar uns dias estudando para achar a resposta correta. Poder usar uma técnica ou outra não quer dizer que ela deva ser utilizada.
Depende da situação. No meu caso específico eu poderia usar polling, ou long polling, ou outras. Mas eu queria saber qual a abordagem adequada
e por quê.
Então vou fazer um resumo do que li, e justificar o pq da escolha do SSE e não as outras sugestões.
Desde o seu início, as aplicações web foram criadas numa lógica de cliente/servidor, onde o cliente SEMPRE INICIA o processo enviando
uma requisição para o servidor e este retorna uma resposta para o cliente (Note que a resposta pode ser um conjunto vazio.
Exemplo: um cliente pergunta por algum dado novo no banco de dados e o servidor responde dizendo que não houve nenhuma alteração
no BD desde a última requisição).
Seguindo essa lógica, não havia alguma maneira do servidor enviar as novas alterações para o cliente de modo INDEPENDENTE, ou seja,
sem que este tenha requisitado primeiro essa ação.
O tempo passou e junto com os dispositivos móveis, o HTML5 e a internet de alta velocidade, veio também o aparecimento da web real time,
que é um conjunto de técnicas e tecnologias que permitem com que os usuários troquem (enviem e recebam) informações em tempo real. Informações que podem ser dos mais diversos tipos, partindo desde pequenas strings como "Oi tudo bem?", passando por jogos real time, chegando até uma streaming de vídeo 4k ou broadcasting bi-direcional e eté mesmo aplicações real time como SAP-HANA com IoT, entre outras necessidades de cominicação bi-direcional ou não.
O fato é que a natureza da web é uni-direcional e as necessidades hoje(2016) são outras. Precisamos de uma comunicação bi-direcional e em real time, sem ter que usar códigos para fazer automaticamente requisições periódicas ao servidor.
Como a solução ainda não estava na mão, apareceram várias técnicas para tentar SIMULAR um canal aberto, bi-direcional onde uma requisição possa ser feita pelo cliente ou uma resposta possa ser enviada pelo servidor, assim que estiver disponível. Um exemplo claro é o facebook ou twitter onde a primeira requisição é feita pelo cliente quando ganhamos acesso à nossa página e depois de lagum tempo de inatividade recebemos notificações de que novas mensagens estão disponíveis, sem que para isso tenhamos solicitados nada a mais.
Vamos ver algumas (não todas) técnicas disponíveis para alcançarmos essa tarefa. Vale notar que um assunto puxa o outro e aqui neste ponto onde se tenta
SIMULAR um canal aberto de comunicaçõ bi-direcional com o servidor as primeiras técnicas, ou a maioria delas, passam a usar requisições periódicas aos
servidores e com isso apareceu um novo problema precisando desde já de uma solução - a sobrecarga dos servidores com requisições bloqueantes de I/O devido às características de processos multi threads. A solução veio com o NODEJS onde tenta fazer o I/O de maneira diferente tenatndo não bloquear o processo. Além disso temos a ajuda do balanceamento de carags com o proxi reverso do NGINX para dar suporte nessa batalha da comunicação bi-direcional cliente/servidor. Esse não é o assunto mas aqui tem um bom vídeo em português falando um pouco de teoria do NODEJS
Então vamos às nossas alternativas de se manter uma conexão bi-direcional com o servidor:

Usar a tag meta com o http-equiv igual a refresh <meta http-equiv='refresh' content='5'> . Essa técnica permite recarregar a página a cada período especificado no atributo content. No exemplo o refresh será feito a cada 5 segundos. Embora seja fácil e uma possível solução para um problema específico, vale lembrar que os principais motores de pesquisa penalizam páginas com http-equiv='refresh' colocando-as na lista negra pois são consideradas práticas anti-éticas de SEO. Doorway page.
Leitura:
Link
Aprimeira alternativa ao http-equiv='refresh' é o uso do javascript - AJAX. XMLHttpRequest (XHR) deu a primeira ilusão de que estava se ENVIANDO dados do servidor para o cliente através de uma conexão (cliente<-->servidor) HTTP persistente ou duradora, mas este não foi o caso. Pois os dados não estavam sendo enviados e sim puxados do servidor. Com o XHR a solicitação é feita pelo cliente de maneira que o usuário não opera nenhum evento explicitamente. O XHR tbm inaugurou o modelo Comet com suas diferentes abordagens (Hidden iframe, XHR polling, XHR long polling e Script tag long polling). Em geral essas técnicas tbm podem ser classificadas como AJAX REVERSO pois tentam mimetizar uma pseudo autonomia do servidor para enviar dados para o cliente. Mas são todas técnicas iniciadas pelo cliente. Essas técnicas podem representar a solução ideal para algumas situações, mas possuem alguns efeitos colaterais, tais como sobrecarga no servidor (e ai vem o NODEJS e NGINX para amenizar o problema) devido a requisições programáticas desnecessátias. Imagina um servidor com 100 mil clientes conectados e fazendo polling a cada 5s onde 30%s desses recebem respostas vazias do servidor (exemplo citado anteriormente no início do texto). O threads foram carregados e I/Os foram bloqueados desnecessariamente. Nem precisa analisar muito para perceber a ineficiência e a dificuldade da escalabilidade.

2.1. XHR. O browser solicita informação ao servidor após um evento iniciado pelo usuário, sem  a necessidade da página ser recarregada. O servidor envia resposta vazia ou não.
2.2. XHR polling. O browser fica solicitando informação do servidor periodicamente e este continua enviando respostas vazias, até que alguma informação nova esteja disponível.  Comparado com o AJAX (XHR) tradicional, o XHR polling dispensa a necessidade da ação do usuário. Ou seja, pode ser usado em situações onde uma página precise ser modificada automaticamente.
2.3. O Piggyback polling é uma derivação do XHR polling que tenta remover as requisições que originarão respostas vazias e enviar dados adicionais. Não exitem requisições intervalares. O cliente manda a requisição quando ela precisa ser enviada. A diferença é que a resposta pode ser quebrada em pedaços (resposta solicitada + outros eventos no servidor). Além de não resolver o problema de sobrecarga das requisições desnecessárias, precisa modificar o código do cliente para responder aos casos de dados adicionais eventualmente enviados.
2.4. XHR long polling. Como as novas informações são enviadas somente quando acontece inicialmente uma requisição do cliente, isso causa um atraso no recebeimento da informação pelo browser, em relação ao momento que ela estava disponível no servidor. Então a solução long polling evita requisições frequentes e favorece recebimentos quase imediatos dessas informações. O browser solicita ao servidor, mas esse só responde quando tem algo para enviar. Então o servidor deixa a requisição suspensa até que exista dados para ser enviado ao browser. Uma vez que os dados foram enviado o servidor encerra a transação, o browser recebe o resultado e inicia logo em seguida uma outra requisição. Comparado com o polling o long polling diminui o uso desnecessário dos recursos do servidor, mas não 100% pois as solicitações continuam sendo enviadas ao servidor (talvez desnecessariamente). Seguindo o exemplo acima, 100 mil requisições seriam enviadas ao servidor, ainda que nem todas tenham respostas imediatas.
Então digamos que 60% dos clientes (60 mil) só recebem atualização 3 vezes ao dia. Se eles permanecesses conectados usando o long pooling só haveria 3 + 1  transações ao dia para esses clientes. Nos modelos anteriores haveria transações a cada intervalo de tempo estabelecido. Essa é uma boa estratégia de comunicação bi-direcional e existem algumas abordagens para realizá-la ou implementá-la. São elas:
2.4.1-Forever Iframe
2.4.2-Multipart XHR
2.4.3-Script Tags com JSONP
2.4.4-Long Living XHR
Leituras:

https://en.wikipedia.org/wiki/Comet_(programming)
http://www.ibm.com/developerworks/web/library/?series_title_by=reverse+ajax
http://www.ibm.com/developerworks/web/library/wa-reverseajax1/index.html
http://www.ibm.com/developerworks/web/library/wa-reverseajax2/index.html
http://www.ibm.com/developerworks/web/library/wa-reverseajax3/index.html
http://www.ibm.com/developerworks/web/library/wa-reverseajax4/index.html
http://www.ibm.com/developerworks/web/library/wa-reverseajax5/index.html
http://directwebremoting.org/dwr/documentation/reverse-ajax/index.html
http://directwebremoting.org/dwr/documentation/reverse-ajax/getting-started.html
http://learn.elgg.org/en/stable/guides/ajax.html
https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Forever-iframe technique => http://cometdaily.com/2007/11/05/the-forever-frame-technique/
multipart xhr => https://stackoverflow.com/questions/9395911/sending-a-file-as-multipart-through-xmlhttprequest
multipart xhr => https://xhr.spec.whatwg.org/#interface-formdata

2.5-Embora as técnicas vistas anteriormente funcionem, e elas permitam uma comunicação duplex ou bi-direcional (cliente->servidor / servidor ->Cliente), elas são apenas alterações de uma tecnologia que não foi criada para esse fim.
É quando entra em cena o HTML5. Essa nova versão do HTML traz embutida em si mesmo (nativo) 2 abordagens ou tecnologias que permitem a comunicação bi-direcional ou uni-direcional (servidor -> cliente) sem ter que alterar nada.
São elas:
2.5.1 - SSE -> Server-Sent Events. Consulta unidirecional (servidor->cliente). Fácil implementação.
2.5.2 - Web SOCKETS -> Full Duplex Web Sockets. Consulta bi-direcional. Implementação um pouco mais trabalhosa.
Leituras:

SSE - https://www.w3.org/TR/2011/WD-eventsource-20110208/
Web SOCKETS - https://www.w3.org/TR/2011/WD-websockets-20110929/

Fico por aqui pois o SSE responde à pergunta original do post. Eu queria uma comunicação unidirecional do servidor para o cliente.
Não tem necessidade (nesse cenário) de sobrecarregar o servidor com requisições que poderiam retornar consultas vazias ou sem nenhuma
alteração desde a última query.
Comment: Ainda estou tentando entender porque esta resposta não ganhou vários ups! Bom trabalho.
Answer: Use o PubNub. Usei em alguns projetos e é muito rápido. Existe um SDK Javascript.
Answer: Olá, acredito que uma boa forma de trabalhar com operações em real time é utilizando socket.io ( para node.js ), acesso o link e bons estudos.
Comment: Bem vindo a comunidade stackoverlow em português. Faça um [tour](http://pt.stackoverflow.com/tour) e conheça um pouco das regras e boas práticas, responda de forma como seria possível implementar este recurso. (Um Exemplo)


Substitution in Integration about log

Question: A question on my book:
$$\int{\frac{1}{x(\log{x})^n}dx}$$where n is an integer.
What I did:
Let u=$\frac{1}{\log{x}}$, then $\frac{du}{dx}=x, dx=\frac{du}{x}.$
Now the integral becomes $$\int{\frac{1}{xu^n}dx}=\int{\frac{1}{xu^n}\times {\frac{du}{x}}}$$
I don't know what to do next. Should I change another u?
Note: if possible, please use substitution to solve the problem.
Comment: $\dfrac{\mathrm d u}{\mathrm d x}=-\dfrac1{x\log^2x}$, not $\;\dfrac1{\log' x}$.
Answer: Call $u=\log x$, then $du = dx/x$ and your integral becomes
$$
\int\frac{dx}{x\log^n x} = \int\frac{du}{u^n} = \cdots
$$
Answer: Consider the substitution $u=\log x$ and so $du=\frac{1}{x}dx$. Hence,$$
\int \frac{1}{x(\log x)^n}\,dx=\int\frac{(\log x)^{-n}}{x}\,dx=\int u^{-n}\,du.
$$
Then, for $n\geq 2$, we get$$
\int u^{-n}\,du=\frac{u^{1-n}}{1-n}=\frac{(\log x)^{1-n}}{1-n}.
$$
For $n=1$, we get$$
\int u^{-1}\,du=\log u=\log(\log x).
$$
Comment: Not true if $n=1$.

Substitution in Integration about log


Why is my program not sending keyboard data over socket?

Question: I have a simple program designed to send raw text data over a TCP socket. I'm thinking this is a buffering problem; but I am not sure. No data appears to be sent.
from threading import Thread as thread
from sys import argv
from socket import socket
from tty import setraw
from sys import stdin
from sys import stdout
def rx(so):
    while True:
        stdout.write(so.recv(1).replace("\n", "\n\r"))
setraw(stdin.fileno())
so = socket()
so.connect((argv[1], int(argv[2])))
thread(target=rx, args=(so, )).start()
while True: so.send(stdin.read(1))

EDIT to clarify:
Keyboard data is not being sent.
Comment: This won't send anything unless you send it something. `\n\r` is wrong, it should be `\r\n`.
Comment: Q: Did you hit "return" anywhere in your keystokes?  Stdin *WILL* buffer data until you hit "return"...
Comment: @paulsm4 yes, but it's supposed to be unbuffered
Answer:
Minor quibble:
As  user207421 said, "\n\r" is wrong.  The correct DOS CR/LF sequence is '\r\n'.
Who knows - maybe you don't need that "replace()" at all.
First Step: verify you can send/receive anything:
Q: Do you see data returned from your socket when you type a few characters, then hit "return"?
Please confirm "Yes" or "No".
Python socket: Try disabling Nagle:
Try something like this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

Raw keyboard input:
If you've verified steps 2 and 3 (you're able to send and receive data, and socket buffering isn't an issue), then you've isolated the problem to "stdin buffering".
Look here for additional suggestions:  unbuffered read from stdin in python
Additional suggestion:
For troubleshooting, can also try sending socket data from a different program: "telnet", "curl", a second Python script, etc. etc.

Please post back and let us know what you find!


How does Rust know whether to run the destructor during stack unwind?

Question: The documentation for mem::uninitialized points out why it is dangerous/unsafe to use that function: calling drop on uninitialized memory is undefined behavior.
So this code should be, I believe, undefined:
let a: TypeWithDrop = unsafe { mem::uninitialized() };
panic!("=== Testing ==="); // Destructor of `a` will be run (U.B)

However, I wrote this piece of code which works in safe Rust and does not seem to suffer from undefined behavior:
#![feature(conservative_impl_trait)]

trait T {
    fn disp(&mut self);
}

struct A;
impl T for A {
    fn disp(&mut self) { println!("=== A ==="); }
}
impl Drop for A {
    fn drop(&mut self) { println!("Dropping A"); }
}

struct B;
impl T for B {
    fn disp(&mut self) { println!("=== B ==="); }
}
impl Drop for B {
    fn drop(&mut self) { println!("Dropping B"); }
}

fn foo() -> impl T { return A; }
fn bar() -> impl T { return B; }

fn main() {
    let mut a;
    let mut b;

    let i = 10;
    let t: &mut T = if i % 2 == 0 {
        a = foo();
        &mut a
    } else {
        b = bar();
        &mut b
    };

    t.disp();
    panic!("=== Test ===");
}

It always seems to execute the right destructor, while ignoring the other one. If I tried using a or b (like a.disp() instead of t.disp()) it correctly errors out saying I might be possibly using uninitialized memory. What surprised me is while panicking, it always runs the right destructor (printing the expected string) no matter what the value of i is.
How does this happen? If the runtime can determine which destructor to run, should the part about memory mandatorily needing to be initialized for types with Drop implemented be removed from documentation of mem::uninitialized() as linked above?
Comment: As Raymond Chen is fond of pointing out, because "undefined behavior" means "anything can happen and still be valid," *one of the valid consequences is for everything to appear to run correctly.*
Comment: @mickeyf @MasonWheeler: Sorry if i didn't understand you but in Rust I would expect if i didn't use any `unsafe` code (which i don't in the main example above) whatever is the behavior observed (even in the first run of it) is pretty much well defined - that would be (one of) the main reason many would choose Rust in the first place (at least i did).
Comment: A.K.A. "mistaking absence of evidence for evidence of absence" - in infamous Black Swan.
Comment: @ustulation I don't know rust at all, so I cannot say whether this is "undefined behavior" or not, but to spell out what Mason and I are saying: If what you show is in fact "undefined behavior" then even if it did seem to work this time or even the next 100 times, that could be because you got lucky and that it may not work every time.
Answer: Using drop flags.
Rust (up to and including version 1.12) stores a boolean flag in every value whose type implements Drop (and thus increases that type's size by one byte). That flag decides whether to run the destructor. So when you do b = bar() it sets the flag for the b variable, and thus only runs b's destructor. Vice versa with a.
Note that starting from Rust version 1.13 (at the time of this writing the beta compiler) that flag is not stored in the type, but on the stack for every variable or temporary. This is made possible by the advent of the MIR in the Rust compiler. The MIR significantly simplifies the translation of Rust code to machine code, and thus enabled this feature to move drop flags to the stack. Optimizations will usually eliminate that flag if they can figure out at compile time when which object will be dropped.
You can "observe" this flag in a Rust compiler up to version 1.12 by looking at the size of the type:
struct A;

struct B;

impl Drop for B {
    fn drop(&mut self) {}
}

fn main() {
    println!("{}", std::mem::size_of::());
    println!("{}", std::mem::size_of::());
}

prints 0 and 1 respectively before stack flags, and 0 and 0 with stack flags.
Using mem::uninitialized is still unsafe, however, because the compiler still sees the assignment to the a variable and sets the drop flag. Thus the destructor will be called on uninitialized memory. Note that in your example the Drop impl does not access any memory of your type (except for the drop flag, but that is invisible to you). Therefor you are not accessing the uninitialized memory (which is zero bytes in size anyway, since your type is a zero sized struct). To the best of my knowledge that means that your unsafe { std::mem::uninitialized() } code is actually safe, because afterwards no memory unsafety can occur.
Comment: well... the difference is that a `let x = mem::uninitialized()` allows you to take references to `x`, while `let x;` doesn't allow this. Therefor you can pass that reference to a function that only writes to that memory. A common example is `let mut x: [i8; 42] = mem::uninitialized(); some_slice_function(&mut x)`
Comment: Right - my drop() impl is trivial to just show the printouts of which ones are executed, but i was talking about general cases of-course. One question though why is `mem::uninitialized()` seen as an assignment to set the drop-flag ? If i were setting it to a particular location (like `operator new()`) then it would make sense, but assigning a random memory location (wherever it is on stack that time) should not have set the drop-flag ? I mean when would that be meaningful ? (It could set it on next assignment just like for case of `b` when `i` is odd).
Answer: There are two questions hidden here:

How does the compiler track which variable is initialized or not?
Why may initializing with mem::uninitialized() lead to Undefined Behavior?

Let's tackle them in order.

How does the compiler track which variable is initialized or not?

The compiler injects so-called "drop flags": for each variable for which Drop must run at the end of the scope, a boolean flag is injected on the stack, stating whether this variable needs to be disposed of.
The flag starts off "no", moves to "yes" if the variable is initialized, and back to "no" if the variable is moved from.
Finally, when comes the time to drop this variable, the flag is checked and it is dropped if necessary.
This is unrelated as to whether the compiler's flow analysis complains about potentially uninitialized variables: only when the flow analysis is satisfied is code generated.

Why may initializing with mem::uninitialized() lead to Undefined Behavior?

When using mem::uninitialized() you make a promise to the compiler: don't worry, I'm definitely initializing this.
As far as the compiler is concerned, the variable is therefore fully initialized, and the drop flag is set to "yes" (until you move out of it).
This, in turn, means that Drop will be called.
Using an uninitialized object is Undefined Behavior, and the compiler calling Drop on an uninitialized object on your behalf counts as "using it".

Bonus:

In my tests, nothing weird happened!

Note that Undefined Behavior means that anything can happen; anything, unfortunately, also includes "seems to work" (or even "works as intended despite the odds").
In particular, if you do NOT access the object's memory in Drop::drop (just printing), then it's very likely that everything will just work. If you do access it, however, you might see weird integers, pointers pointing into the wild, etc...
And if the optimizer is clever, even without accessing it, it might do weird things! Since we are using LLVM, I invite you to read What every C programmer should know about Undefined Behavior by Chris Lattner (LLVM's father).
Comment: On the bonus part though - U.B should not be possible without `unsafe` code - so if it appears to work it better be a defined behavior since i haven't used any unsafe code in the main example in O.P. (in case you are referring to it)
Comment: Further question: if `i` is even and compiler can track that `b` is uninitialized and not call its dtor on unwind, why can't it track something like `let u: Type = mem::uninitialized();` is uninitialized too (infact i'm explicitly specifying it as such) and **not** call its dtor during stack unwind, unless it was assigned ?
Comment: (b.t.w your answer is pretty explanatory/helpful as well but accepted the other just because it was put 1st and was equally helpful)
Comment: @ustulation: UB only occurs if you use `mem::uninitialized()` which requires `unsafe` code. I was merely commenting that "nothing weird happening" did not mean that you had steered clear of UB :) As for accepting another answer: you are free to accept whatever you wish! :)
Answer: First, there are drop flags - runtime information for tracking which variables have been initialized. If a variable was not assigned to, drop() will not be executed for it.
In stable, the drop flag is currently stored within the type itself. Writing uninitialized memory to it can cause undefined behavior as to whether drop() will or will not be called. This will soon be out of date information because the drop flag is moved out of the type itself in nightly.
In nightly Rust, if you assign uninitialized memory to a variable, it would be safe to assume that drop() will be executed. However, any useful implementation of drop() will operate on the value. There is no way to detect if the type is properly initialized or not within the Drop trait implementation: it could result in trying to free an invalid pointer or any other random thing, depending on the Drop implementation of the type. Assigning uninitialized memory to a type with Drop is ill-advised anyway.


bitmap row size calculation

Question: I found this source which works quite well, I just want to ask about this piece of code which I dont get:
<code>//calculate total size of RGBQUAD scanlines (DWORD aligned)

    bih.biSizeImage = (((bih.biWidth * 3) + 3) & 0xFFFC) * bih.biHeight ;
</code>
I get why there is "*3", but dont get the "+3" and the bitwise AND with FFFC hexa. Could someone explain me why he claculates size of the image this way?
Thanks
Answer: If you try that out for various values, you'll see it's actually forcing (width * 3) to round up to the smallest multiple of 4 that will contain it. He's probably doing this to enforce things to be 32-bit aligned.
Using python:
<code>>>> f = lambda x: ((x * 3) + 3) & 0xFFFC
>>> [f(x) for x in range(1, 20)]
[4, 8, 12, 12, 16, 20, 24, 24, 28, 32, 36, 36, 40, 44, 48, 48, 52, 56, 60]
</code>
The following shows the difference between just doing the straight multiplication and rounding upwards towards a multiple of 4
<code>>>> [(3*x, f(x)) for x in range(1, 8)]
[(3, 4), (6, 8), (9, 12), (12, 12), (15, 16), (18, 20), (21, 24)]
</code>
I'm surprised the code doesn't actually document this fact. Bit twiddling is a wonderful thing, but it can seem very arbitrary.
Comment: Considering RGBQUAD is a four-byte structure it makes sense now. Got it. Thanks!

bitmap row size calculation


Erro Uncaught Error: Class 'Cliente\Cadastro' not found Utilizando namespace

Question: Estou estudando sobre namespaces, escrevi o código abaixo, porém esta retornando o seguinte erro:

string(16) "Cliente\Cadastro"  Fatal error: Uncaught Error: Class
  'Cliente\Cadastro' not found in
  /var/www/html/curso_php/namespace/index.php:13 Stack trace: #0 {main}
  thrown in /var/www/html/curso_php/namespace/index.php on line 13

No arquivo config.php o var_dump() deveria retornar as duas classes.
Estrutura das pastas:
|-Projeto
|-config.php
|-index.php
|--class
|---Cadastro.php
|---Cliente
|-----Cadastro.php
config.php
<?php
    spl_autoload_register(function($nameClass){

        var_dump($nameClass);

        $dirClass = "class";
        $filename = $dirClass . DIRECTORY_SEPARATOR . $nameClass . ".php";

        if (file_exists($filename) === true) {
            require_once $filename;
        }

    });?>

Cliente\Cadastro.php
<?php
namespace Cliente {

    class Cadastro extends \Cadastro {
        public function registrarVenda() {

            echo "foi registrada uma venda para o cliente " . $this->getNome();

        }
    }
}?>

Cadastro.php
    public function getEmail():string
    {
        return $this->email;
    }

    public function getNome():string
    {
        return $this->nome;
    }

    public function getSenha():string
    {
        return $this->senha;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function setNome($nome)
    {
        $this->nome = $nome;
    }

    public function setSenha($senha)
    {
        $this->senha = $senha;
    }

    public function __toString()
    {
        return json_encode(array(
            "nome"=>$this->getNome(),
            "email"=>$this->getEmail(),
            "senha"=>$this->getSenha()
        ));
    }
}?>

index.php
<?php
require_once "config.php";

use Cliente\Cadastro;

$cad = new Cadastro();
$cad->setNome("Matheus");
$cad->setEmail("firstname.lastname@example.com");
$cad->setSenha("12345");

echo $cad;
echo "--------------
";

$cad->registrarVenda();?>

Answer: Confere sua classe Cadastro.php, o erro penso que esteja nela:
class Cadastro {
    private $nome;
    private $email;
    private $senha;

    public function getNome():string{
        return $this->nome;
    }

    public function getEmail():string{
        return $this->email;
    }

    public function getSenha():string{
        return $this->senha;
    }

    public function setNome($nome){
        $this->nome = $nome;
    }

    public function setEmail($email){
        $this->email = $email;
    }

    public function setSenha($senha){
        $this->senha = $senha;
    }

    public function __toString(){

        return json_encode(
            array(
                "nome"=>$this->getNome(),
                "email"=>$this->getEmail(),
                "senha"=>$this->getSenha()
            )

        );

    }

}

Answer: No arquivo de config, troca:
$filename = $dirClass . DIRECTORY_SEPARATOR . $nameClass . ".php";

para:
$filename = str_replace ("\\", "/", $dirClass . DIRECTORY_SEPARATOR . $nameClass . ".php");


Point in triangle

Question: Inside a random triangle, consider a point P and its distances PM, PN and PQ to the 3 sides a, b and c.
For which location of the point P the below sum gets minimal?
$$\frac{a}{PM} + \frac{b}{PN} + \frac{c}{PQ}$$
I think it is the incenter but how do we prove it?
Answer:
Note that
\begin{align}
a\cdot x+b\cdot y+c\cdot z&=2\,S=\mathrm{const}\quad\text{for fixed }a,b,c.
\end{align}
\begin{align}
\operatorname*{argmin}_{P}\left(\frac{a}x + \frac{b}y + \frac{c}z\right)
&=
\operatorname*{argmin}_{P}2\,S\cdot\left(\frac{a}x + \frac{b}y + \frac{c}z\right)
\\
&=
\operatorname*{argmin}_{P}
\left(
(\tfrac{x}y+\tfrac{y}x)\,ab+(\tfrac{y}z
+\tfrac{z}y)bc+(\tfrac{z}x+\tfrac{x}z)\,ca
+\underbrace{(a^2+b^2+c^2)}_{\mathrm{const}}
\right)
\\
&=
\operatorname*{argmin}_{P}
\left(
(\tfrac{x}y+\tfrac{y}x)\,ab+(\tfrac{y}z
+\tfrac{z}y)bc+(\tfrac{z}x+\tfrac{x}z)\,ca
\right)
,\\
\end{align}
\begin{align}
\left(
(\tfrac{x}y+\tfrac{y}x)\,ab+(\tfrac{y}z
+\tfrac{z}y)bc+(\tfrac{z}x+\tfrac{x}z)\,ca
\right)
&\overset{\text{AM-GM}}{\ge}
\left(
3\,
\sqrt[3]{
a^2\,b^2\,c^2\,
(\tfrac{x}y+\tfrac{y}x)
(\tfrac{y}z+\tfrac{z}y)
(\tfrac{z}x+\tfrac{x}z)
}
\right)
,\\
\operatorname*{argmin}_{P}
\left(
3\,
\sqrt[3]{
 a^2\,b^2\,c^2\,
 (\tfrac{x}y+\tfrac{y}x)
 (\tfrac{y}z+\tfrac{z}y)
 (\tfrac{z}x+\tfrac{x}z)
}
\right)
&=
\operatorname*{argmin}_{P}
\left(
 (\tfrac{x}y+\tfrac{y}x)
 (\tfrac{y}z+\tfrac{z}y)
 (\tfrac{z}x+\tfrac{x}z)
\right)
,\\
(\tfrac{x}y+\tfrac{y}x)
(\tfrac{y}z+\tfrac{z}y)
(\tfrac{z}x+\tfrac{x}z)
&\overset{\text{AM-GM}}{\ge}
2\cdot2\cdot2=8
,\\
\operatorname*{min}_{P}
\left(
(\tfrac{x}y+\tfrac{y}x)
(\tfrac{y}z+\tfrac{z}y)
(\tfrac{z}x+\tfrac{x}z)
\right)
&=8,\quad P:x=y=z
.
\end{align}
That is, $x=y=z=r$ and $P$
coincides with the incenter of the triangle.
Comment: What is argmin?
Comment: @ Alex.vollenga:  [argmin](https://en.wikipedia.org/wiki/Arg_max)

Point in triangle