Recommendation for modules/workflow to build a premium link directory

Question: I'm just about to start building a link directory and I'm at odds over the best way to go about it.
The directory will accept both standard (free) and premium subscriptions. Premium subscribers will have extra fields available to them to fill out and display on their 'profile' page (standard link directory model I guess).
The front-end directory itself will be based on taxonomy/views so that's not an issue, but I'm struggling with the best way to handle the subscriptions. Conceptually I guess I would be selling access to a user role for a limited period of time, and showing/hiding various fields on the profile form based on the role's permissions.
I'd prefer to use Commerce and I'm struggling to find a stable module (or example using rules) that would help me plan out this subscription system.
Has anyone built a similar system before? If not can anyone think of a good collection of modules/workflow to accomplish this? I'm happy to write as much custom code as is needed but I'd rather not reinvent the wheel where possible, and it seems like Drupal is made for this kind of thing.
EDIT
Following Patrick Kenny's comment I should add that I don't need these subscriptions to recur automatically, just for the access to the role to expire after a certain amount of time.
If this will be difficult to do with Commerce I'd love to hear any other ideas (Ubercart, etc).
Comment: The [presentation at Drupalcon Denver on recurring billing](http://denver2012.drupal.org/program/sessions/recurring-billing-hard-hard-hard) concluded flatly that there was no good way to do this right now, unfortunately.
Comment: Thanks @PatrickKenny that's good info to have. I'll update the question
Comment: what form of payments do you want to accept?
Comment: @MotoTribe I'd like to keep it as flexible as possible really; Initially I think it will PayPal, but this client is extremely financially-driven so as soon as something cheaper comes along in the UK they're very likely to change their mind
Comment: do you need to integrate with paypal or are they manually adding and removing subscriptions?
Comment: @MotoTribe It doesn't need to integrate with PayPal's subscriptions system, the payment will essentially be one-off; when the premium sub expires, the user will simply have the option to upgrade their account back up to a premium listing. All standard subscribers will have that option anyway so I don't see that being an issue. I'm not sure if I'm confusing things by using the word 'subscription' to be honest ;)
Comment: checkout the subs module http://drupal.org/project/subs
Answer: I'm building a site with free and paid memberships now; my use case isn't exactly the same but I'll share what I can.
I'm not using Drupal Commerce; in my case, users make a payment with PayPal and then I manually add a paid role to each account.  I intend to eventually set this up in Drupal Commerce but I haven't had the time yet.
When I add the paid role, a rule is triggered that automatically sets an expiration date using the Role Expire module.  Until very recently the 7.x rules integration was bugged but I am happy to report that it is now fixed and works great.
As for working with Commerce, Randy Fay also did a screencast on setting up content access for a membership site.  I'm not sure if the content access part is relevant but the final part of the screencast covers:

Create a product representing the premium role.
Create a rule that grants the premium role on order completion:

After updating an order
If the order state is Completed
And the order contains our premium product
Add a role to the user who is the owner of the order
Comment: That looks like a good solution for what I'm trying to do, thanks


String (g)Match

Question: Bom, estou querendo transformar uma string em tabela.
Tentei assim:
toset = "nb = 10, gb = 20, sb = 0, sfb = 0, ub = 0;"
toget = "nb = (.-), gb = (.-), sb = (.-), sfb = (.-), ub = (.-);"
t = toset:gmatch(toget)
for a,b,c,d,e in pairs(t) do
print(a.." "..b.." "..c.." "..d.." "..e)
end

Mas retorna esse erro:
[string "stdin"]:4: bad argument #1 to 'pairs' (table expected, got function)

Alguem sabe resolver? Obrigado.
Comment: `gmatch` não funciona assim. Nem `pairs`.
Answer: Se você confia nesse string, então use
t = loadstring("return {"..toset.."}")()

Depois você pode verificar o conteúdo de t com
for k,v in pairs(t) do
   print(k,v)
end

String (g)Match


Predicting the time until an expected event occurs

Question: I have a situation where an event is supposed to occur every x minutes for a number of different sites (each site could be configured for a different time interval x). From time to time the event may fail.
I'd like to be able to predict an interval of time that I should worry if an event hasn't occurred. (e.g. for site A 1 missed event indicates a problem that needs attention, but site B misses a lot, so I wouldn't worry about 5 missed events).
To make this a little more concrete. Let's say that I have 3 stores that are supposed to upload their sales data every 30 minutes. If store 1 misses an upload, it may be a temporary problem and they'll be able to upload at the next 30 minute interval. This is especially true if this happens frequently for store 1.
On the other hand store 2 may almost always upload at the 30 minute interval mark, so that one failure indicates a problem that someone needs to look at.
Assuming I have a lot of historical data on how frequently each store fails uploading, how would I go about creating a model for each store based on their history that I can use to determine an estimated prediction of when each store should next upload their data?
Comment: Should this be tagged survival analysis instead of time-series?
Comment: As @JasonMorgan notes, survival models are appropriate for this task.  Presumably, you want a parametric repeated-event model and then you would track the value of the deviance residual for a specific store.
Answer: The answer can be offered by survival analysis which, when used in engineering, is called reliability analysis. I understand that you need to estimate fault occurrence cross-time so  you might consider this article on assessing product Reliability.
Models you might want to consider include:

Power low (Duane) model
Homogeneous Poisson Process model
or if it comes to survival analysis:
Cox-Regression Analysis:

A good reference that covers these is the book Survival Analysis Using S.
A second approach is from perspective of processes control and quality control. A theoretical point of view is in in the book Reliability Modeling, Analysis And Optimization.


New MTURK SDK: Set Sandbox Endpoint?

Question: (In the past year, AWS updated the MTURK API, obsoleting the old API. As a result old SO threads on this topic are out of date.)
I have the MTURK SDK working to post live HITS. Now I'm trying to use the SDK to call the MTURK sandbox. The MTURK docs don't seem to document how to do this, and while I have been stepping through the code (e.g. public static function _apply_endpoint_provider) I haven't yet found the correct approach.
In the new MTURK SDK, what is the correct way to specify a sandbox endpoint?
Update:
The MTURK SDK seems to set the endpoint for me. It never asks me to set it and seems to build it itself. In partitionendpointprovider.php, I can see it is loading the sandbox endpoint to:
$data["partitions"][0]["services"]["mturk-requester"]["endpoints"]["sandbox"]["hostname"]
...but I don't yet see any way to tell the SDK to use that endpoint.
What is the correct way to tell the SDK that I'd like to use the sandbox endpoint?
Answer: Found it -- https://blog.mturk.com/tutorial-using-the-mturk-api-with-the-aws-sdk-for-php-472dc70dc4c3
$mTurk = new Aws\MTurk\MTurkClient([
     'version' => 'latest',
     'region'  => 'us-east-1',
     'endpoint' => 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'
 ]);

Use your own server's regions, of course.

New MTURK SDK: Set Sandbox Endpoint?


Como pegar dados de um input, fazer um cálculo e jogar em outro input?

Question: Gostaria de saber como pegar um valor de um input, fazer o cálculo e jogar o resultado em outro input. Exemplo: imc = peso x (altura)².E quando a pessoa colocar a altura e o peso nos inputs, o cálculo será feito e aparecerá no input do IMC.
Também tenho que realizar cálculos em outros campos, mas gostaria de uma ajuda pois não sei como fazer esses cálculos, se e em PHP mesmo ou JavaScript?
Segue o código abaixo:

    <input class="campo-form-c" type="text" name="pesoatual" placeholder="Peso Atual">

    <input class="campo-form-c" type="text" name="altura" placeholder="Altura">

    <input class="campo-form-c" type="number" name="idade" placeholder="Idade">

    <input class="campo-form-c" type="date" name="datan" placeholder="Data de nascimento">

    <input class="campo-form-c" type="text" name="medidab" placeholder="Medida do Braço" maxlength="5">

   <input class="campo-form-c" type="text" name="medidat" placeholder="Medida Tricipital" maxlength="5">

   <input class="campo-form-c" type="text" name="medidaabd" placeholder="Medida Abdominal" maxlength="5">

    <input class="campo-form-c" type="text" name="imc" placeholder="IMC" maxlength="4">

    <input class="campo-form-c" type="text" name="gorduratricpital" placeholder="Gordura Tricipital" maxlength="5">

    <input class="campo-form-c" type="text" name="circunferenciabraço" placeholder="Circunferência do Braço" maxlength="5">

    <input class="campo-form-c" type="text" name="circunferenciambraço" placeholder="Circunferência Muscular do Braço" maxlength="5">

Comment: Da pra fazer só em javascript sim. Da uma olhada nesse link: http://wbruno.com.br/javascript-puro/calculo-simples-entre-inputs-resposta-em-outro/ . E aqui o codigo funcionando: http://wbruno.com.br/examples/calc-simples/

Só adaptar para seus cálculos.
Comment: inclusive na net se vc pesquisar "calculo de imc em javascript" vc vai encontrar vários códigos prontos q tbm da pra vc adaptar, como esse por exemplo: http://www.emagrecerpravaler.com/wp-content/uploads/2017/02/calc.1-cod-html.txt
Answer: Por serem valores que serão digitados, o recomendável usar JavaScript para fazer o cálculo. No entanto, a fórmula do imc na sua pergunta está incorreta. O correto é:
imc = peso / (altura)² e não imc = peso x (altura)²

Fórmula: peso (em kg) dividido pelo quadrado da altura (em metros1).

Para jogar o valor do cálculo no campo name="imc", pode usar querySelector para pegar os valores dos campos name="pesoatual" e name="altura" e atualizar o resultado de forma dinâmica à medida que os valores forem sendo inseridos nos campos:

var peso = document.querySelector("input[name=pesoatual]");
var altu = document.querySelector("input[name=altura]");
peso.addEventListener("keyup", calcImc, false);
altu.addEventListener("keyup", calcImc, false);

function calcImc(){
   var peso_val = parseFloat(peso.value);
   var altu_val = altu.value;
   altu_val.match(/[,.]/) ? altu_val=parseFloat(altu_val.replace(",",".")) : altu_val=parseFloat(altu.value)/100;
   imc = (peso_val / (altu_val * altu_val)).toFixed(1); // "1" significa 1 casa decimal
   if(!isNaN(imc)){
      document.querySelector("input[name=imc]").value = imc;
   }
}

    <input class="campo-form-c" type="text" name="pesoatual" placeholder="Peso Atual">

    <input class="campo-form-c" type="text" name="altura" placeholder="Altura">

    <input class="campo-form-c" type="number" name="idade" placeholder="Idade">

    <input class="campo-form-c" type="date" name="datan" placeholder="Data de nascimento">

    <input class="campo-form-c" type="text" name="medidab" placeholder="Medida do Braço" maxlength="5">

   <input class="campo-form-c" type="text" name="medidat" placeholder="Medida Tricipital" maxlength="5">

   <input class="campo-form-c" type="text" name="medidaabd" placeholder="Medida Abdominal" maxlength="5">

    <input class="campo-form-c" type="text" name="imc" placeholder="IMC" maxlength="4">

    <input class="campo-form-c" type="text" name="gorduratricpital" placeholder="Gordura Tricipital" maxlength="5">

    <input class="campo-form-c" type="text" name="circunferenciabraço" placeholder="Circunferência do Braço" maxlength="5">

    <input class="campo-form-c" type="text" name="circunferenciambraço" placeholder="Circunferência Muscular do Braço" maxlength="5">

1 Embora a medida da altura oficial do cálculo do imc seja metros, para efeito de cálculo, o código acima também aceita valores em centímetros, o resultado será o mesmo.
Answer: Da pra fazer com Javascript mesmo.
Segue exemplo bem simples https://jsfiddle.net/s9mn5nvf/
Espero que ajude.


Diferença na declaração do Socket.io

Question: Estou começando a trabalhar com o Socket.io no Node.js, a dúvida por enquanto segue simples.
Usando meu exemplo abaixo.
Qual a diferença em usar socket.emit() e chat.emit()?
PS:*Espero que não tenha erro de sintaxe kkk.

var chat = io.of('/chat')
             .on('connection', function (socket) {
                 socket.emit('testOne', {
                    data: 'data'
                 });
                 chat.emit('testTwo', {
                    data2: 'data2'
                 });
             });
Answer: socket.emit irá emitir o evento para este socket específico, no caso algum cliente que está conectado e representa o socket.
Em chat.emit o evento é emitido para todos os clientes que estão conectados no namespace /chat (que é criado em io.of('/chat')).

Diferença na declaração do Socket.io


Finite sum & power series

Question:
After some algebra, I found the whole expression equal to 10^9(1+ 2*(11/10) +3*(11/10)^2+...+10(11/10)^9)
The expression in inside the bracket is similar to power series of (1-x)^2. But, I don't know how to get a finite sum of n terms of (1-x)^2 series.
Need a hint. (Just need a hint, I know it's too easy)
Comment: Did  you observe a simple AGP
Comment: Thanks. Got it. Love wikipedia.
Answer: There is this simple and neat result for the sum of a special arithmetico-geometric sequence:
$$\sum_{k=1}^n k\,\left(1+\frac{1}{n}\right)^k = n(n+1)$$
This can be easily verified from the expression for the sum of a generic arithmetico-geometric sequence. What is surprising, at least for me, is that given the amount of powers of fractions in the sequence, the summation result is an integer! In other words:
$$\sum_{k=1}^n k \, n^{n-k}\left(n+1\right)^k \equiv 0 \quad mod(n^n)$$
which I guess is by itself non trivial. Anyway, dividing your expression by $10^9$ gives exactly the above sequence with n=10 so the answer to your question is k=10$\cdot$11=110.
T. Hermsen

Finite sum & power series


is covariance matrix and eigen vector question

Question: is every covariance matrix 's eigenvector is orthogonal?
why symmetric matrix's eigenvector is orthogonal?
can you show some example? and the reason?
$$\Sigma {\bf U_i} = \lambda_i U_i$$
additional question) why first eigenvalue is the direction of covariance matrix?
and second eigenvalue(what is second eigenvalue?) is the 90 degrees of the first eigenvalue?
Comment: [This answer](http://math.stackexchange.com/questions/82467/eigenvectors-of-real-symmetric-matrices-are-orthogonal) on the math stackexchange site may help.
Answer: Every covariance matrix is symmetric, that is, $\Sigma^T=\Sigma$. Then eigenvectors corresponding to distinct eigenvalues are orthogonal (you left out the important qualifier!). Here is a simple algebraic proof.
Let $\Sigma=\Sigma^T$ be symmetric, with eigenvectors $x, y$ such that
$$ \Sigma x=\lambda x, \Sigma y=\mu y, \quad \lambda \not=\mu, \lambda \not=0. $$
$x$ and $y$ are orthogonal means that $x^Ty=0$. Now
$$ x^Ty = \left( \frac1\lambda \Sigma x\right)^T y = \frac1\lambda x^T \Sigma y =\\
   \frac1\lambda \mu x^Ty $$
By subtraction we have
$$ x^Ty - \frac\mu\lambda x^T y =\left( 1-\frac\mu\lambda\right) x^T y=0
$$ and since $\lambda \not=\mu$ necessarily $x^Ty=0$.
That is the standard proof, and more details is at https://math.stackexchange.com/questions/82467/eigenvectors-of-real-symmetric-matrices-are-orthogonal
For your second question, what do you mean by direction of covariance matrix?
Comment: You don't need to assume $\lambda\ne 0,$ suggesting there's a simpler demonstration.   Indeed, the *symmetry* of $\Sigma$ implies $$\lambda y^\prime x = y^\prime (\Sigma x) = x^\prime\Sigma y = x^\prime \mu y = \mu y^\prime x.$$ Therefore $$(\lambda-\mu)\, y^\prime x = 0,$$ whence $\lambda=\mu$ or $y^\prime x = 0,$ *QED.* (I see now that this is exactly the approach taken in the answer you link to.)  More importantly, it's worth remarking that nonzero eigenvectors with the *same* eigenvalues are not necessarily orthogonal.


Python: como servir uma página HTML programaticamente sem travar a execução

Question: Eu sei que é possível criar um servidor local em Python digitando na CLI python -m http.server. Posso também executar este comando de dentro de um script Python usando os.system. O problema é que isto trava a execução. Tem alguma maneira de servir uma página e permitir a continuação do programa?
Answer: Geralmente se usa Flask ou Django para essas finalidades, mas se for algo assim simples dá para fazer só usando threads:
from http.server import HTTPServer, SimpleHTTPRequestHandler
from threading import Thread

PORT = 8000  # pode escolher qualquer uma
server = HTTPServer(('localhost', PORT), SimpleHTTPRequestHandler)
server_thread = Thread(target=localhost_server.serve_forever).start()

A última linha vai iniciar o host imediatamente e o código que estiver em sequência será executado logo após da inicialização do servidor. server_forever trancaria a execução se não fosse posto numa thread.
Importante destacar que isto vai servir o conteúdo que está no working directory da execução atual. Normalmente este diretório é o mesmo em que está o arquivo Python que foi executado, mas há casos em que uma IDE pode interferir nele. Você pode descobrir o working directory usando os.getcwd() e alterá-lo usando os.chdir(diretorio), tendo em mente que ele não deverá ser alterado novamente enquanto durar o servidor. Para encerrar o servidor, basta executar server.shutdown().


Winforms c# outlook like Interface

Question: I have already asked the same question but in regards with MDI Application design. Now just for R&D purpose so that we can go with 2 solutions to our user. Can somebody plz help me out...
We are developing an OutLook Style Application using C# Winforms. In that application we are using Microsoft Table Control. Which is what we need to show our UI. In the left hand pane we have menu and in the right hand we are displaying our UserControl. Like CustomerManager. This UserControl is doing Adding, Updating, Deleting ect etc but we want to put the common action buttons, Like Add,Delete,Save on the top toolbar.
So far so good, Now what we need to acheve is regardless of UserControl. What ever UserControl is loaded in the MainForm's TableControl. When the save button is clicked it should process the data on that UserControl. Obviously we will write the logic of the Save Action on each UserControl.
Please help...
Regards
Shanx
Answer: I may advice you the Krypton Toolkit. You will write an Outlook style app in seconds.
Comment: It's an advice. You call it spam.
Comment: +1 to cancel out the negative vote. This might read like spam but it was a good suggestion (not knowing the OP was using another control set).
Comment: friends, I have asked the suggestions, not the components. By the way we are using DevExpress components already. And for this app we will also use DevExpress. For us there is no best component vendor available than Devexpress for Winform application.
Answer: For all who ended up here like me in search of a free toolkit: As Vulkanino suggested to use Krypton, I loooked it up.
This is now open source Freeware and can be found unter: Krypton Toolkit
Answer: Create a Base user control that contains your Add, Delete, Save methods and events. Then create every other functional control that inherits from the Base control.
When you action the main toolbar buttons, you can safely cast each user control in your given container, to the Base user control.
Some MSDN links you might want to read up on:
http://msdn.microsoft.com/en-us/library/44a9ty12(VS.80).aspx
http://msdn.microsoft.com/en-us/library/ms173149(VS.80).aspx

Winforms c# outlook like Interface


Problem of ending return statement on canActivate

Question: I have a problem when I use CanActivate method: error ts2366 "Function lacks ending return statement and return type does not include undefined" appears.
Following my code:
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      this.router.navigate(['/auth']);
    }
  }
}

I tried to add '| undefined' after boolean but an other error told me it was incompatible with CanActivate.
Do you have any idea to solve it ?
Thanks by advance for your help.
Comment: You are supposed to return either a `boolean` or a `UrlTree` from `canActivate`. If you return the UrlTree it will deal with the navigation for you, so you don't need to call `this.router.navigate` yourself (see https://angular.io/api/router/CanActivate)
Comment: @cdimitroulas So, if I understand, I need to return a ```this.router.parseUrl('/auth')``` in the second case and the navigate will be automaticaly done with this UrlTree ?
Comment: I believe so - I haven't actually worked with Angular so I'm basing this off what is written in the docs link I sent in my previous comment.
Comment: @cdimitroulas thanks for your answer, it is solved.
Comment: I'm going to add a proper answer to your question - if you could mark it as the correct answer I would appreciate it :)
Answer: You are supposed to return either a boolean or a UrlTree from canActivate. If you return the UrlTree it will deal with the navigation for you, so you don't need to call this.router.navigate yourself (see https://angular.io/api/router/CanActivate)
Your code might look like this:
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      return this.router.parseUrl('/auth');
    }
  }
}


Reloading  from backing bean doesn't seem to work

Question: I have this tree in my page:
<h:form id="form" >

    <h:panelGrid columns="4" id="panel">

                    <h:outputText value="#{myObject.label}" />

                    <f:setPropertyActionListener value="#{myObject}" target="#{mybean.selectedmyObject}" />

                <h:outputText value="#{myObjectAvailable.label}" />

    </h:panelGrid>

</h:form>

    <h:form id="formDialogmyObject" >

                <h:outputLabel for="idmyObject" value="ID myObject" />
                <h:outputText id="idmyObject" value="#{mybean.selectedmyObject.idmyObject}" />

    </h:form>

In my bean, method "cmdSaveSinglemyObjectItem" do this:
//business logic for update data into database about menu item and update bean...
RequestContext.getCurrentInstance().update("form");
RequestContext rc = RequestContext.getCurrentInstance();
rc.execute("PF('documentDialog').hide();");
rc.closeDialog(dialog);

Bean is updated correctly but tree component (id=tree1) isn't updated. View old value, but if I refresh page I view data updated...
Comment: Better include popup Window and use  `update="tree1"` I tried it previously it work for me.
Comment: I must use Primefaces...
Comment: Have you tried to use the same form for the dialog also?
Comment: @Diaboliko Who told you not use Primefaces? I told put popup code in another file and include it .
Comment: @Subodh Joshi: I will try but I prefer use same file for Dialog.
Comment: @David_Ware: if I use same form, the command button into dialog (id=cmdSaveSinglemyObjectItem) don't work, onlick nothing happened.
Comment: @Subodh Joshi: I tried to use a popup in another file. I set update="tree1" in Dialog commandButton but doesn't work... Any ideas?
Comment: Nothing happened? Is your backing method void, right? try to change your code:
Answer: You should update the whole tree and not just a specific subelement of it.
update=":form:tree1"

instead of your update=":form:tree1:treeNode1"


Strict inclusion in subdifferential sum rule $\partial{f(x)}+\partial{g(x)}\subseteq{\partial(f+g)(x)}$.

Question: I wish to find an example to show that the inclusion in the subdifferential sum rule
$$\partial{f(x)}+\partial{g(x)}\subseteq{\partial(f+g)(x)}$$
is strict. However, I have a problem understanding the way this inclusion is stated.
This inclusion in the subdifferential sum rule is taken from the book Convex Analysis by R. Tyrrell Rockafellar, Page 223, Theorem 23.8. This theorem says:

Let $f_1,f_2,\dots,f_m$ be proper convex functions on $\mathbb{R}^n$, and $f=f_1+f_2+\cdots+f_m$, then  $\partial{f_1(x)}+\cdots+\partial{f_2(x)}\subset{\partial{f(x)}}~~~\forall{x}$.

It also says if the domains of the $f_i$s have common point, then the inclusion turns into equality. From what I understand, if the domains of the $f_i$s do not have common point, then the strict inclusion should hold. One of the many examples that I tried was the pair $\sqrt{1-x}$ and $\sqrt{x-2}$. These two functions do not have any point in common in their domains. However, I do not understand how we can add two functions whose domains do not overlap.
I have two main issues:

Intuitively, the subset sign should be the other way around. In the last part of the answer to this question, there is an example where the inclusion is true for the case where the subset sign is the other way around. In addition, the example is in contradiction to the inclusion statement in the question.

This might be an easy question, but how can we add two functions whose domains do not intersect?

Any insight and example that can help me understand this are really appreciated!
Answer: Re 2: If domains don't overlap, then the sum function is $+\infty$ everywhere.
Re 1: Consider two disks in $\mathbb{R}^2$ that touch in exactly one point. To be concrete,
$$A = \text{ball of radius $1$ centred at $(-1,0)$ and
$B=$ ball of radius $1$ centred at $(1,0)$}.$$
Note that $A\cap B = \{(0,0)\}$.
Set $z := (0,0)\in\mathbb{R}^2$. Now define
$$ f(x) = \begin{cases} 0, &\text{if $x\in A$;}\\
+\infty, &\text{else}
\end{cases}
\quad\text{and}\quad
g(x)= \begin{cases} 0, &\text{if $x\in B$;}\\
+\infty, &\text{else.}
\end{cases}$$
Note that
$\partial f(z)=\mathbb{R}_+(1,0) = \{(\rho,0)\,|\,\rho\geq 0\}$ and
$\partial g(z)=\mathbb{R}_+(-1,0) = \{(\rho,0)\,|\,\rho \leq 0\}$; thus,
$$\partial f(z)+g(z) = \mathbb{R}_+(1,0) + \mathbb{R}_-(1,0)
= \mathbb{R}\times\{0\}.$$
Moreover,
$$ (f+g)(x) = f(x)+g(x) = \begin{cases} 0, &\text{if $x\in A\cap B=\{(0,0)\}$;}\\
+\infty, &\text{else.}
\end{cases}
$$
Hence
$$\partial(f+g)(z) = \mathbb{R}^2$$
which is a strict superset of $\mathbb{R}\times\{0\}$.
Comments.
(1) The sum rule is true when the underlying space is just $\mathbb{R}$ as long as the domains of the subdifferential operators intersect. It fails for merely having the domains intersect, see example by @gerw below.
(2) The sum rule can fail as shown above even when the domains do intersect nontrivially.
(3) Finally, the sum rule holds when the domains overlap sufficiently (see Rockafellar's book for details involving say the relative interior or polyhedral functions).
Comment: Can you please explain why the sum function is the indicator function $\mathbbm{1}{p}$ and how do you define your inclusion in the indicator function you are referring to as $\mathbbm{1}{p}$?
Comment: Thanks for clarification! Just to make sure, by $\mathbb{R}_ (1,0)$ you are excluding these two points? Also, if you have seen the post I linked, there is a counter example to this theorem. How should we justify that?
Comment: @NBS I've added more explanations of the notation. The post you linked to shows that the inclusion you have is *always true* but the example here shows that *equality may fail*.
Comment: Thank you so much!
Comment: The sum rule can already fail in one dimension if the domains intersect in exactly one point, see my answer.
Comment: @gerw is correct. I have modified my remark (1) accordingly.
Comment: @max_zorn. There is no condition on the domain of the sum rule in the theorem I mentioned.
Answer: Here is an example in $\mathbb R^1$: Define
$$
f(x) =
\begin{cases}
-\sqrt{x} & \text{for } x \ge 0, \\
+\infty & \text{for } x < 0,
\end{cases}
$$
and
$$
g(x) =
\begin{cases}
0 & \text{for } x \le 0, \\
+\infty & \text{for } x > 0.
\end{cases}
$$
Thus, $f+g$ is the indicator function of $\{0\}$.
Then,
\begin{align*}
\partial f(0) &= \emptyset, \\
\partial g(0) &= [0,\infty), \\
\partial f(0) + \partial g(0) &= \emptyset, \\
\partial (f+g)(0) &= \mathbb R.
\end{align*}
Comment: In your example, $f_2$ is not convex.
Comment: Excellent example! You can also use $g(x) = f(-x)$ for which $\partial g(0)=\emptyset$.
Comment: @gerw Thank you for the example! What still keeps me confused is that a theorem should be always true. This theorem, however, has a counterexample. The one in the answer to the question I linked in my question. Can you answer this question, please?
Comment: @NBS Can you rephrase what bothers you? You mention a theorem that should be true but there is a counterexample. If you talk about the inclusion in the linked post, then indeed this inclusion is always true (and there is no counterexample).
Comment: @max_zorn For the case $f_1(x)=\max{0,x}$ and $f_2(x)=-f_1(-x)$. at $x=0$, $\partial{(f_1+f_2)}(0)=\{1\}$, and $\partial{f_1}(0)+\partial{f_2}(0)=[0,2]$. Is it not a counterexample to the theorem? I took this example from [link](https://math.stackexchange.com/questions/2188858/sum-of-subgradients-belongs-to-subgradient-of-sums).


Prove $||a| - |b||$ is less than or equal to $|a-b|$

Question: I was given the hint to split it into two cases ($|a| - |b|$ being positive and negative) and then use the triangle inequality. However, since the triangle inequality says that $|a+b|$ is less than or equal to $|a| + |b|$, so I don't see how I can use that to help since I'm dealing with subtraction. I've tried using the definition of absolute value, and I was able to find that $||a| - |b||$ = $|a| - |b|$ in my first case, but I couldn't do much with that.
Comment: See also [this question](http://math.stackexchange.com/questions/127372/reverse-triangle-inequality-proof) and other posts [linked there](http://math.stackexchange.com/questions/linked/127372).
Comment: You may change the subtraction $x-y$ into the addition $x+(-y)$ (this is the _definition_ of subtraction, after all), which should enable the triangle inequality.
Answer: You may write
$$
x=x-y+y
$$ giving, by the triangle inequality,
$$
|x|\leq |x-y|+|y|
$$ or

$$
|x|-|y|\leq|x-y|
$$

then do the same starting this time with $$y=y-x+x.$$
Comment: Instead of your last step we can do this : after getting $|x|-|y| \le |x-y|$, we can just swap $x$ & $y$ in it to get $|y|-|x| \le |y-x|=|x-y|$
Comment: @VikrantDesai Right, but "swapping" $x$ and $y$ is fact doing the same thing as starting with $y$.
Comment: Yes I know that. :D
Answer: You may prove $(|a|-|b|)^2 \leq (a-b)^2$, since $2|a||b| \geq 2ab$. By taking positive absolute values, you obtain $||a|-|b|| \leq |a-b|$.


MIssing 'Drush configuration' and 'Php configuration' when running 'Drush status'

Question: If a run the method 'drush status' in the terminal I see that the values for  'Drush configuration' and 'Php configuration' are missing.
It give me not problem at all. But is this correct?
Look the capture:
I use the free version of MAMP.
Answer: One of my colleagues has MAMP installed and that's what his Drush status looks like too.
I'm using the build of Apache built in to OSX and the only difference I see is that the PHP configuration is filled in:

Like you, neither my colleague or I suffer any problems with these settings missing so I wouldn't worry too much about it.
Comment: thanks clive, as you say I'll pay no attention to this.


How to store checks of gradient algorithm in a matrix using R?

Question: I would like to check different gradient algorithms. For example:
 fr <- function(x) {   ## Rosenbrock Banana function
         x1 <- x[1]
         x2 <- x[2]
        print(c(x1,x2))
         100 * (x2 - x1 * x1)^2 + (1 - x1)^2
     }
optim(c(-1.2,1),fr,method="BFGS")

prints to the screen the values at which the RBF has been evaluated.
How can I store these values in a matrix ? (instead of just printing them to the screen)
Answer: Use the function capture.output:
cc<-capture.output(vv<-optim(c(-1.2,1),fr,method="BFGS"))
t(sapply(strsplit(gsub(" +"," ",cc)," "),function(l)as.numeric(l[2:3])))

The variable vv is used so that the result of optim will not be printed only your calls to the function. Each call to the function results in one element of cc. Then I strip extra spaces, so that I can split the strings with the space. Afterwards you simply select what is needed.
This solution will work if optim produces errors, but I think it is not very hard to adapt the code to guard against that.
This is of course only the quick hack. For more complicated solutions you will need to delve into the code of optim.
@onestop suggested using sink, it is more simple:
sink("bu.txt")
vv<-optim(c(-1.2,1),fr,method="BFGS")
sink()
read.table("bu.txt")

Note the additional sink, so that the output is diverted again to the console.
Comment: @onestop, why did you delete your answer? I was just about ready to upvote it.
Comment: (+1) Let's say my vote goes to both of you :-)


Efficiently generate 2^n combinations (/w java)

Question: I'm trying to generate all 2^n as efficiently as possible (and save them to an array), like
    0001
    0010
    0011
    etc.
Where n could be up to 15.
Here is my code:
public static void main(String args[]) {
    final long startTime = System.nanoTime();
    final int N = 15;
    int m = (int) Math.pow(2, N) - 1;
    int[][] array = new int[m][N];
    int arrLength = array.length;

    for (int i = 0; i < arrLength; i++) {
        String str = String.format("%" + N + "s", Integer.toBinaryString(i + 1)).replace(' ', '0');
        for (int j = 0; j < N; j++) {
            array[i][j] = Character.getNumericValue(str.charAt(j));
        }
    }
    final long duration = System.nanoTime() - startTime;
    double sec = (double) duration / 1000000000.0;
    System.out.println(sec);
}

Any suggestion on how i can do this faster?
As of now, my timer says it takes ~0.1 to ~0.12
Comment: 1) If you want `2^n` combinations, why do you create array with size `2^n-1`? --- 2) Since `m` is already the array size, `arrLength = array.length` is rather redundant. --- 3) `Math.pow(2, N)` would be better written as `1 << N`. --- 4) When you divide a `long` value with a `double` value, the `long` value is automatically [promoted](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.6.2) to `double`, so no need to cast it.
Comment: @Andreas Thanks for the feedback, i forgot to mention that i wanted to skip the first combo (0000)!
Answer: String processing tends to be slow (typically requires loops and allocations). You can just shift the interesting bit to position 0 instead, then cut off higher bit using bitwise and with 1.
for (int i = 0; i < arrLength; i++) {
    for (int j = 0; j < N; j++) {
        array[i][j] = (i >> j) & 1;
    }
}

p.s. I have left out adding 1 to i, wasn't sure if this was intended in the original code, should be straightforward to add as needed.
Comment: Thanks alot! Exactly what i needed (as you say str processing takes time)! yes it was intended! Thanks again!
Answer: My most efficient way would be by not generating them at all, which roughly takes... 0 nanoseconds.
These strings are the textual representation of all integers from 0 to 2^n-1, for which enumeration is no mystery. There is no need to store them (in an array), as the keys would be the same as the indexes.
If you have compelling reasons to process them as strings, you can perform the conversion when required, with you own routine or with toBinaryString.
Depending on your application, f.i. string lookup, another option can be to turn the given string to its integer value. If the goal is to check presence/absence of items in a given combination, binary masks will do an effective job.


Duvida sobre o jTextArea.append (adicionar o valor da variavel 'area' ao BorderLayout) - Java

Question: Estou com um problema numa linha de código, nesta linha que está sublinhada na imagem, dá-me um erro que diz que as coordenadas x1, y1, x2, y2 tem de ser estáticas, acontece que esta aplicação consiste em desenhar um rectângulo com o rato, logo o seu tamanho é indefinido, e preciso de calcular a sua área e meter na parte debaixo da BorderLayout, gostaria de saber como o posso fazer.
Linha de código que está a dar erro e que vos falo:

Aqui está a função que calcula a Area:

Aqui é onde está a inicialização do objecto em causa (RectanguloCheio):

Aqui está de onde vem as coordenadas x1,y1,x2,y2 (são todas do tipo inteiro):

Para quem prefere o que esta em imagens em codigo:
Linha de código que está a dar erro e que vos falo:
public static void main(String[] args) {
    Editor e = new Editor();
    JTextArea jTextArea = new JTextArea();
    PointerInfo a = MouseInfo.getPointerInfo();
    Point b = a.getLocation();
    int x = (int) b.getX();
    int y = (int) b.getY();

    e.add(jTextArea, BorderLayout.SOUTH );
    e.setVisible(true);
    e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //jTextArea.append("(x,y) = ("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");

    while (true) {
    jTextArea.append("(x,y) =("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+") ");
        try
        {
            Thread.sleep(30);
            jTextArea.setText("");
        }
        catch (InterruptedException e3)
        {
            e3.printStackTrace();
        }
    }

}

Aqui está a função que calcula a Area:
 @Override
public void setCoordenadas(int x1, int y1, int x2, int y2) {
    p.x = Math.min(x1, x2);
    p.y = Math.min(y1, y2);
    largura = Math.abs(x1-x2);
    altura = Math.abs(y1-y2);
    area = largura * altura;
}

public int setCoordenadasB(int x1, int y1, int x2, int y2) {
    p.x = Math.min(x1, x2);
    p.y = Math.min(y1, y2);
    largura = Math.abs(x1-x2);
    altura = Math.abs(y1-y2);
    area = largura * altura;
    return area;
}

Aqui é onde está a inicialização do objecto em causa (RectanguloCheio):
bRetanguloCheio = new JButton ("RetânguloCheio");

    pBotoes.add(bRetanguloCheio);

    ActionListener acRetanguloCheio = new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            r = new RetanguloCheio();
            r.setColor(cor);
        }
    };
    bRetanguloCheio.addActionListener(acRetanguloCheio);

Aqui está de onde vem as coordenadas x1,y1,x2,y2 (são todas do tipo inteiro):
@Override
public void mousePressed(MouseEvent e) {
    x1 = e.getX();
    y1 = e.getY();
    mousePressionado = true;
}

@Override
public void mouseDragged(MouseEvent e) {
    x2 = e.getX();
    y2 = e.getY();
    r.setCoordenadas(x1, y1, x2, y2);
    r.setCoordenadasB(x1, y1, x2, y2);
    pEdicao.repaint();
}

Se alguém me souber ajudar agradecia, obrigado.
Comment: De onde vem essas variaveis x1, x2, y1 e y2? O que á variavel r? Ela é iniciada dentro do main? Parece que o código postado não está completo.
Comment: Já editei a minha publicação, apenas estou a tentar fazer com que haja uma maior compreensão da minha duvida, visto que ja fim um tópico apenas com código e algumas pessoas não o entenderam.
Obrigado, caso me possa ajudar ou saiba alguém, agradeço.
Comment: Obrigado pela sugestão, já adicionei as informações pedidas.
Comment: Pelo menos pra mim, ainda não está claro de onde vem as variaveis que falei, da linha do erro. Eu vi o que você salientou em negrito, mas o código em volta da linha do erro não está claro de onde vem as variaveis que citei. Sugiro que dê uma lida em [Como criar um exemplo Mínimo, Completo e Verificável](/help/mcve)
Comment: o x1, y1, x2, y2 são coordenadas que vem do getx() e do gety(), que sao valores obtidos pelo rato, ao selecionar um ponto e arrastar o rato, ele vai fazer um rectangulo, a única coisa que quero é calcular a area desse rectângulo a medida que o rectângulo está a ser criado.
Answer: Este é o código utilizado na função main, em que faz a chamada a função mostrarInfo() de cada class, o meu projecto tinha varias figuras, mas em questão na minha pergunta estava a figura rectângulo, o código colocado na função main é:
public void textoSul () {
        Thread t = new Thread(new Runnable(){
            @Override
            public void run() {
                while (true) {
                    info.setText("(x,y) =("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");
                    if(r != null && r.p.x != 0) {
                        info.append (r.mostrarInfo());
                    }
                    else if (lista.size()>0) {
                        info.append(lista.get(lista.size()-1).mostrarInfo());
                    }
                    try
                    {
                        Thread.sleep(100);
                        info.setText("");
                    }
                    catch (InterruptedException e3)
                    {
                        e3.printStackTrace();
                    }
                }
            }

        });
        t.start();
    }

NOTA: Este código, mostra as coordenadas do rato da tela toda e mostra as informações das figuras apenas no momento em que começarem a ser desenhadas.

O código colocado dentro da class Rectângulo é:
@Override
    public String mostrarInfo() {
        return (" Area = " +Area() +" Perimetro = " +Perimetro()+
                " Ponto Inicial = " +p.x + "," +p.y +" largura = " + largura +" altura = "+altura);
    }

NOTA: Com este código são mostradas as informações como a Area o Perímetro, o Ponto Inicial a Largura e a Altura do Rectângulo.
  Para que isto aconteça é necessário ter pré-definido as funções correspondestes à Área e restantes informações.

Caso alguem tenha duvidas de como fazer essas funções ou duvidas em como mostrar estas informações em outras figuras pode consultar o seguinte link: soeiromass GitHub, os ficheiros java estão localizados na directoria: "Editor-GeometricalFigures/src/editor/".


How to calculate p values in logistic regression with gradient descent algorithm

Question: In logistic regression, the gradient descent algorithm for calculating coefficients can be
described this way:
Until convergence, do
$$
  \beta := \beta + \alpha
  \frac{\partial L}{\partial \beta}
$$
where L is the log likelihood function.
Coefficients can be got quite easily here, but how can I get the p values with this algorithm?
Answer: The answer provided by @user43310 is generally correct, but incomplete, as @WHuber pointed out.
Once you've declared the algorithm to have converged, compute the Hessian $\textbf{H}$, which effectively tells you how "peaked" the parameter surface is at some parameter values. The matrix $(-\textbf{H})^{-1}$ is the variance-covariance estimates of the parameters at their (approximate) maxima. Therefore, the vector $\sqrt{\text{diag(}(-\textbf{H})^{-1}{)}}$ is the estimate of the standard error of each parameter value at its maximum. Under the assumption that the sampling distribution of the parameters is approximately normal in the limit of infinite sample size, then we test the hypothesis that the parameters are deviates from a normal distribution with mean zero and s.d. given by this procedure, e.g. that the parameter $z$ satisfies $|z|\ge 1.96\text{se}$ at a typical level. Alternatively, one can compare the quantity $$\frac{(\hat{z}-z_0)^2}{\text{var}(\hat{z})}$$ to a $\chi^2$ distribution with degrees of freedom determined from the number of observations less the number of parameters estimated.
More information on this method of determining the variance of parameter estimates can be found in Gary King, Unifying Political Methodology, pp. 89-90.
As @gung writes, this approach is called a Wald test. Asymptotically, it is equivalent to the likelihood ratio test. However, the Wald test is sensitive to the parameterization, while the LRT is not: any monotonic transformation of $z$ will work for the LRT.
As an added bonus, the wiki link currently cites professor & CV contributor Frank Harrell in several places, which I think is neat.
Comment: $H$ is Hessian of the log likelihood function $L$, right?
Comment: That's correct. And I just found the citation I was looking for; it's now recorded in the answer.
Answer: Compute the Hessian evaluated at the obtained coefficients.  Then negate the Hessian, invert it, and thats the variance-covariance matrix of the coefficients.
Comment: ...And how are the p-values obtained?  (Perhaps more importantly, when can this approach--which is *approximate*--be expected to work and why?)


Complex Integral with respect to Arc Length

Question: The exercise is to prove that for $0<\rho\neq|\alpha|$,
$$\int_{|z|=\rho}{\frac{|dz|}{|z-\alpha|^2}} = \frac{2\pi\rho}{|\rho^2-|\alpha|^2|}$$
I tried making a substition where $z=\rho e^{it}$, $t$ goes from $0$ to $2\pi$, and this leads to the integral $\int_0^{2\pi}\frac{\rho}{\rho ^2 + |\alpha|^2 -2\rho Re(\bar{\alpha}e^{it})}dt$. But that's somehow cumbersome to solve, if solvable at all.
Is there a simpler way? It looks like Cauchy's integral formula, but the $|dz|$ doesn't let me use it directly.
Answer: On the circle $\lvert z\rvert = \rho$, with the parametrisation $z = \rho e^{it}$, we have
$$\lvert dz\rvert = \rho\,dt = \rho\, \frac{dz}{iz}.$$
So you can write the integral as
$$\rho\int_{\lvert z\rvert = \rho} \frac{dz}{iz(z-\alpha)(\overline{z} - \overline{\alpha})}.$$
This can be transformed into a form where the residue theorem is applicable by noting $\lvert z\rvert^2 = \rho^2$ on the circle.


How to do simple subtraction in Computed Field?

Question: I'm trying to calculate the price difference between old price and new price, and if the price has dropped to display by how much, both Nominally and in Percent.
So, basically these are 2 simple formulas that should look like this:

NOMINAL PRICE DROP = field_price_original - field_price_new
PERCENTAGE PRICE DROP =  ( (field_price_new - field_price_original) /
  field_price_original ) * 100

I tried setting this up through Rules (unsuccessfully), but it seems that doing it through Computed Field will not be so heavy on the server.
Using Computing Field I have the following formula:

$entity_field[0]['value'] =
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_price_original'))) -
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_price_new')));

The number is set as float, 10.2.   But for some reason it doesn't work.
Can someone please help and provide the correct syntax for Computed Field?
Answer: As per the documentation of computation field module to calculate the difference of two fields you need to use the PEAR:
<code>$path = '/pathToPearsParentDirectory/pear/PEAR';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'PEAR.php';
include_once "Text/Diff.php";
include_once "Text/Diff/Renderer.php";
include_once "Text/Diff/Renderer/inline.php";

$diff = &new Text_Diff('auto', array(array($node->field_nameOfOneFieldToCompare[0]['value']), array($node->field_nameOfOtherFieldToCompare[0]['value']))); $renderer
= &new Text_Diff_Renderer_inline();

$node_field[0]['value'] = $renderer->render($diff);
</code>
More info about it available here http://arencambre.com/blog/2009/05/17/how-i-got-field-diffs-working-with-drupal-pear-text_diff-and-dreamhost
Comment: @drupalina Has the above solution worked for you, or if you found some better solution than please share. Thanks!!
Answer: <code>$entity_field[0]['value'] = $entity->field_price[LANGUAGE_NONE][0]['value'] - $entity->field_cost[LANGUAGE_NONE][0]['value'];
</code>
Comment: If it's an answer to the question please provide some description.
Comment: Also, please avoid encouraging people to use the field arrays directly like that. [field_get_items](https://api.drupal.org/api/drupal/7/search/field_get_items), as used by the OP, is helpful here.


Where does Visual Studio Code store information about enabled extensions per workspace?

Question: Visual Studio Code has the option to disable extension globally and enable it only for specific workspace.
Where is this settings saved? In which file exactly?
Locations where I checked but couldn't find it are:

user settings file: %APPDATA%\Code\User\settings.json
workspace settings file (e.g., for my single-folder project it is located in .vscode/settings.json)
extensions installation folder: %USERPROFILE%\.vscode\extensions

Where is this setting?
Comment: maybe in one of these locations, https://code.visualstudio.com/api/extension-capabilities/common-capabilities#data-storage
Comment: do you maybe know are these storage data stored in some file that I can view? (note: I have no experience with vs code extension development)
Answer: Visual Studio Code stores that information in:
Windows: %APPDATA%\Code\User\workspaceStorage
Linux: ~/.config/Code/User/workspaceStorage
macOS: ~/Library/Application Support/Code/User/workspaceStorage
Each subdirectory contains three files: workspace.json, state.vscdb, and state.vscdb.backup.
workspace.json is a JSON file that contains the URI of the workspace folder. Example:
{
  "folder": "file:///c%3A/Users/josia/MEGA/Projects/Programming%20Languages/Python/JSON%20Serialize"
}

state.vscdb (and state.vscdb.backup) are SQLite3 files that contain the workspace information that you are looking for. They can be opened with an SQLite viewer/editor such as DB Browser for SQLite.
Comment: Also, the relevant fields in the database are `extensionsIdentifiers/disabled` and `extensionsIdentifiers/enabled`.  Note that on Linux, I had to close ALL instances of VSCode (not just the workspace I was editing) in order for edits to those files to be picked up.
Comment: If this is the correct answer, @mlst should have accepted. I came to this thread because I'm looking for an easy way to set the desired extensions for a workspace. It's easy to set Recommended Extensions (https://code.visualstudio.com/docs/editor/extension-marketplace#_workspace-recommended-extensions). The problem is that we need to manually get the list of extensions IDs from each extension. I was looking for a list in JSON format. I'm sure a utility can be created to query the state db files, and save the result in text suitable for copy/paste.
Comment: `$HOME/.config/Code/User/workspaceStorage` doesn't exist for me, using `code-insiders-1.88.0-1710157206.el8`.


Are you allowed unlimited challenges in a hockey game?

Question: In hockey, they often challenge penalty calls, goals, etc.
Sometimes a goal is called back, sometimes it's awarded. Are you allowed to challenge everything? Why don't they often challenge offside calls? What stops a coach challenging every call against his team, just in case it gets called back?
Answer: There are no challenges in the NHL.  All replays are automatic: goals are reviewed by the video judge, with help from the war room in Toronto.  Coaches do not have the ability to initiate replays in any form.  Penalties are never reviewable, unless the timing relates to a goal.  All goals are reviewed (at least cursorily) by the Video Goal Judge, and further review may be undertaken if he or the referees determine it necessary.
This is explained in the NHL Official Rules, where it lists the jobs of the Video Goal Judge (38.1):

(i)  He will review replays of disputed goals when requested to do so by the Referees.
(ii)  He will review replays of disputed goals when he observes an incident that was undetected by on-ice officials.

It later mentions that he reviews all goals:

38.2 Goals – Every goal is to be reviewed by the Video Goal Judge.

The review may not be in all that much detail, and may be short enough to not delay the game; it also may be in more detail and may slightly or significantly delay the game, if needed.  This is somewhat covered in the rules.
Finally, it lists that the Video Goal Judge may also determine the correct game clock setting, which appears to be the only non-goal related act that is subject to replay.
Comment: so why are some goals reviewed and others are not? who decides?
Comment: The referees request the Video Judge to do so.  I'll clarify in the answer.
Answer: As of the 2015-16 season, NHL coaches are given one timeout per game. There are two scenarios where a challenge is allowed:

A suspected offside occurs before a goal. The coach can challenge the play stating that the play is offside.
Goaltender interference occurs, preventing the goalie from being able to make the save, resulting in a goal.

In either case, if the play is deemed fine, the team loses their timeout and ability to make future challenges.
On the other hand, if a challenge is successful, the team keeps their timeout and can make later challenges. As well, the clock gets set back to the end of play, or to when the offside occurred.
If a team uses their timeout, they also lose their ability to challenge future plays.
The play only gets to this process if it gets through the quick review that happens on every goal, as described in this earlier answer, however that automatic review doesn't include offside review and is very brief.


View contextual filter only applies to first filter AND/OR group

Question: I have a view that returns two different content types in its results. Each content type needs different filters, so I group them using OR and AND. See below:

This view represents a category page and filters the results using a contextual filter. Both content types share the same category field. However, the contextual filter (a taxonomy term based on the URL) only applies to the first group of filters before the "OR". This shows up in the query it generates:
SELECT DISTINCT node.nid AS nid, node.created AS node_created, node.title AS node_title, node.sticky AS node_sticky, node.nid AS node_nid, 'node' AS field_data_field_image_node_entity_type, 'node' AS field_data_field_duration_node_entity_type, 'node' AS field_data_field_slug_node_entity_type, 'node' AS field_data_field_stickybit_expiretime_node_entity_type, 'node' AS field_data_field_ribbon_color_node_entity_type, 'node' AS field_data_field_ribbon_text_node_entity_type, 'node' AS field_data_field_blog_thumbnail_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_segment} field_data_field_segment ON node.nid = field_data_field_segment.entity_id AND (field_data_field_segment.entity_type = 'node' AND field_data_field_segment.deleted = '0')
LEFT JOIN {field_data_field_submitted} field_data_field_submitted ON node.nid = field_data_field_submitted.entity_id AND (field_data_field_submitted.entity_type = 'node' AND field_data_field_submitted.deleted = '0')
WHERE (( (node.type IN  ('story')) AND (node.status = '1')
        AND (field_data_field_segment.field_segment_value IS NULL )
        AND (field_data_field_submitted.field_submitted_value NOT IN  ('2'))
        AND (node.nid IN
          (SELECT tn.nid AS nid FROM {taxonomy_index} tn
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th ON th.tid = tn.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th1 ON th.parent = th1.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th2 ON th1.parent = th2.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th3 ON th2.parent = th3.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th4 ON th3.parent = th4.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th5 ON th4.parent = th5.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th6 ON th5.parent = th6.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th7 ON th6.parent = th7.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th8 ON th7.parent = th8.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th9 ON th8.parent = th9.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th10 ON th9.parent = th10.tid
          WHERE ( (tn.tid = '205') OR (th1.tid = '205') OR (th2.tid = '205')
            OR (th3.tid = '205') OR (th4.tid = '205') OR (th5.tid = '205')
            OR (th6.tid = '205') OR (th7.tid = '205') OR (th8.tid = '205')
            OR (th9.tid = '205') OR (th10.tid = '205') )
        ))
      )
      OR ( (node.type IN  ('blog')) AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC, node_nid DESC
LIMIT 12 OFFSET 0

You can see that the contextual filter is applied only to the first group, not both. Is there any way to get the contextual filter to apply to both?
Drupal 7.8
Views 7.x-3.0-rc1
Views UI 7.x-3.0-rc1

Comment: My initial reaction to any bug in outdated modules is to update the modules. Did you try it? Drupal, CTools and Views have progresses since those releases.
Comment: That's something I thought of and upgrading all of this is in the roadmap for us. But we aren't ready for that right now. Can anyone confirm that this is fixed in later versions?
Answer: Updating Drupal to 7.28 and the Views module to 7.x-3.7 solved the problem, as barraponto suggested it might.


when I want to change a ComboBox of datagridview, its automatically change all other combos of same DataGridView

Question: First of all, I must mention that I have seen this question, but it didn't help me to fix my problem.
According to my previous question, I saved my DataGridView to an XML file. Now I am going to fill the DataGridView when I load the window form using the data stored on the XML file.
My problem is that when I want to set the value of one ComboBox based on the stored data, the other ComboBox's value changes too. I want to set each ComboBox's value separately.
My code is as follows :
private void WindowSelection_Load(object sender, EventArgs e)
        {
            dataGridSource = DeserializeFromXML();
            foreach (WindowHolder obj in dataGridSource)
            {
                int index = dataGridViewWindowSelection.Rows.Add();

                DataGridViewComboBoxColumn combo2 = new DataGridViewComboBoxColumn();
                combo2 = (DataGridViewComboBoxColumn)dataGridViewWindowSelection.Rows[index].Cells["Reader"].OwningColumn;
                combo2.DataSource = readerSource;

                int readerSourceIndex = findReaderSourceIndex(obj.reader);
                if (readerSourceIndex != -1)
                {
                    combo2.DefaultCellStyle.NullValue = readerSource[readerSourceIndex];
                }
                else
                {
                    combo2.DefaultCellStyle.NullValue = readerSource[0];
                }

                dataGridViewWindowSelection.Rows[index].Cells["Location"].Value = obj.location;
                dataGridViewWindowSelection.Rows[index].Cells["AlwaysOnTop"].Value = obj.alwaysOnTop;
                dataGridViewWindowSelection.Rows[index].Cells["AlwaysShow"].Value = obj.alwaysShow;
            }

        }

Answer: Do you mean the line where you're changing combo2.DefaultCellStyle?
This happens because combo2.DefaultCellStyle is a reference to the default cell style of all the combos, so you're not changing this one combo - you're changing the common default style.
If you want the style of this combo to be different from the default one (and from the other combos' style), you should probably create a separate style and set it as the style of combo2.
I guess the statement should look something like combo2.DefaultCellStyle = ... or combo2.SetDefaultCellStyle( ... )
Comment: I have combo2.DefaultCellStyle but could you please tell I must set it to what value?
Comment: You should create a new cell style based on the current one, and set combo2.DefaultCellStyle to refer to the new style.


Symbolic Dynamics - Prove Different Full Shifts are Not Conjugate

Question: The full shift over an alphabet $A$ is the set of all bi-infinite sequences built from characters belonging to $A$. The full $n$-shift is the full shift over some alphabet of size $n$.
The exercise I was asked to solve is to tell whether the $2$-shift is conjugate to the $3$-shift, and whether there exists a factor map from the full $2$-shift to the full $3$-shift.
Searching the web I found (in Scholarpedia) that the topological entropy is invariant under isomorphism of symbolic dynamics. The topological entropy of the full $n$-shift is $\log (n)$ (as described in the link and not hard to see), therefore these two dynamics are not conjugate, and moreover, an additional result states that a factor map cannot increase the entropy, therefore a factor map from the full $2$-shift to the full $3$-shift cannot exist.
Can you help in finding a more basic way of proving that these dynamics are not conjugate? I don't think this was the method implied in the exercise - we haven't reached topological entropy in the course yet.
Answer: You can count fixed points.
For the full $n$-shift, the number of fixed points is $n$, one per symbol. Since the number of fixed points is an invariant of topological conjugacy, the full $m$ and $n$-shifts are not conjugate when $m \ne n$.
As noted in the comment of @DanRust, under a factor map it is possible for the number of fixed points to go up or down. I don't have a particular example at hand, but one idea is that a period 2 orbit can be mapped to a single point. So this method does not seem useful for the question about factor maps.
Comment: You just need to show that the image of a fixed point under a factor map is a fixed point. Then just use the fact that a factor map is surjective.
Comment: Sorry actually the statement is false! The map from any shift space to the single point system is a factor map, so factor maps can in fact decrease **or** increase the number of fixed points (take a sturmian shift for examples to see how the number of fixed points can increase from $0$ to $1$). What you should really be using is the fact that a full topological conjugacy preserves the number of fixed points (and in general the number of points of period $p$ for any given $p$). Lee should edit his post.
Comment: Entropy is the easiest method for showing that imo. Entropy is non-increasing under factor maps.
Comment: Thanks Dan, that was careless of me. I'm removing that part.
Comment: This may be simple, but why a factor map cannot increase the number of fixed points?
Comment: @DanRust (or anyone) please help, I still can't figure this out. A fixed point really goes to a fixed point: if $\phi$ is the factor map, $\sigma_X$ is the shift function in the domain set, $\sigma_Y$ the shift function in the codomain set, and $x \in X$ a fixed point, then $\sigma_X(x)=x$, and $\sigma_Y(\phi(x))=\phi(\sigma_X(x))=\phi(x)$ and therefore $\phi(x)$ is a fixed point. But, why a non-fixed point cannot go to a fixed point? I don't see how surjectiveness helps...
Comment: @DanRust: OK, thanks. Do you know than a method to show that there cannot exist a factor map from the full $2$-shift to the full $3$-shift?
Comment: Thank you both @DanRust and Lee Mosher. If you come up with an idea about the factor map please post it here :)
Answer: The factor part of the question has the following entropy-free solution:
Assume by contradiction that $$\phi \quad \colon\quad  \text{full shift over \{v,w\}} \to \text{full shift over \{x,y,z\}}$$
is a factor map. By the Curtis–Hedlund–Lyndon theorem, $\phi$ is induced by a sliding block code with some memory $m$ and anticipation $a$:
$$\Phi \quad \colon \quad \{v,w\}^{m+a+1} \to \{x,y,z\}$$
$\phi$ is onto, so any word of $\{x,y,z\}$ of length $n$ is an image of some word of $\{v,w\}$ of length $m+a+n$. As a consequence,
$$\forall n \ \colon 2^{m+a+n} \geq 3^n$$
which is impossible ($m$ and $a$ are constants).


How to make lookup() look for a larger value?

Question: According to this document: https://support.google.com/docs/answer/3256570#, it is the behavior of the lookup function

If search_key is not found, the item used in the lookup will be the
  value that's immediately smaller in the range provided. For example,
  if the data set contains the numbers 1, 3, 5 and search_key is 2, then
  1 will be used for the lookup.

However I want to have 3 returned in my case.
For example, let says I have a data table as such
2, class A
4, class B
8, class C

If I search this range with value 3, I want the search function can take 4 as a match and return class B accordingly
How can I achieve this?
Answer: One way is to let the function return 'class A' but to wrap it in a function that looks as the cell below that:
=offset(vlookup(C1,A:B,2),1,0)

However I would prefer a different pair of functions:
=index(B:B,match(C1,A:A)+1)


Redirecionar página com post usando ajax

Question: Sei que a pergunta é muito estranha, mas é uma necessidade que temos, preciso passar para uma outra página algumas variáveis que resgatei, mas não é somente passar mas redirecionar a página também.
Não posso usar um window.location, precisa ser por post.
O que tenho no momento, o retorno está me exibindo as variáveis que preciso passar, mas como disse preciso redirecionar.

function preparaPagina() {

    $('button.inline-button').click(function() {

        var self = $(this);
        var IdCota = self.siblings('.product-info').data('idcota');
        var IdProduto = self.siblings('.product-info').data('produto');
        var IdUsuario = self.siblings('.product-info').data('usuario');
        var NomeUser = self.siblings('.product-info').data('nome');

        dados = {"IdCota": IdCota, "IdProduto": IdProduto, "IdUsuario": IdUsuario, "NomeUser": NomeUser  };

    $.ajax({
        type: 'POST',
        url: 'iCadAutorizacaoTrans.php',
        data : dados,
        success:function(data){
            console.log(data);
        }
    });
    })
}

preparaPagina();
Comment: `window.location` dentro do callback sucess não funcionaria?
Comment: Se não eu não entendi isso: Não posso usar um window.location, precisa ser por post.
Comment: Isso que mesmo Marconi, preciso passar essas variáveis e redirecionar para a página que estouro enviando.
Answer: Na função success do Ajax você pode inserir um form na página colocando os valores em cada input com seu respectivo name e submetê-lo via method="post", redirecionando a página para a página destino declarada na variável url_ (veja comentários explicativos no código):
function preparaPagina(){

   $('button.inline-button').click(function(){

      var self = $(this);
      var IdCota = self.siblings('.product-info').data('idcota');
      var IdProduto = self.siblings('.product-info').data('produto');
      var IdUsuario = self.siblings('.product-info').data('usuario');
      var NomeUser = self.siblings('.product-info').data('nome');

      var dados = {"IdCota": IdCota, "IdProduto": IdProduto, "IdUsuario": IdUsuario, "NomeUser": NomeUser  };

      // url do post
      var destino = 'iCadAutorizacaoTrans.php';

      $.ajax({
         type: 'POST',
         url: destino,
         data : dados,
         success:function(data){
            console.log(data);

            // monta o formulário
            // note que o atributo "hidden" faz com que ele fique oculto
            var formulario = '<form id="form" hidden method="post" action="'+destino+'">'
            +'<input name="IdCota" value="'+IdCota+'">'
            +'<input name="IdProduto" value="'+IdProduto+'">'
            +'<input name="IdUsuario" value="'+IdUsuario+'">'
            +'<input name="NomeUser" value="'+NomeUser+'">'
            +'</form>';

            // insere o formulário no body
            $("body").append(formulario);
            // faz o submit e remove o formulário
            $("#form").submit().remove();

         }
      });
   })
}

preparaPagina();

Comment: Excelente, muito obrigado @DVD, me ajudou demais, valeu.


How to create new excel spreadsheet by subtracting duplicates of another spreadsheet

Question: I have two excel spread sheets.
Test1 Test2.
Test1 has user1, user2, user3, and so on.
Test2 had user1, user2, and user5.
I would like to remove user1, user2, and user5 from Test1.
This is an example. Long story short. I have two excel spreadsheets that pull data. One is autogenerated the other is one I made. I would like to remove the users from the made spreadsheet and create a new spreadsheet that displays only the users from Test1 after removing users listed on Test2.
I am using python and pandas and have found no solutions to this.
So far I have tried doing research on python and pandas. My original solution was to manually remove the users every week to create a new spreadsheet.
Answer: If I'm understanding correctly?
<code>import pandas as pd

path = "/path/to/files/"
test1 = pd.read_excel(f"{path}Test1.xlsx")
users2 = pd.read_excel(f"{path}Test2.xlsx").users.unique()

users1 = test1.users.unique()
user_intersection = set(users1).intersection(users2)

test1.query("~users.isin(@user_intersection)").reset_index(drop=True).to_excel(f"{path}/Test3.xlsx", index=False)
</code>
Comment: Hmm. This doesn't seem to work for me. Whenever I put in users2 = pd.read_excel(f"{path}Test2.xlsx").users.unique(). I get errors.
Comment: what kind of error? Do you need to specify a sheet? Is your path wrong?


Is there anyway fsi.exe can be made to run on .NET 3.5?

Question: I am have managed to get fsi.exe become 64 bit... next I want it to load/work with .NET 3.5. Has anyone figured out a way to do this?
I have found some dated blog entries regarding this ... but no solution.
since there is no way to support older version. I get following error If I try to load .NET 3.5 DLLs into FSI
<code>> let s = new SPSite("http://myserver/sites/test");;
System.PlatformNotSupportedException: Microsoft SharePoint is not supported
with version 4.0.30319.269 of the Microsoft .Net
Runtime.
at Microsoft.SharePoint.Administration.SPConfigurationDatabase.get_Farm()
at Microsoft.SharePoint.Administration.SPFarm.FindLocal(SPFarm& farm, Boolean& isJoined)
at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
at <StartupCode$FSI_0005>.$FSI_0005.main@()
Stopped due to error
>
</code>
Answer: FSI references .NET 4, so it's not possible to run it on an older version of the CLR.  SharePoint is an exception to the rule - usually one can load assemblies which reference older .NET versions.  There must have been some compatibility issues that caused the SharePoint team to explicitly disable loading on .NET 4+.  I would not expect such an error to come up for most other .NET 3.5 assemblies you try to load.


Solve the differential equation $y(xy^{''}+y^{'})=xy^{'2}(1-x)$

Question: Solve the differential equation $y(xy^{''}+y^{'})=xy^{'2}(1-x)$
This is the integrable differential which can be solved by substitution $y^{'}=yz,z=z(x)$
Applying substitution gives $y(x(z+yz^{'})+yz)=y(xz+xzy^{'}+yz)\Rightarrow xz+xyz^{'}+yz-xyz^2+x^2yz^2=0$.
How to evaluate $y$ in terms of $z$?
Answer: $$y(x)\left(xy''(x)+y'(x)\right)=xy'(x)^2\left(1-x\right)\Longleftrightarrow$$
$$\frac{y(x)\left(xy''(x)+y'(x)\right)}{y'(x)^2}=x\left(1-x\right)\Longleftrightarrow$$
$$\frac{y(x)}{y'(x)}+\frac{xy''(x)}{y'(x)^2}=x\left(1-x\right)\Longleftrightarrow$$
$$\frac{x^2y'(x)^2-xy'(x)+y'(x)y(x)+xy''(x)y(x)}{y'(x)^2}=0\Longleftrightarrow$$
$$x^2y'(x)^2-xy'(x)^2+y'(x)y(x)+xy''(x)y(x)=0\Longleftrightarrow$$

The equation is a homogeneous polynomial of degree 2 with respect to $y$,$y'(x)$ and $y''(x)$.
Letting $y(x)=e^{v(x)}$ will reduce the order of the equation.
This gives $y'(x)=e^{v(x)}v'(x)$ and $y''(x)=e^{v(x)}\left(v''(x)+v'(x)^2\right)$:

$$e^{2v(x)}\left(x^2v'(x)^2+xv''(x)+v'(x)\right)=0\Longleftrightarrow$$

For $e^{2v(x)}=0$ does no solution exist.
Let $v'(x)=u(x)$ which gives $v''(x)=u'(x)$:

$$xu'(x)+u(x)=-x^2u(x)^2\Longleftrightarrow$$
$$-\frac{u'(x)}{u(x)^2}-\frac{1}{xu(x)}=x\Longleftrightarrow$$

Let $w(x)=\frac{1}{u(x)}$, which gives $w'(x)=-\frac{u'(x)}{u(x)^2}$:

$$w'(x)-\frac{w(x)}{x}=x\Longleftrightarrow$$

Let $\mu(x)=e^{\int-\frac{1}{x}\space\text{d}x}=\frac{1}{x}$:

$$\frac{w'(x)}{x}-\frac{w(x)}{x^2}=1\Longleftrightarrow$$

Substitute $-\frac{1}{x^2}=\frac{\text{d}}{\text{d}x}\left(\frac{1}{x}\right)$:

$$\frac{w'(x)}{x}+\frac{\text{d}}{\text{d}x}\left(\frac{1}{x}\right)w(x)=1\Longleftrightarrow$$
$$\frac{\text{d}}{\text{d}x}\left(\frac{w(x)}{x}\right)=1\Longleftrightarrow$$
$$\int\frac{\text{d}}{\text{d}x}\left(\frac{w(x)}{x}\right)\space\text{d}x=\int 1\space\text{d}x\Longleftrightarrow$$
$$\frac{w(x)}{x}=x+\text{C}\Longleftrightarrow$$
$$w(x)=x\left(x+\text{C}\right)\Longleftrightarrow$$
$$u(x)=\frac{1}{x^2+x\text{C}}\Longleftrightarrow$$
$$v'(x)=\frac{1}{x^2+x\text{C}}\Longleftrightarrow$$
$$v(x)=\frac{\ln(x)-\ln(x+\text{C})}{\text{C}}+\text{C}_2\Longleftrightarrow$$
$$y(x)=\text{C}_2e^{\frac{\ln(x)-\ln(x+\text{C})}{\text{C}}}$$
Comment: In the second substitution, $v^{'}(x)=u(x)$, what is $e^{2v(x)}$?
Comment: @user_99 I let $y(x)=e^{v(x)}$ than $x^2y'(x)^2=x^2v'(x)^2e^{2v(x)}$
Comment: (+1) Why this substitutions? Specially the first one I mean! Are they well-known? I have not seen such a substitution for a **non-linear** second order ODE! :)
Comment: Yes they are, I'm studying differential equations and I've seem them more often!


org/dom4j/DocumentException

Question: Good morning every body ,
I have java code that alllows me to create an excel file from xml flie.. But it can not create correctly the file, i have this exception that I do not inderstand its meaning :
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
at org.apache.poi.openxml4j.opc.Package.init(Package.java:145)
at org.apache.poi.openxml4j.opc.Package.<init>(Package.java:132)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:67)
at org.apache.poi.openxml4j.opc.Package.create(Package.java:271)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.newPackage(XSSFWorkbook.java:245)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:145)
at escel1.Escel1.main(Escel1.java:104)
Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)

If someone knows what that means , it will be very helpfull for me :)
Comment: Do you have dom4j JAR in your classpath?
Comment: Please show your classpath and code.
Comment: Yes i added dom4j-1.6.1-sources.jar in my prject libraries .. Is that correct ?
Comment: and this is my class path : java.class.path now = C:\Documents and Settings\Adm\Bureau\jars_excel_project\ooxml-schemas-1.0.jar;C:\Documents and Settings\Adm\Bureau\jars_excel_project\xmlbeans\xmlbeans.jar;C:\Documents and Settings\Adm\Bureau\jars_excel_project\poi-3.5-FINAL.jar;C:\Documents and Settings\Adm\Bureau\jars_excel_project\poi-ooxml-3.5-beta5.jar;C:\Documents and Settings\Adm\Bureau\logj4\apache-log4j-1.2.17\log4j-1.2.17.jar;C:\Documents and Settings\Adm\Bureau\jar files\dom\dom4j-1.6.1-sources.jar;C:\Documents and Settings\Adm\Mes documents\NetBeansProjects\escel1\build\classes
Answer: I have found the key about your problem. you shouldn't add the jar file of dom4j-1.6.1-sources.jar  but dom4j-1.x.jar into the project library. Because the jar file's name with sources is pure java file(xx.java), that means it's not compiled at all.
then rebuild your project, it'll work fine.
Hope to help you :)
Comment: Thank me by voting my answer:) (voting means it's useful)
Comment: Sorry but I can not Vote for you because I am a new subscriber in this forum and I have reputation less than 15 :/
Comment: @Bob.Z - Thanks. The error was on line `AnnotationConfiguration config = new AnnotationConfiguration();`. I added `dom4j-1.6.1.jar` and fixed it. I wonder why my simple Java bean code shows no error when I don't import this class, but fails at runtime. Can you please tell me why ?
Answer: Apache POI have a handy page listing all the components and their dependencies, you should start by reading that!
Secondly, if you downloaded the binary zip/tarball of Apache POI, then it comes with all of the dependencies you need in the /lib/ and /ooxml-lib/ directories. Make sure you include all the dependencies required from there on your classpath! (You've missed some out, hence the error)


Predicate Logic Interpretation/Modelling help

Question: I'm having trouble creating models for predicate logic statements. I am going to give an example, I hope you guys can help me out.
$$\forall x(P(x) \text{^} Q(x,a) \to Q(x,b) )$$
Let $M_1$ be the following model:

dom($M_1$) = N
$P ^M (x) =x$ is positive
$Q^M(x, y) = x \ge y$
$a^M = 5$
$b^M = 0$

To my understanding this means that for all v $ \in N $, if $v$ is positive and $v \ge 5$ then $v \ge 0$.
$M_1 \models \forall x(P(x) \text{^} Q(x,a) \to Q(x,b) )$
Is this correct?
Now say I'm trying to make this statement false.
Say I were to switch constants a and b, such that $a^M = 0$
 $b^M = 5$. Would that mean $M_1 \nvDash \forall x(P(x) \text{^} Q(x,a) \to Q(x,b) )$?
Any help would be greatly appreciated. I'm really stuck with this. Thank you in advance.
Comment: All that you have written is right,
Comment: $\hat{ }$ means the logical conjunction?
Comment: @tetori yes, ^ is the logical conjunction
Comment: So by changing the constants around, I have essentially made the statement false? Ok. Then falsifying a statement in Predicate Logic is really easy... I think I'm a little uneasy about the fact that predicate logic is so flexible. @AndréNicolas Thanks!
Comment: You are welcome. There are harder things! Right now is just language lesson, the meaning of $L$-structure and of "$\varphi$ is true in $M$."
Answer: Just as a further suggestion for when you encounter this sort of problem: the easiest thing to do is to choose models with finite domains. I'd even say try and put as few elements as possible in them. Remember that the domains and the denotations of predicates are just sets, and as such you can always define them by extension (there is no need to look for a property which members of the set satisfy -that is, no need to define them by comprehension).
For instance, in the excercise you just posted, I would have just done this:

dom(M1) = {1, 2}
$P^M$(x) = {}  (the empty set)
$Q^M$(x,y) = {}
$a^M$ = 1
$b^M$ = 2

Since the antecedent of the conditional is always false, the sentence will always be true.
Another option would have been $P^M$(x) = dom(M1), and $Q^M$(x,y) = dom(M1)$^2$ (just have everything satisfy property P, and everything relate to everything through Q)
If you need to make the sentence false, then have some element be a P, and relate through Q to $a$ but not to $b$. For instance $P^M$(x) = {1}, and $Q^M$(x,y) = {<1,1>}
The method will not always work (there are sentences and sets of sentences which can only be satisfied by infinite models), but in many cases it will, and I think is a good 'first approach' possible.


how to add a Client in SCCM system collections

Question: I am building a new sccm client VM. My only doubt is how to add the system name of the client to all systems collections before building the OS.
Many Thanks in advance. :)
Kind Regards,
Yuvi
Answer: You can do this in configuration manager console by going to SCCM | Site Database | Computer Management | Operating System Deployment | Computer Association.  Right-click on this node and select Import Computer Information.  You can then associate the new machine by its MAC address.


case insensitivity for routing in play framework 1.2.5

Question: I am using play framework 1.2.5.  If I use camelCase for my controller names, the URL appears to follow the same format.  Is there anyway I can keep the camelcase for the controller names without needing to use camelCase in the resulting URL.  I believe I could try something like the following (regex in routes.conf) but I was wondering if there is another way:
<code>[aA]dmin
</code>
Thanks in advance.
Answer: I did a quick test on one of my projects and the catch all line
<code># Catch all
*       /{controller}/{action}                  {controller}.{action}
</code>
is not case sensitive
So you could simply just use
<code># Catch all
*       /{action}                  MyController.{action}
</code>
If you wanted to expose the admin method as /Admin /admin or even /AdMiN


Broadcast or event doesnt do anything

Question: I wanted to add some pusher stuff on my app with laravel broadcasting however using broadcast() or event() helpers doesn't do anything and I have no errors.
Added my pusher info to env, changed broadcasting driver from log to pusher and neither worked. Created test event with channel name 'my-channel' and event name 'my-event'. Some dummy data in event and tried to call broadcast/event helpers with that event.
Also started PHP artisan queue:work --tries=3
And added composer require pusher/pusher-php-server
Nothing works, not even calling event(new TestEvent()) from tinker.
Only thing that works is using Pusher class directly:
$P = NEW Pusher\Pusher('KEY','SECRET','ID', ['cluster' => 'eu']);
$P->trigger('my-channel', 'my-event', ['message' => 'test']);

Comment: For everyone, I am not sure what happened but from nowhere it solved itself :D
Comment: Have you uncommented the following line in config/App.php?`App\Providers\BroadcastServiceProvider`
Comment: yes i did :D....
Answer: do you implement your event on ShouldBroadcast ?
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class TestEvent implements ShouldBroadcast
{
 ....
}

Broadcast or event doesnt do anything


Creating Menus in adobe flex

Question: I am working on a game in flex, and I am trying to figure out how to create menus in the game. I am was thinking it would be easy just to add and remove a child for the menu, but then it would be a pain to make interactive. I figure there must be some way to do it, so I am asking here.
I am trying to do both a pop up menu and an always on screen menu, like a bottom menu bar, so if anyone has any ideas please let me know. I am completely new to flash and flex and don't really know where to start past making the actual game. Thanks
WWaldo
Comment: Why oh why are you creating a game in Flex?  Flex is a UI framework, not a game framework, unless the game is just full of UI elements...
Answer: Have you looked at the Flex MenuBar class?
More documentation on it here.
If you need something spark related, check out the ButtonBar and see about extending that.
Beyond that, I'm unclear exactly what you want.  Adding and removing children to any given Flex UIComponent is pretty easy.  I don't know why that would make it hard for things to be interactive.
Answer: In terms of making a menu with different appearances based off of the state of something, check out the built in state management :
http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf63611-7ffa.html
This lets you define what children appear in which state of the menu, then you just set the currentState : currentState='soundMenu'

Creating Menus in adobe flex


Mockito: WebClient reactive method call

Question: I am facing difficulties in writing a unit test for my collect  method. Specifically, the Jacoco test coverage for the methods that occur after I call getBearerToken() within the collectEndpointCount method is not getting recognized. StepVerifier is able to verify that it has been completed but the values within it are all null.
Here is a quick breakdown of what my collect does. It takes in a timeRange and initiates 2 asynchronous operations using the collectEndpointCount method for each endpoint. This method retrieves an Apigee access token using extractAccessToken and getBearerToken to authenticate the API requests
The usage count data is fetched from the external API for each endpoint using the constructed URL and the obtained access token. The response is then processed by the processEndpointResponse method to extract the usage count. The collected counts for all 2 endpoints are combined using the Mono.zip operation.
ResultsCollectorImpl.java
public ResultCollectorImpl(WebClient webClient) {
    this.webClient = webClient;
}

@Override
public Mono<ResultStats> collect(String timeRange) {
    Mono<Long> results1 = collectEndpointCount(timeRange, "url1");
    Mono<Long> results2 = collectEndpointCount(timeRange, "url2");

    return Mono.zip(results1, results2)
        .map(tuple -> new ResultStats(tuple.getT1(), tuple.getT2()));
}

private Mono<String> getBearerToken() {
    return webClient.post()
        .uri("https://login.apigee.com/oauth/token")
        .header(HttpHeaders.AUTHORIZATION, "Basic ZWRnZWNsaTplZGdlY2xpc2VjcmV0")
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
        .bodyValue("grant_type=refresh_token&refresh_token=my_refresh_token")
        .retrieve()
        .bodyToMono(String.class)
        .flatMap(this::extractAccessToken);
}

private Mono<String> extractAccessToken(String responseBody) {
    try {
        JsonNode accessTokenNode = new ObjectMapper().readTree(responseBody).get("access_token");
        if (accessTokenNode != null && accessTokenNode.isTextual()) {
            return Mono.just(accessTokenNode.asText());
        }
        return Mono.empty();
    } catch (IOException e) {
        return Mono.error(e);
    }
}

private Mono<Long> collectEndpointCount(String timeRange, String url) {
    return getBearerToken()
        .flatMap(bearerToken -> webClient.get()
            .uri(url)
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken)
            .retrieve()
            .bodyToMono(String.class)
            .flatMap(responseBody -> Mono.fromCallable(() -> processEndpointResponse(responseBody))))
        .onErrorMap(ex -> ex instanceof WebClientResponseException || ex instanceof IOException,
            BillProcessorExceptionCollect::new);
}

private long processEndpointResponse(@NonNull String responseBody) throws IOException {
    try (JsonParser jsonParser = new JsonFactory().createParser(responseBody)) {
        while (jsonParser.nextToken() != null) {
            if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME
                && "values".equals(jsonParser.getCurrentName())) {
                jsonParser.nextToken();
                while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                    if (jsonParser.getCurrentToken() == JsonToken.VALUE_STRING) {
                        return (long) Double.parseDouble(jsonParser.getText());
                    }
                }
            }
        }
    }
    return 0;
}

ResultsCollectorImplTest.java
@Mock
private WebClient webClient;
@Mock
private ApigeeConfig apigeeConfig;
@InjectMocks
private ResultStatsCollectorImpl resultStatsCollector;
@Mock
private RequestBodyUriSpec requestBodyUriSpec;
@Mock
private RequestHeadersUriSpec requestHeadersUriSpec;
@Mock
private RequestHeadersSpec requestHeadersSpec;
@Mock
private ResponseSpec responseSpec;

@BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
    ResultStatsCollector = new ResultStatsCollectorImpl(webClient, apigeeConfig);
}

@Test
void testCollectWithValidData() {
    String timeRange = "08/01/2023 00:00~08/31/2023 23:59";

    Mono<String> accessToken = Mono.just("{\"access_token\":\"bearer_token\"");
    when(apigeeConfig.getRefreshToken()).thenReturn("mockRefreshToken");
    when(webClient.post()).thenReturn(requestBodyUriSpec);
    when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodyUriSpec);
    when(requestBodyUriSpec.header(anyString(), anyString())).thenReturn(requestBodyUriSpec);
    when(requestBodyUriSpec.bodyValue(anyString())).thenReturn(requestHeadersSpec);
    when(requestBodyUriSpec.retrieve()).thenReturn(responseSpec);
    when(responseSpec.bodyToMono(String.class)).thenReturn(accessToken);

    String mockApiResponse = "{\"from\":\"2023-08-01T00:00:00+08:00\",\" count1\":100,\"count2\":100}";
    when(webClient.get()).thenReturn(requestHeadersUriSpec);
    when(requestHeadersUriSpec.uri(anyString())).thenReturn(requestHeadersUriSpec);
    when(requestHeadersUriSpec.header(HttpHeaders.AUTHORIZATION, "mockAccessToken")).thenReturn(requestHeadersSpec);
    when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
    when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just(mockApiResponse));

    Mono<ResultStats> usageStats = resultStatsCollector.collect(timeRange);

    StepVerifier.create(usageStats).verifyComplete();
}

Comment: Why do you assign `ResultStatsCollector`? It is never used. At the same time, `resultStatsCollector` is already assigned by annotation `@InjectMocks` (I'm assuming you are running the test with Mockito extension – your test class definition is not included in the question)
Answer: As my method calls webClient, each produced a different responseSpec. Adding another mock ResponseSpec did the trick.
@Mock
private ResponseSpec responseSpecStats;

...
when(requestHeadersUriSpec.retrieve()).thenReturn(responseSpecStats);
when(responseSpecStats.bodyToMono(String.class)).thenReturn((endpointResponse));

Mockito: WebClient reactive method call


Add base fields to custom entity after install

Question: I have a custom module with a custom entity which has its base fields specified in baseFieldDefinitions.
Now I want to add another base field to the entity but I can't see it in neither edit nor form display when applying the code below.
I can see it gets added in the database and I have also tried just copy-pasting existing fields from baseFieldDefinitions() (which I know works) without luck. It seems it just doesn't update the frontend.
function word_update_9001() {
  $storage_definition = BaseFieldDefinition::create('string')
    ->setLabel(t('Temp Word'))
    ->setCardinality(4)
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => -5,
    ])
    ->setDisplayConfigurable('form', true);

  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $update_manager->installFieldStorageDefinition('locked', 'word', 'word', $storage_definition);

Cache has been cleared several times.
Comment: Is this helpful? https://stefvanlooveren.me/blog/how-update-custom-entity-drupal-8-once-installed-add-field
Comment: That code seems similar to the code shown in https://www.drupal.org/docs/drupal-apis/update-api/updating-entities-and-fields-in-drupal-8. The only difference is that the Drupal.org example is for a custom block, while the code in this question is for a custom entity we don't know.  Apart noticing the field label is much different from the field machine name (*Temp Word* versus *locked*), there isn't much we can say without having more details on that entity.
Answer: You should do this in two steps. First make a new version of the entity class. Test it by reinstalling or, if you want to keep the data, by installing it on a different site. If the new entity version works and you can edit the entities including the new fields, then write the update hook. You can test the hook also on a second test site by installing first the old version and test the new code, before you apply it on production data.
Answer: This is for adding base field to any entity.

Implement hook_base_field_info().
Update schema (you already did this).

https://bryanmanalo.com/what-drupal-base-field-and-when-do-you-need-create-one


Negative number causes VarInt's encoding function to crash

Question: I try to implement the function below in Python but as soon as I enter a negative number the function crashes. Does anyone understand why?
public static void writeVarInt(int value) {
    do {
        byte temp = (byte)(value & 0b01111111);

        value >>>= 7;
        if (value != 0) {
            temp |= 0b10000000;
        }
        writeByte(temp);
    } while (value != 0);
}

Here my function :
def write_varint(array, data):
    first_pass = True
    while data != 0 or first_pass:
        first_pass = False
        temp = (data & 0b01111111)
        data >>= 7

        if data != 0:
            temp |= 0b10000000

        print(temp)

        write_byte(array, temp)

def write_byte(array, data):
    write_bytes(array, struct.pack('>b', data))

def write_bytes(array, source_bytes):
    for byte in source_bytes:
        array.append(byte)

Answer: if data != 0:
    temp |= 0b10000000

When data value is -1 this conditional does not get called and therefore temp ends up out of range of the needed [-128, 127], and wounds up crashing when struct.pack() function gets called (which requires a number within that range).