Desativar página enquanto carrega progress bar

Question: Boa tarde, pessoal!
Eu tenho uma barra de progresso a qual é utilizada para indicar o carregamento da página. Ela é implementada através de css e js. Eu gostaria de saber como faço para desativar o corpo da página até que se complete o carregamento (barra de progresso). Segue código da barra.
Abraço!

/*! pace 1.0.0 */
(function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X=[].slice,Y={}.hasOwnProperty,Z=function(a,b){function c(){this.constructor=a}for(var d in b)Y.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},$=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(b in this&&this[b]===a)return b;return-1};for(u={catchupTime:100,initialRate:.03,minTime:250,ghostTime:100,maxProgressPerFrame:20,easeFactor:1.25,startOnPageLoad:!0,restartOnPushState:!0,restartOnRequestAfter:500,target:"body",elements:{checkInterval:100,selectors:["body"]},eventLag:{minSamples:10,sampleCount:3,lagThreshold:3},ajax:{trackMethods:["GET"],trackWebSockets:!0,ignoreURLs:[]}},C=function(){var a;return null!=(a="undefined"!=typeof performance&&null!==performance&&"function"==typeof performance.now?performance.now():void 0)?a:+new Date},E=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,t=window.cancelAnimationFrame||window.mozCancelAnimationFrame,null==E&&(E=function(a){return setTimeout(a,50)},t=function(a){return clearTimeout(a)}),G=function(a){var b,c;return b=C(),(c=function(){var d;return d=C()-b,d>=33?(b=C(),a(d,function(){return E(c)})):setTimeout(c,33-d)})()},F=function(){var a,b,c;return c=arguments[0],b=arguments[1],a=3<=arguments.length?X.call(arguments,2):[],"function"==typeof c[b]?c[b].apply(c,a):c[b]},v=function(){var a,b,c,d,e,f,g;for(b=arguments[0],d=2<=arguments.length?X.call(arguments,1):[],f=0,g=d.length;g>f;f++)if(c=d[f])for(a in c)Y.call(c,a)&&(e=c[a],null!=b[a]&&"object"==typeof b[a]&&null!=e&&"object"==typeof e?v(b[a],e):b[a]=e);return b},q=function(a){var b,c,d,e,f;for(c=b=0,e=0,f=a.length;f>e;e++)d=a[e],c+=Math.abs(d),b++;return c/b},x=function(a,b){var c,d,e;if(null==a&&(a="options"),null==b&&(b=!0),e=document.querySelector("[data-pace-"+a+"]")){if(c=e.getAttribute("data-pace-"+a),!b)return c;try{return JSON.parse(c)}catch(f){return d=f,"undefined"!=typeof console&&null!==console?console.error("Error parsing inline pace options",d):void 0}}},g=function(){function a(){}return a.prototype.on=function(a,b,c,d){var e;return null==d&&(d=!1),null==this.bindings&&(this.bindings={}),null==(e=this.bindings)[a]&&(e[a]=[]),this.bindings[a].push({handler:b,ctx:c,once:d})},a.prototype.once=function(a,b,c){return this.on(a,b,c,!0)},a.prototype.off=function(a,b){var c,d,e;if(null!=(null!=(d=this.bindings)?d[a]:void 0)){if(null==b)return delete this.bindings[a];for(c=0,e=[];c<this.bindings[a].length;)e.push(this.bindings[a][c].handler===b?this.bindings[a].splice(c,1):c++);return e}},a.prototype.trigger=function(){var a,b,c,d,e,f,g,h,i;if(c=arguments[0],a=2<=arguments.length?X.call(arguments,1):[],null!=(g=this.bindings)?g[c]:void 0){for(e=0,i=[];e<this.bindings[c].length;)h=this.bindings[c][e],d=h.handler,b=h.ctx,f=h.once,d.apply(null!=b?b:this,a),i.push(f?this.bindings[c].splice(e,1):e++);return i}},a}(),j=window.Pace||{},window.Pace=j,v(j,g.prototype),D=j.options=v({},u,window.paceOptions,x()),U=["ajax","document","eventLag","elements"],Q=0,S=U.length;S>Q;Q++)K=U[Q],D[K]===!0&&(D[K]=u[K]);i=function(a){function b(){return V=b.__super__.constructor.apply(this,arguments)}return Z(b,a),b}(Error),b=function(){function a(){this.progress=0}return a.prototype.getElement=function(){var a;if(null==this.el){if(a=document.querySelector(D.target),!a)throw new i;this.el=document.createElement("div"),this.el.className="pace pace-active",document.body.className=document.body.className.replace(/pace-done/g,""),document.body.className+=" pace-running",this.el.innerHTML='
\n

\n
\n

',null!=a.firstChild?a.insertBefore(this.el,a.firstChild):a.appendChild(this.el)}return this.el},a.prototype.finish=function(){var a;return a=this.getElement(),a.className=a.className.replace("pace-active",""),a.className+=" pace-inactive",document.body.className=document.body.className.replace("pace-running",""),document.body.className+=" pace-done"},a.prototype.update=function(a){return this.progress=a,this.render()},a.prototype.destroy=function(){try{this.getElement().parentNode.removeChild(this.getElement())}catch(a){i=a}return this.el=void 0},a.prototype.render=function(){var a,b,c,d,e,f,g;if(null==document.querySelector(D.target))return!1;for(a=this.getElement(),d="translate3d("+this.progress+"%, 0, 0)",g=["webkitTransform","msTransform","transform"],e=0,f=g.length;f>e;e++)b=g[e],a.children[0].style[b]=d;return(!this.lastRenderedProgress||this.lastRenderedProgress|0!==this.progress|0)&&(a.children[0].setAttribute("data-progress-text",""+(0|this.progress)+"%"),this.progress>=100?c="99":(c=this.progress<10?"0":"",c+=0|this.progress),a.children[0].setAttribute("data-progress",""+c)),this.lastRenderedProgress=this.progress},a.prototype.done=function(){return this.progress>=100},a}(),h=function(){function a(){this.bindings={}}return a.prototype.trigger=function(a,b){var c,d,e,f,g;if(null!=this.bindings[a]){for(f=this.bindings[a],g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(c.call(this,b));return g}},a.prototype.on=function(a,b){var c;return null==(c=this.bindings)[a]&&(c[a]=[]),this.bindings[a].push(b)},a}(),P=window.XMLHttpRequest,O=window.XDomainRequest,N=window.WebSocket,w=function(a,b){var c,d,e,f;f=[];for(d in b.prototype)try{e=b.prototype[d],f.push(null==a[d]&&"function"!=typeof e?a[d]=e:void 0)}catch(g){c=g}return f},A=[],j.ignore=function(){var a,b,c;return b=arguments[0],a=2<=arguments.length?X.call(arguments,1):[],A.unshift("ignore"),c=b.apply(null,a),A.shift(),c},j.track=function(){var a,b,c;return b=arguments[0],a=2<=arguments.length?X.call(arguments,1):[],A.unshift("track"),c=b.apply(null,a),A.shift(),c},J=function(a){var b;if(null==a&&(a="GET"),"track"===A[0])return"force";if(!A.length&&D.ajax){if("socket"===a&&D.ajax.trackWebSockets)return!0;if(b=a.toUpperCase(),$.call(D.ajax.trackMethods,b)>=0)return!0}return!1},k=function(a){function b(){var a,c=this;b.__super__.constructor.apply(this,arguments),a=function(a){var b;return b=a.open,a.open=function(d,e){return J(d)&&c.trigger("request",{type:d,url:e,request:a}),b.apply(a,arguments)}},window.XMLHttpRequest=function(b){var c;return c=new P(b),a(c),c};try{w(window.XMLHttpRequest,P)}catch(d){}if(null!=O){window.XDomainRequest=function(){var b;return b=new O,a(b),b};try{w(window.XDomainRequest,O)}catch(d){}}if(null!=N&&D.ajax.trackWebSockets){window.WebSocket=function(a,b){var d;return d=null!=b?new N(a,b):new N(a),J("socket")&&c.trigger("request",{type:"socket",url:a,protocols:b,request:d}),d};try{w(window.WebSocket,N)}catch(d){}}}return Z(b,a),b}(h),R=null,y=function(){return null==R&&(R=new k),R},I=function(a){var b,c,d,e;for(e=D.ajax.ignoreURLs,c=0,d=e.length;d>c;c++)if(b=e[c],"string"==typeof b){if(-1!==a.indexOf(b))return!0}else if(b.test(a))return!0;return!1},y().on("request",function(b){var c,d,e,f,g;return f=b.type,e=b.request,g=b.url,I(g)?void 0:j.running||D.restartOnRequestAfter===!1&&"force"!==J(f)?void 0:(d=arguments,c=D.restartOnRequestAfter||0,"boolean"==typeof c&&(c=0),setTimeout(function(){var b,c,g,h,i,k;if(b="socket"===f?e.readyState<2:0<(h=e.readyState)&&4>h){for(j.restart(),i=j.sources,k=[],c=0,g=i.length;g>c;c++){if(K=i[c],K instanceof a){K.watch.apply(K,d);break}k.push(void 0)}return k}},c))}),a=function(){function a(){var a=this;this.elements=[],y().on("request",function(){return a.watch.apply(a,arguments)})}return a.prototype.watch=function(a){var b,c,d,e;return d=a.type,b=a.request,e=a.url,I(e)?void 0:(c="socket"===d?new n(b):new o(b),this.elements.push(c))},a}(),o=function(){function a(a){var b,c,d,e,f,g,h=this;if(this.progress=0,null!=window.ProgressEvent)for(c=null,a.addEventListener("progress",function(a){return h.progress=a.lengthComputable?100*a.loaded/a.total:h.progress+(100-h.progress)/2},!1),g=["load","abort","timeout","error"],d=0,e=g.length;e>d;d++)b=g[d],a.addEventListener(b,function(){return h.progress=100},!1);else f=a.onreadystatechange,a.onreadystatechange=function(){var b;return 0===(b=a.readyState)||4===b?h.progress=100:3===a.readyState&&(h.progress=50),"function"==typeof f?f.apply(null,arguments):void 0}}return a}(),n=function(){function a(a){var b,c,d,e,f=this;for(this.progress=0,e=["error","open"],c=0,d=e.length;d>c;c++)b=e[c],a.addEventListener(b,function(){return f.progress=100},!1)}return a}(),d=function(){function a(a){var b,c,d,f;for(null==a&&(a={}),this.elements=[],null==a.selectors&&(a.selectors=[]),f=a.selectors,c=0,d=f.length;d>c;c++)b=f[c],this.elements.push(new e(b))}return a}(),e=function(){function a(a){this.selector=a,this.progress=0,this.check()}return a.prototype.check=function(){var a=this;return document.querySelector(this.selector)?this.done():setTimeout(function(){return a.check()},D.elements.checkInterval)},a.prototype.done=function(){return this.progress=100},a}(),c=function(){function a(){var a,b,c=this;this.progress=null!=(b=this.states[document.readyState])?b:100,a=document.onreadystatechange,document.onreadystatechange=function(){return null!=c.states[document.readyState]&&(c.progress=c.states[document.readyState]),"function"==typeof a?a.apply(null,arguments):void 0}}return a.prototype.states={loading:0,interactive:50,complete:100},a}(),f=function(){function a(){var a,b,c,d,e,f=this;this.progress=0,a=0,e=[],d=0,c=C(),b=setInterval(function(){var g;return g=C()-c-50,c=C(),e.push(g),e.length>D.eventLag.sampleCount&&e.shift(),a=q(e),++d>=D.eventLag.minSamples&&a<D.eventLag.lagThreshold?(f.progress=100,clearInterval(b)):f.progress=100*(3/(a+3))},50)}return a}(),m=function(){function a(a){this.source=a,this.last=this.sinceLastUpdate=0,this.rate=D.initialRate,this.catchup=0,this.progress=this.lastProgress=0,null!=this.source&&(this.progress=F(this.source,"progress"))}return a.prototype.tick=function(a,b){var c;return null==b&&(b=F(this.source,"progress")),b>=100&&(this.done=!0),b===this.last?this.sinceLastUpdate+=a:(this.sinceLastUpdate&&(this.rate=(b-this.last)/this.sinceLastUpdate),this.catchup=(b-this.progress)/D.catchupTime,this.sinceLastUpdate=0,this.last=b),b>this.progress&&(this.progress+=this.catchup*a),c=1-Math.pow(this.progress/100,D.easeFactor),this.progress+=c*this.rate*a,this.progress=Math.min(this.lastProgress+D.maxProgressPerFrame,this.progress),this.progress=Math.max(0,this.progress),this.progress=Math.min(100,this.progress),this.lastProgress=this.progress,this.progress},a}(),L=null,H=null,r=null,M=null,p=null,s=null,j.running=!1,z=function(){return D.restartOnPushState?j.restart():void 0},null!=window.history.pushState&&(T=window.history.pushState,window.history.pushState=function(){return z(),T.apply(window.history,arguments)}),null!=window.history.replaceState&&(W=window.history.replaceState,window.history.replaceState=function(){return z(),W.apply(window.history,arguments)}),l={ajax:a,elements:d,document:c,eventLag:f},(B=function(){var a,c,d,e,f,g,h,i;for(j.sources=L=[],g=["ajax","elements","document","eventLag"],c=0,e=g.length;e>c;c++)a=g[c],D[a]!==!1&&L.push(new l[a](D[a]));for(i=null!=(h=D.extraSources)?h:[],d=0,f=i.length;f>d;d++)K=i[d],L.push(new K(D));return j.bar=r=new b,H=[],M=new m})(),j.stop=function(){return j.trigger("stop"),j.running=!1,r.destroy(),s=!0,null!=p&&("function"==typeof t&&t(p),p=null),B()},j.restart=function(){return j.trigger("restart"),j.stop(),j.start()},j.go=function(){var a;return j.running=!0,r.render(),a=C(),s=!1,p=G(function(b,c){var d,e,f,g,h,i,k,l,n,o,p,q,t,u,v,w;for(l=100-r.progress,e=p=0,f=!0,i=q=0,u=L.length;u>q;i=++q)for(K=L[i],o=null!=H[i]?H[i]:H[i]=[],h=null!=(w=K.elements)?w:[K],k=t=0,v=h.length;v>t;k=++t)g=h[k],n=null!=o[k]?o[k]:o[k]=new m(g),f&=n.done,n.done||(e++,p+=n.tick(b));return d=p/e,r.update(M.tick(b,d)),r.done()||f||s?(r.update(100),j.trigger("done"),setTimeout(function(){return r.finish(),j.running=!1,j.trigger("hide")},Math.max(D.ghostTime,Math.max(D.minTime-(C()-a),0)))):c()})},j.start=function(a){v(D,a),j.running=!0;try{r.render()}catch(b){i=b}return document.querySelector(".pace")?(j.trigger("start"),j.go()):setTimeout(j.start,50)},"function"==typeof define&&define.amd?define(function(){return j}):"object"==typeof exports?module.exports=j:D.startOnPageLoad&&j.start()}).call(this);
.pace {
  -webkit-pointer-events: none;
  pointer-events: none;

  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

.pace-inactive {
  display: none;
}

.pace .pace-progress {
  background: #29d;
  position: fixed;
  z-index: 2000;
  top: 0;
  right: 100%;
  width: 100%;
  height: 5px;
}
Comment: Como assim desativar o corpo da página ?
Comment: Vou tentar explicar melhor. Enquanto a página ainda está carregando, é possível mexer nela, por exemplo, rolar, clicar em algum botão, etc, sem a página ter terminado todo seu carregamento. Eu gostaria de inutilizar o corpo da página (disabled) de forma que o usuário só consigo mexer alguma coisa quando a página estivesse totalmente carregada.
Comment: http://stackoverflow.com/questions/24345548/how-block-ui-until-page-load-with-wait-image-using-javascript-css-only
Answer: Bom amigo o código da "barra" não é muito útil uma vez que esta "minificado" quanto a pace.js a biblioteca possui opção para monitorar o carregamento de de determinados elementos como mostrado na documentação.
Agora se o que você que é de fato não mostrar o conteúdo enquanto não houver o carregamento completo te deixo duas respostas:

Resposta curta: use window.onload referencia e exemplos W3Schools.

Resposta correta:
Bloquear o acesso do usuário ao conteúdo da página (body) ou a partes do conteúdo por razão de não ter havido carregamento completo não é uma técnica tão incomum assim porém não é recomendado utilizar aspectos "obstrutivos" para tal pois denegrecem a experiencia do usuário para com a aplicação.
O método mais fácil (e menos recomendado) seria aplicar uma classe com propriedade display: none na body e após o carregamento completo via javascript (leia-se: window.onload) modificar esta classe para display: block ou remove-la.
Exemplo: jsfiddle
<!DOCTYPE html>

  <meta charset="utf-8">

Hello World!

Caso já possui o atributo class em sua body e não queira remover podes usar setAttribute para reescrever os atributos da class ou usar de artifícios como removeClass para remover explicitamente o item.
A exemplo disto você poderia mostrar uma imagem de fundo, uma mensagem de carregamento ou um ícone enquanto o conteúdo ainda estiver carregando más para isto a classe com display: none não deve ser atribuída a body mas sim a outro elemento na página como uma div utilizada como "container" da aplicação e o elemento com a "mensagem|imagem" seria exibido por padrão e removido posteriormente como neste exemplo no jsfiddle.
Contudo em ambos os exemplos são praticas obstrutivas que podem trazer prejuízo a experiencia do usuário uma vez que os recursos de sua aplicação podem demorar a carregar ou caso ocorra um erro fatal na execução do script fazendo assim com que a página não seja visualizada porque a classe não foi removida ou modificada pelo script.
Seguindo essa "técnica" a abordagem "mais correta" seria disponibilizar a parte do conteúdo essencial da página imediatamente e fazer um carregamento dinâmico dos demais elementos da página servindo-os em blocos fazendo assim estarem disponíveis apenas após o carregamento de suas dependências... claro isto esta mais aplicado a arquitetura e a orientação do projeto do que simplesmente um código visto que inúmeras técnicas e metodologias se fazem necessário para se chegar nesta abordagem "mais correta".
Existem muitas bibliotecas que ajudam neste sentido (carregamento dinâmico).
Para aguçar sua curiosidade deixo a recomendação desta PreloadJS é bem sólida e fácil de trabalhar talvez seja de ajuda a entender e chegar no resultado que esperas.


Cloudfront with private EC2 origin

Question: I want to integrate cloudfront with private origin as all the instances will be in private subnet with outpost setup.
while creating cloudfront distribution I tried adding private DNS of EC2 (ip-XX-XX-XX-XX.us-east-2.compute.internal) but its giving error : 502 bad gateway
I have below questions :

Can we have aws cloudfront with private origin (EC2 instance) ?
Can we use cloudfront as a shared proxy cache inside private subnet ?
Answer: Amazon CloudFront lives on the Internet. When it retrieves content from an Origin, the content must be accessible from the Internet.
Amazon EC2 instances in a private subnet are not accessible from the Internet. Therefore, CloudFront would not be capable of accessing the content.
Private IP addresses can only be resolved and used within the VPC. They are not accessible from outside the VPC.
Comment: You will need to expose your private resources to the Internet so that CloudFront can reach them. You could configure access so that only CloudFront can access the resources, but it is a large list of IP addresses: [Locations and IP address ranges of CloudFront edge servers - Amazon CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html)
Comment: Yes, but the Load Balancer would need to be accessible from the Internet so people could potentially bypass CloudFront and access the Load Balancer directly (unless you restrict it as suggested above).
Comment: A NAT Gateway is used to provide **Outbound** access to the Internet for resources inside a VPC. It intentionally does _not_ permit **Inbound** connections from the Internet or, therefore, from CloudFront. If you want your resources reachable from CloudFront, they either need to be in a Public Subnet and accessible to CloudFront, or you need a Load Balancer in a public subnet that is accessible to CloudFront.
Comment: Is there any way we can connect cloudfront to our private network?
Comment: What about placing an ELB in front of the EC2 instance? would that be sufficient to allow CloudFront to forward the traffic without having to make the instance public?
Comment: Can we have NAT gateway to connect to internet from private subnet and configure cloudFront with EC2 instance within private subnet ?
Answer: A good practice for this would be to use IP prefix list - available as part of VPC functionality.
There you would find managed Cloudfront IP Prefix list, you can reference it in your Security group ingress/egress rules. Updates of this list are managed by AWS.
Additionally, if you are using any other CDN's, such as Cloudflare, you can populate your own prefix lists and manage in similar fashion your SG rules. Mind that custom prefix lists you have to manage yourself - something I employ myself Lambdas for.
Answer: use an internet facing ALB with a custom header rule to determine if the query was from cloudfront.
you can then configure your cloudfront distribution to forwards that custom header key & value so that only requests through cf will pass through
Comment: Or you can just use the IP prefix list and only allow inbound requests from CF. That is much easier than doing what you suggested, which is not even safe as anyone could send these headers.
Comment: @T3rm1 The technique described by silvercondor is what AWS prescribe: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html Anyone can send a header value, but the idea is that the value is a secret only known to owner of the AWS Account (other solutions involve rotating the secret regularly). Using an IP prefix list alone allows anyone to send traffic via CloudFront to your origin; It is easier, yes, but it is not going to secure the origin to disallow others to access it via another CloudFront distribution.

Cloudfront with private EC2 origin


Integral with closed form? $\int_0^\infty\frac{x^n\ln x}{(1+x)^2(1+x^m)}dx$

Question: I am trying to evaluate
$$I(n,m)=\int_0^\infty\frac{x^n\ln x}{(1+x)^2(1+x^m)}dx$$
and I'm strongly convinced that it has a nice closed form. This is because if you plug small values for $(n,m)$, you get neat results in terms of $\pi^2$. Here are some examples:
$$I(0,2)=-\frac{\pi^2}{16}$$
$$I(0,3)=-\frac16-\frac{4\pi^2}{81}$$
$$I(0,4)=\frac{2\sqrt2-5}{32}\pi^2$$
$$I(1,3)=\frac16-\frac{2\pi^2}{81}$$
$$I(3,4)=\frac{4\sqrt2-5}{64}\pi^2$$
I managed to calculate some of them via partial fractions. The others are from WolframAlpha.
Two interesting facts:
1) Notice that $$I(n,m)=-I(m-n,m)$$ This is easily obtained by letting $x=\frac1t$ in the integral. It follows that, for example:
$$I(2,3)=\frac{2\pi^2}{81}-\frac16$$
$$I(1,4)=\frac{5-4\sqrt2}{64}\pi^2$$
2) From the same result follows also that $I(n,2n)=0$, and so we get beautiful results like
$$\int_0^\infty\frac{\sqrt{x}\log x}{(1+x)^3}dx=0$$
I am clueless on how to solve the general case. I think it's useful to reduce it to
$$I(n,m)=\int_0^1\frac{x^n\log x}{(1+x)^2(1+x^m)}dx-\int_0^1\frac{x^{m-n}\log x}{(1+x)^2(1+x^m)}dx$$
Expanding $\frac{1}{1+t^m}$ in series reduces the problem to evaluating integrals of the form
$$\int_0^1\frac{x^a\log x}{(1+x)^2}dx$$
and then summing the result over $\mathbb N$
, but I'm not sure how to proceed from here.
Answer:
and now expanding $\frac{1}{1+t^m}$ in series reduces the problem to evaluating integrals of the form
$$\int_0^1\frac{x^a\log x}{(1+x)^2}dx$$
but I'm not sure how to proceed from here.

Let $$J=\int_0^1\frac{x^a}{(1+x)^2} dx$$
Integration by part,
$$J=-\frac{1}2+a\int_0^1\frac{x^{a-1}}{1+x} dx=-\frac{1}2+a\sum_{n=0}(-1)^n\int_0^1 x^{n+a-1} dx=-\frac{1}2+a\sum_{n=0}\frac{(-1)^n}{n+a}$$
we have
$$I=\frac{dJ}{da}=\int_{0}^{\infty} \frac{{x}^{a}\ln x}{(1+x)^2} dx=\sum_{n=0}\frac{(-1)^n}{n+a}-a\sum_{n=0}\frac{(-1)^n}{(n+a)^2}$$
Remarks:
We can generalize the OP into this form
$$I(n,m, k)=\int_0^\infty\frac{x^n\ln^k x}{(1+x)^2(1+x^m)}dx$$
Let:
$$H=\int_0^\infty\frac{x^a}{(1+x)^2(1+x^m)}dx$$
hence
$$I(n,m, k)=\frac{d^k H }{da^k}\bigg|_{a=n}$$
To compute $H$, we can use contour integral, with the classic key-hole contour, with the branch cut along positive x-axis. The integral vanishes on the large circle when $a<m+1$, and the integral vanishes on the small circle when $-1<a$, therefore, we require $-1<a<m+1$
$$\int_0^\infty\frac{z^a}{(1+z)^2(1+z^m)}dz-\int_0^\infty\frac{z^ae^{2\pi a i}}{(1+z)^2(1+z^m)}dz=2\pi i \sum_p Res(z_p)$$
so we get
$$H=\int_0^\infty\frac{z^a}{(1+z)^2(1+z^m)}dz=\frac{2\pi i}{1-e^{2\pi a i}} \sum_p Res(z_p)$$
When computing the residues, there are two cases,
(1). if $m$ is odd,
$z_p=-1$ is a 3rd order pole. $z_p=e^{\frac{2p+1}{m}\pi i}, p=0,1,\dots,\frac{m-3}2,\frac{m+1}2,\dots,m-1$ are simple poles.
(2). if $m$ is even,
$z_p=-1$ is a 2rd order pole. $z_p=e^{\frac{2p+1}{m}\pi i}, p=0,1,\dots,m-1$ are simple poles.
Comment: Because this is to answer your question on how to proceed to evaluate $\int_0^1\frac{x^a\log x}{(1+x)^2}dx$. @Zima
Answer: Assuming m is a positive integer value greater than 1, we can always break down a fraction of the form $\frac{1}{1+x^m}$ as follows using partial fraction decomposition.
$$\frac{1}{1+x^m}=\frac{1}{(x-r_1)(x-r_2)...(x-r_m)}=\sum_{k=1}^m\frac{C_k}{x-r_k}$$
This reduces the problem into
$$\int_0^\infty\frac{x^n\ln x}{(1+x)^2(1+x^m)}dx=\sum_{k=1}^mC_k\int_0^\infty \frac{x^n\ln x}{(1+x)^2(x-r_k)}dx$$
Now we evaluate the integral by splitting it at x=1
$$\int_0^\infty \frac{x^n\ln x}{(1+x)^2(x-r_k)}dx=\int_0^1 \frac{x^n\ln x}{(1+x)^2(x-r_k)}dx+\int_1^\infty \frac{x^n\ln x}{(1+x)^2(x-r_k)}dx=\int_0^1 \frac{x^n\ln x}{(1+x)^2(x-r_k)}dx+\int_0^1 \frac{x^{3-n}\ln x}{(1+x)^2(1-r_kx)}dx=I(n,r_k)-\frac{1}{r_k}I(3-n,\frac{1}{r_k})$$
We can calculate $I(n,r_k)$ by using a series expansion, integrating term by term, and using the Lerch transcendent function.
$$\frac{1}{(1+x)^2(x-r)}=\frac{1}{(r+1)^2}\frac{1}{x-r}-\frac{1}{(r+1)^2}\frac{1}{x+1}-\frac{1}{r+1)}\frac{1}{(x+1)^2}$$$$=-\frac{1}{r(r+1)^2}\sum_{l=0}^\infty\left(\frac{x}{r}\right)^l-\frac{1}{(r+1)^2}\sum_{l=0}^\infty(-x)^l-\frac{1}{r+1}\sum_{l=0}^\infty(l+1)(-x)^l$$
$$I(n,r_k)=\int_0^1\frac{x^n\ln x}{(1+x)^2(x-r_k)}dx$$$$=-\frac{1}{r(r+1)^2}\sum_{l=0}^\infty\int_0^1\frac{x^{l+n}\ln x}{r^l}dx-\frac{1}{(r+1)^2}\sum_{l=0}^\infty(-1)^l\int_0^1x^{l+n}\ln x\space  dx-\frac{1}{r+1}\sum_{l=0}^\infty(-1)^l(l+1)\int_0^1x^{l+n}\ln x\space dx$$$$=\frac{1}{r(r+1)^2}\sum_{l=0}^\infty\frac{1}{r^l(l+n+1)^2}+\frac{1}{(r+1)^2}\sum_{l=0}^\infty\frac{(-1)^l}{(l+n+1)^2}+\frac{1}{r+1}\sum_{l=0}^\infty\frac{(-1)^l}{l+n+1}-\frac{n}{r+1}\sum_{l=0}^\infty\frac{(-1)^l}{(l+n+1)^2}$$$$=\frac{1}{r(r+1)^2}\Phi(1/r,2,n+1)+\frac{1-n(r+1)}{(r+1)^2}\Phi(-1,2,n+1)+\frac{1}{r+1}\Phi(-1,1,n+1)$$
Now that we have calculated $I(n,r_k)$, we can plug it back in.
$$\int_0^\infty \frac{x^n\ln x}{(1+x)^2(x-r_k)}dx=I(n,r_k)-\frac{1}{r_k}I(3-n,\frac{1}{r_k})$$
$$=\frac{1}{r_k(r_k+1)^2}\Phi(1/r_k,2,n+1)+\frac{1-n(r_k+1)}{(r_k+1)^2}\Phi(-1,2,n+1)+\frac{1}{r_k+1}\Phi(-1,1,n+1)-\frac{r_k^2}{(r_k+1)^2}\Phi(r_k,2,4-n)-\frac{r_k-(3-n)(r_k+1)}{(r_k+1)^2}\Phi(-1,2,4-n)-\frac{1}{r_k+1}\Phi(-1,1,4-n)$$
Now we can give the original integral as a finite sum of Lerch transcendents by summing over k to m, coming out to a total of $6m$ Lerch transcendents
$$\int_0^\infty\frac{x^n \ln x}{(1+x)^2(1+x^m)}=-\sum_{k=1}^m\frac{r_k}{m}\left(I(n,r_k)-\frac{1}{r_k}I(3-n,\frac{1}{r_k})\right)$$
Where $r_1,r_2,...,r_m$ are roots of the equation $x^m+1=0$
Remember that using the 'cover up' method for partial fractions, we can find $C_k$ for this case
$$C_k=\lim_{x\rightarrow r_k}\frac{x-r_k}{1+x^m}=\frac{1}{mr_k^{m-1}}=-\frac{r_k}{m}$$
Comment: In $I(n,r)$, the second and third Lerch transcendent may be simplified into polygamma functions
Comment: Quite interesting that, even with most of the $r_k$ complex, the result ends up being real


Combining flash files

Question: So, I'm naturally a PHP coder, but I have to use flash for a part of a project.
I was wondering if I have files such as mainsite.swf and page1content.swf, is there a way to simply include the page1content.swf file into a predefined area on the mainsite.swf file (as in PHP's include)?
Also, would it be possible to use this flash "include" to embed external swf's?
Finally, ideally I'd be able to merge these files together, but from what I've read, it's a tricky business, with filenames, referencing etc, so this is optional.
Thanks for your help.
PS: I'll be using actionscript 2.
Answer: It's possible to load an external swf into a movie clip on the stage.
Have a look at this - http://kb2.adobe.com/cps/141/tn_14190.html#main_Using_the_ActionScript_2_0_loadMovie_command
I'm not sure what you mean by merging the movies, what exactly do you need them to do?
Comment: Thanks, this seems pretty much what I wanted, I was just wondering if there was a way of doing it without movieclips etc, just a single line of code on the main frame, that embedded the external swf.

Combining flash files


Map Channel Mutes to Keys or MIDI note toggle

Question: I have some tracks I would like to simultaneously play the mute button on (dub-style), and either record as automation or route to audio tracks.
To be clear, I want to be able to turn the different tracks on and off (up and down in volume could work as well) independently of one another.
Not seeing an option to MIDI-learn on mute in the Channel Mixer, or a way to assign specific mixer channels to key commands.
Using Logic Pro X
Any recommendations?
Comment: this 3rd party site reckons this works for mute too - https://www.logicprohelp.com/forum/viewtopic.php?f=5&t=432 - can't test, don't use Logic.
Answer: This is an XY answer, giving you a solution to what you want to achieve, rather than answering the actual question about automating mutes. Let the downvotes commence…!
I would advise against using mute for this purpose as you might get clicks with these instant changes of volume. There a few better ways to do this:

automate the volume with very short ramps up and down
use an inverted noise gate (set as a "ducker") side chained to another track that plays notes whenever you want the gaps in your other tracks. Something with a constant volume, like a simple synth, would work well for this. The advantage of this method is that you can subtly change the attack, release, threshold, hold etc. on the noise gate to get exactly the sound you want.

Most importantly though, whichever method you choose to use for this ducking, it is much easier to apply this to multiple tracks by first sending them all to one Aux track.
Comment: Ahhh - okay! I might redo the answer or do a different one. I'm in the pub at the moment so maybe not tonight…
Comment: One thing that can be automated is the on/off for any plugin (bypass). Several plugins should be able to stop any signal going through (e.g. noise gate with a high dB). However, Logic tends to pop and click when you automate bypass on and off… I'll have a think over another pint…
Comment: idk Logic very well, I'm Cubase, but you could probably do this on group channels too, rather than auxes. [btw, I've never known Cubase's mutes (or indeed any on/off switch) to click. I'd assumed they're 'softened' some way internally, otherwise people would constantly complain about them.]
Comment: First of all, thank you very much. Updated the question. I want to be able to change the volume or "on" state of each channel independently so that I can *play* the five channels like you would on a mixing board. I thought about doing it with a ducker, which I supposed could be done by sending different MIDI notes to different instruments, each which would be chained to a different gate, or maybe you can send a specific MIDI note to a certain instrument, or perhaps filter out all the other notes.
Comment: Interesting concept BTW…


ImageMagick convert: UnrecognizedMorphologyMethod

Question: I saw in documentation of Imagemagick this command:
convert qc.gif  -morphology Thinning:-1 Skeleton  qc2.gif
But echo this error:
convert: UnrecognizedMorphologyMethod `Thinning' @ error/convert.c/ConvertImageCommand/1957.

But when I list the commands avaliable (convert -list command) it shows:
+morphology
-morphology

Answer: I updated Imagemagick to 6.6.9-1 version and now it works.


Como obter um retorno de uma Exception da WebApi?

Question: Tenho o seguinte método que faz uma requisição de Delete para a minha WebApi:
[HttpPost]
public async Task<IActionResult> Delete(int id, IFormCollection frmCollection)
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("http://localhost:6000/api/");
    var resposta = await httpClient.DeleteAsync($"cencus/{id}");

    //... TRATAR A EXCEPTION AQUI
}

O método de retorno da minha API é o seguinte:
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
  DatabaseConnector dbConn = new DatabaseConnector();
  try
  {
    int affected = dbConn.Connection
        .Execute($"DELETE FROM CENCUS WHERE CODCEN = {id}");

    if (affected > 0)
    {
      return NoContent(); //203
    }
    else
    {
      return NotFound(); //404
    }
  }
  catch (Exception exp)
  {
    return Conflict(exp); //409
  }
  finally
  {
    dbConn.Dispose();
  }
}

Minha dúvida é: em caso de exception na hora de executar o comando SQL, como vou acessar as informações como mensagem da Exception na resposta?
Comment: você aqui já envia o problema para sua WebApi (`return Conflict(exp); //409`) apesar que não sei se isso é bom ... !
Comment: Retorne o status de erro e adicione a mensagem que deseja...
Comment: Qual é a sua dúvida, especificamente? Não dá pra entender o que você pretende fazer...
Answer: Na verdade é mais simples do que eu imaginava, basta tentar converter o retorno e ver se a conversão foi um sucesso:
if (!resposta.IsSuccessStatusCode)
{
    Exception ex = await resposta.Content.ReadAsAsync<Exception>() as Exception;

    if (ex != null) {
        //O retorno da API foi uma exception...
    }
}


response time in python not the same as postman

Question: When I execute the code below the response time is 0.4, but when I make the exact request in postman the response time is ~4, what's wrong with my code?
<code>import requests

url = "https://www.wechall.net/challenge/training/mysql/auth_bypass2/index.php"

payload = {'username': 'admin\' and username like \'a%\' and sleep(4)#',
'password': '',
'login': 'Login'}

headers = {
  'Content-Type': 'multipart/form-data; boundary=--------------------------626487670766176098971255'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.elapsed.total_seconds())
</code>
Answer: According to https://kite.com/python/docs/requests.Response.elapsed, elapsed measures the time taken between sending the first byte of the request and finishing parsing the headers, and not until the full response has been transfered.
So in this case, time calculated by postman client is the response time for the api.


Prevent Typing a Line Break in textarea Input With onkeyup="this.value=this.value.replace..."

Question: I don't want users to type some characters in my textarea input.
I use a global variable (php): `
$preventedInputCharacters = '=:;?/$*<>|\[\]\'';

And use it in textarea input (Sorry for the escaping backslashes, it is from a php string.):
onkeyup="this.value=this.value.replace(/['.$preventedInputCharacters.']/g, \'\')"

The problem is, when user uses line break (enter key), it harms my code so I want to disable it too.
Where and how should I modify to add "line break" to my prevented input characters?
Thank you.
Answer: Adding \n is the answer:
onkeyup="this.value=this.value.replace(/['.$preventedInputCharacters.'\n]/g, \'\')"

Answer: You can done it by calling jquery event keycode which will prevent the enter key function

$('#textarea').keypress(function(event){
  var key_code = event.keyCode;
  if(key_code==13){
    event.preventDefault();
  }
});
Comment: Thank you for your answer. Does this method prevent line breaks from a copied text?
Comment: no it won't it will prevent only when the user manually add line break into the field but using regex method we can prevent here is a sample
someText = someText.replace(/(\r\n|\n|\r)/gm, "");


MEF Recomposition of child containers

Question: I've built a MEF container that creates a service. I build another MEF container with these services from the first container. The problem is those services get recomposed when being added to the second container.
<code>[Export(typeof(IFoo))]
public class Foo : IFoo
{
    [Import(typeof(IServiceA))]
    public IServiceA A { get; set; }
}

[Export(typeof(IServiceA))]
public class ServiceAImpl : IServiceA
{
    public ServiceAImpl()
    {
        Console.Out.WriteLine("Service A Created");
    }
}

//Create the parent container
var parentContainer = new CompositionContainer(Composer.AggregateCatalog);
IFoo foo = parentContainer.GetExportedValue<IFoo>();

//..... some work

//Create a child container providing it an existing instance of IFoo
var childContainer = new CompositionContainer(Composer.AggregateCatalog);
var batch = new CompositionBatch();
batch.AddPart(foo); //Add existing IFoo

//This causes a recomposition of IFoo resulting in
//a new instance of IServiceA to be created and injected
childContainer.Compose(batch);
</code>
"Service A Created" gets called twice on the last line above when the container creates the composition because it's trying to recompose Foo, which I don't want it to.
Does anyone have a solution to this? I've tried explicitly specifying AllowRecomposition=false too but that doesn't work either.
Answer: What are you trying to achieve with parent/child containers?  In the code you show, you're not actually creating a parent and a child, you're creating two unrelated containers.  To actually create a child container, do the following:
<code>var childContainer = new CompositionContainer(childCatalog, parentContainer);
</code>
Then anything in the parent will automatically be available in the child (so you won't have to add it via a batch).  You'll want a different catalog for the child container with the parts you want to be in the child.

MEF Recomposition of child containers


Is it possible to add a class to an image field of a node wise

Question: I have a content type that has title, body, image etc. I am displaying the Title, image with caption and body using Manage Display. But here there is no option to align (Left, Right, Center) the image. How to align the image node wise.
OR
Is it possible to add a class to an image field of a node wise.
Answer:
Have you checked the already built-in classes drupal adds to fields in the HTML? That is the way I style a single content view.
Is this https://drupal.org/node/1795294 the module? In the description they explain how to add a class.

PD: I wanted to leave a comment but do not have enough reputation to do so.
Answer: Francisco has the right idea. Use Display Suite to wrap a div around your displayed image, and put your css class there.
Another option is to use the insert module and style the image any way you want after inserting it into another field.


Android: Loading data from a URL to SQLite

Question: What's the easiest way to populate a SQLLite table with data off a URL?
I'm writing a Delphi web app that will generate a file on a server for my Android app to download.
In Delphi, I'll probably save it as a .csv file and use bulk import to import into MS SQL Server.
What's the easiest / best practice way to do this in Android? How would I download the file from the URL and then load it into SQLLite?
Many thanks for any pointers.
Comment: [HttpClient](http://developerlife.com/tutorials/?p=288) for the download.
Answer:
How would I download the file from the URL

Use HttpClient, as Frayser indicates.

and then load it into SQLLite?

You neglected to tell us what format you will use for the download.
If the format is the CSV you mentioned for other uses, parse it and use SQL INSERT statements (execSQL() or insert() with your SQLiteDatabase object). Wrap the INSERT statements in a transaction to improve performance, since each transaction requires a flash write, and flash writes are slow.
If you are downloading a complete SQLite database, just put it in getDatabasePath(), and open it when needed.
Comment: Thanks, I tried to explain, whatever format is easiest / best. CSV it is!

Many thanks


Return only unique values from foreach

Question: I'm currently trying to use a foreach to return all the addresses using the relation from my event model. All is fine, returns all the addresses but will return even the duplicate results. I tried the array_unique but not sure I have the syntax correct.
<?php
    foreach ($data->events as $address) {
        //array_unique($address, SORT_REGULAR);
        echo $address->getAddressString() ."

";
    }
  ?>

Comment: Dont select duplicates in the 1st place - how are you querying the database
Comment: This is code I inherited, it's not got documentation and is fairly spaghetti like, I would happily change how the database is queried but due to time constraints at the minute it is important that I just get this working.

It looks at the event model and goes through to the relations public function getAddressString() {
        return $this->venue->address->building_name . ', ' . $this->venue->address->street_name . ', ' . $this->venue->address->city . ', ' . $this->venue->address->post_code;
    }

I'm not sure how else the data is being pulled but I know the function is being used elsewhere
Answer: You should try with array store technique using array_unique
//  First Store data in $arr
$arr = array();
foreach ($data->events as $address) {
    $arr[] = $address->getAddressString();
}
$unique_data = array_unique($arr);
// now use foreach loop on unique data
foreach($unique_data as $val) {
       echo $val;;
}

Answer: You can add each unique element to a new array and then see if they exist with in_array():
$uniques = [];
foreach($data->events as $address){
    if(!in_array($address->getAddressString(), $uniques)){
        $uniques[] = $address->getAddressString();
        echo $address->getAddressString()."

";
    }
}

Comment: `in_array` will get slower and slower as the array grows. Better to save the values as keys instead. No function calls are required and uniqueness is guaranteed. By the way if you need to check if a value exists in an array, `array_key_exists` is much faster than `in_array`. I always store unique values as keys rather than values if possible. Of course, the OP should try to get the data model to return only unique values in the first place.
Answer: array_unique should do it. Try this:
<?php
foreach (array_unique($data->events) as $address) {
    echo $address->getAddressString() ."

";
}
?>

Comment: Error : Object of class Event could not be converted to string.

I believe this what I tried first.
Answer: There's a faster way, if you'd like to prematurely optimize.
<?php
    $arr = array();
    foreach ($data->events as $address) {
        $arr[$address->getAddressString()] = 'a'; // value doesn't matter
        // using inherent uniqueness of keys.
    }
    // $addrs = array_keys($arr);
    // optionally, take all those array keys and put them in values.
    // keys would become regular numeric keys
  ?>

That should run faster than any of the other answers here. But it will only make a difference if you are dealing with large amounts of data.
If you want to echo, you will want to do array_keys if you didn't above. Here it is in one line:
echo implode(', ',array_keys($arr)); // comma separated list of unique values

Or this, for sorted:
$addrs = array_keys($arr);
sort($addrs);
echo implode(', ',$addrs); // sorted list

Finally, I'd like to add that you should be getting unique, ordered results from your data model in the first place. The database is much faster and better at simple tasks like ordering unique results than your PHP code ever will be.
SELECT DISTINCT `address` FROM `table`
WHERE `city` LIKE 'Lodi'
ORDER BY 'address' ASC

Comment: Array keys in php are inherently unique and it's a fairly well known secret/shortcut to use the keys to store unique values rather than the values. Php also has functions like ksort, etc that apply directly to keys.
Comment: I won't be working with large amount of data for this particular instance, but this will no doubt come in handy when I'm exporting all of this at once..
Answer: You can try this -
<?php
    $all_addresses= array();
    foreach ($data->events as $address) {
        $all_addresses[]= $address->getAddressString();
    }
    $all_addresses= array_unique($all_addresses);
    foreach($all_addresses as $val) {
       echo $val . "

";
    }
?>

Or
Instead of
    foreach($all_addresses as $val) {
       echo $val . "

";
    }

Do
    echo implode('

', $all_addresses);

Comment: This answer did not return any results for me in the address. I'm not sure if it's my implementation as it looks similair to the working code submitted by Php developer.
Answer: Even though the question was different I agree with Steve. You should adjust your query. Its faster, more readable and maintainable. You don't want to do anything you don't need to do.
If i gathered correctly you have to tables that are in relation. Great. Try something like this:
$var1 = YourModel::model()
->with('address_table')
->findAllByAttributes(array(-optional if you want certain columns-),
                     array('condition'=>'`type` LIKE :type AND `typeId` = :typeId AND `suggestionId` IS NULL', 'params'=>array(':type'=>$_GET['type'], ':typeId'=>$_GET['typeId']), 'group'=>'address_table.`column`'));

Most important thing here for you is the 'group' command which like the name says groups results and returns only unique ones. Be sure to prefix it correctly, either table name or alias depending on what you are working with.
Hope it helps.

Return only unique values from foreach


Why are my dialogs not draggable in jQuery?

Question: I've created a dialog in jQuery but they are not draggable even though i've set 'draggable: true'. Can anyone see what's wrong?
HTML:

    Lesson Details

'.$l['name'].'

Resources and Objectives

JS:
$('.popUpLink').each(function()
{
    $divDialog = $(this).next('.popUpDialog');
    $.data(this, 'dialog', $divDialog.dialog(
    {
        autoOpen: false,
        modal: true,
        title: $divDialog.attr('title')
        //draggable: true
    }));
}).click(function()
{
    $.data(this, 'dialog').dialog('open');
    return false;
});

Comment: do you have an error message? do you load jQuery UI? your draggable line is commented out. Activate it and put a comma after the previous line.
Comment: Works for me: http://jsfiddle.net/Wzya4/
Comment: @jgauffin thats because the jQuery UI library on jsfiddle is the complete library ...
Comment: Can you show us your test page somewhere?
Comment: No error messages or anything :s
Answer: You don't need to include the draggable:true as its the default value ..
But you do need to include 2 additional libraries to make draggable work:

Have a look at the dependencies section on the docs
When you download the jQuery UI Libraries you have to select which "modules" you require - your need to select the ones above or better still reference the complete jQuery UI library using Googles CDN
Comment: @YanickRochon have a look at the link i included - when you download the jQuery UI library you pick which libraries you use - maybe you selected all - or use Googles CDN ?
Comment: where do you read about those dependencies? I have used the `draggable` option and never used those two scripts before.
Comment: These are my two dependancies:
Comment: Hmmmmmmm, this is bugging me so bad! Do you know where the ajax.googleapis link is for the two dependencies in your answer are?
Comment: the googleapis link you posted is the complete library so it should work
Answer: Youve missed a comma after:
title: $divDialog.attr('title')

You could have probably seen this in a javascript console or debugger
Comment: It should be draggable per default
Comment: that was my error when editing the code here when I was posting the question. My bad


Loading log4j2.xml or properties configuration file during runtime by specifying path

Question: I am trying to load log4j2.xml or properties file from a specific location which will be provided at runtime.
This is part of a migration from log4j 1.x to log4j 2.x version. I have seen there are lots of changes in the logging configuration loading sequences in log4j2. So right now after searching I have the following methods below -
1 -
 Configurator.reconfigure(new URI("URI of your file"));

2 -
// import org.apache.logging.log4j.core.LoggerContext;
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File("path/to/a/different/log4j2.xml");

// this will force a reconfiguration
context.setConfigLocation(file.toURI());

But they say that LoggerContext class is not part of the public API, is it still the case now ?
3-
InputStream inputStream = new FileInputStream("C:/path/to/log4j2.xml");
ConfigurationSource source = new ConfigurationSource(inputStream);
Configurator.initialize(null, source);

4- Or simply
Configurator.initialize(null, "/path/to/log4j2.xml");

I am confused if all of these are viable or are to be used in different scenarios and have different outcomes.
Also the functions that I am trying to replace are DOMConfigurator and PropertyConfigurator. I know log4j2 will find configurations automatically in classpath but incase I have multiple configuration files for different environments etc or scenarios or the configuration file is outside the classpath, somewhere else on the system - I am trying to use these above functions to do it.
Please help as I am stuck here, thank you.
Answer: If no LoggerContext is associated with the caller, all these methods have the same effect: they create a LoggerContext and configure it using the configuration source provided.
The 4 methods start to differ if there is a LoggerContext associated with the caller. This can happen if any LogManager's get* method was called before (e.g. in a static initializer). If this happens, the first two methods will replace that context's configuration, while the last two are no-ops.
PropertyConfigurator and DOMConfigurator in Log4j 1.x worked differently: unless you used log4j.reset=true key they modified the previous configuration. Although the two classes have been ported to the newest log4j-1.2-api, the "reset" semantic is not implemented and they behave like Configurator.reconfigure restricted to a single configuration format.
Remark: Configurator.reconfigure tries to guess the configuration format to choose the appropriate ConfigurationFactory. Since both Log4j 2.x and Log4j 1.x have the properties and XML formats, all properties and XML files will interpreted as native Log4j2 configuration files. Check this question for a workaround.
Comment: I would still try a couple of alternatives before falling back to programmatic configuration: 1. the [Log4j2 system property](https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties) `log4j2.configurationFile`, 2. a custom [ConfigurationFactory](https://logging.apache.org/log4j/2.x/manual/extending.html#ConfigurationFactory). And if programmatic configuration is needed I would rather use `Configurator.reconfigure`.
Comment: Thanks for the answer, this solves the confusion to a large extent. So bottom line is if I have changed my log4j 1.x XML and properties files to the new log4j2.x format, I can load these configurations before the application starts using Configurator.initialize() right ?
Comment: _"Before the application starts"_ is hard to achieve, since usually even the main class has a static logger field. However, if the configuration file is called `log4j2.properties` (or `log4j2.xml` if you prefer a less messed-up format), Log4j 2 will pick it up automatically (see [automatic configuration](https://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration)) and you don't need to do anything at all.
Comment: thanks for the reply, yep I am aware about the automatic loading of the log4j2.xml. Only problem here for me is that the log4j2.xml is not in classpath, its in the WEB-INF folder and not inside the classes folder under it. In this case I do need to load it via the path programatically right ?
Comment: thank you again for following up, will try these alternate options and replace configure with reconfigure, as it seems like the safer one to use.
Comment: Is there anyway to mimic the behavior of the absence of the old log4j.reset=true parameter ? Because I have a situation now to modify the current configuration, and on the official log4j2 website I see they are using context.getConfiguration(); then use FileAppender.createAppender method to create the appender then add it to the existing configuration, but now its seems like the createAppender method is deprecated. Can I still use the .createAppender method, or are there any alternatives ?
Comment: I have figured it out no issue, thanks


Erro com sintaxe no Python 3.7

Question: Estou praticando um exercício do curso e me deparei com o seguinte erro abaixo. Estou utilizando o Python 3.7. Qual o problema nesta digitação?
convite = 'Flavio Henrique Almeida'
parte1 = convite[0:4]
parte2 = convite[11:15]
print "%s %s" % (parte1, parte2)

Erro:
File "<stdin>", line 1
  print "%s %s" % (parte1, parte2)
                ^
SyntaxError: invalid syntax

Answer: O erro está no print "%s %s" % (parte1, parte2). No Python 3 você precisa colocar os argumentos do print entre parênteses (, ), como qualquer outra chamada de função.
No caso ficaria assim:
print("%s %s" % (parte1, parte2))

Erro com sintaxe no Python 3.7


Managing multiple asynchronous NSURLConnection connections

Question: I have a ton of repeating code in my class that looks like the following:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];

The problem with asynchronous requests is when you have various requests going off, and you have a delegate assigned to treat them all as one entity, a lot of branching and ugly code begins to formulate going:
What kind of data are we getting back? If it contains this, do that, else do other. It would be useful I think to be able to tag these asynchronous requests, kind of like you're able to tag views with IDs.
I was curious what strategy is most efficient for managing a class that handles multiple asynchronous requests.
Answer: I track responses in an CFMutableDictionaryRef keyed by the NSURLConnection associated with it. i.e.:
connectionToInfoMapping =
    CFDictionaryCreateMutable(
        kCFAllocatorDefault,
        0,
        &kCFTypeDictionaryKeyCallBacks,
        &kCFTypeDictionaryValueCallBacks);

It may seem odd to use this instead of NSMutableDictionary but I do it because this CFDictionary only retains its keys (the NSURLConnection) whereas NSDictionary copies its keys (and NSURLConnection doesn't support copying).
Once that's done:
CFDictionaryAddValue(
    connectionToInfoMapping,
    connection,
    [NSMutableDictionary
        dictionaryWithObject:[NSMutableData data]
        forKey:@"receivedData"]);

and now I have an "info" dictionary of data for each connection that I can use to track information about the connection and the "info" dictionary already contains a mutable data object that I can use to store the reply data as it comes in.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSMutableDictionary *connectionInfo =
        CFDictionaryGetValue(connectionToInfoMapping, connection);
    [[connectionInfo objectForKey:@"receivedData"] appendData:data];
}

Comment: Aldi... it *is* thread safe provided you start all connections from the same thread (which you can do easily by invoking your start connection method using performSelector:onThread:withObject:waitUntilDone:).

Putting all connections in an NSOperationQueue has different problems if you try to start more connections than the max concurrent operations of the queue (operations get queued instead of running concurrently). NSOperationQueue works well for CPU bound operations but for network bound operations, you're better off using an approach that doesn't use a fixed size thread pool.
Comment: This is not thread safe if the delegate is being called from multiple threads.  You must use mutual exclusion locks to protect the data structures.  A better solution is subclassing NSURLConnection and adding response and data references as instance variables.  I am providing a more detailed answer explaining this at Nocturne's question: http://stackoverflow.com/questions/1192294/cocoa-any-checks-required-for-multiple-asynchronous-nsurlconnections
Comment: Just wanted to share that for iOS 6.0 and above, you can use a `[NSMapTable weakToStrongObjectsMapTable]` instead of a `CFMutableDictionaryRef` and save the hassle. Worked well for me.
Comment: Since it is possible that two or more asynchronous connections may enter the delegate methods at a time, is there anything specific that one would need to do to ensure correct behavior?
Comment: (I have create a new question here asking this: http://stackoverflow.com/questions/1192294/cocoa-any-checks-required-for-multiple-asynchronous-nsurlconnections )
Comment: As stated before, this is not thread safe. I'd rather prefer to solve this issue by using NSOperation subclasses and NSOperationQueue, which in addion allows you to manage the number of ongoing concurrent requests at one time. Each of these operations may handle their NSURLConnection callbacks and inform their individual delegates about progress and results.
Comment: This is really useful - thanks! How do I get rid of this warning? "warning: passing argument 1 of 'CFDictionaryAddValue' discards qualifiers from pointer target type"
Comment: This really helped as well! And @josh-brown , one reason you might be getting this warning is if you are using CFMutableDictionaryRef  as a pointer... I mean `CFMutableDictionaryRef *dic = CFDictionaryCreateMutable(...` instead of just `CFMutableDictionaryRef dic = CFDictionaryCreateMutable(...`
Comment: Another method for doing this is shown here: https://github.com/dbowen/Demiurgic-JSON-RPC. @Matt Gallagher, what are the pros and cons of this method versus your own solution?
Answer: I have a project where I have two distinct NSURLConnections, and wanted to use the same delegate. What I did was create two properties in my class, one for each connection. Then in the delegate method, I check to see if which connection it is

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if (connection == self.savingConnection) {
        [self.savingReturnedData appendData:data];
    }
    else {
        [self.sharingReturnedData appendData:data];
    }
}

This also allows me to cancel a specific connection by name when needed.
Comment: @adit Why will this lead to a race condition?  It's a new concept to me.
Comment: be careful this is problematic as it will have race conditions
Comment: How do you assign the names (savingConnection and sharingReturnedData) for each connection in the first place?
Comment: @adit, no, there is no race condition inherent to this code. You'd have to go pretty far out of your way with the connection creation code to create a race condition
Comment: your 'solution' is exactly what the original question is looking to avoid, quoting from above: '... a lot of branching and ugly code begins to formulate ...'
Comment: I'm new in iOS/Objective-C. I tried using this kind of approach for my `NSURLConnection`s and doesn't work when used in if-else
Answer: Subclassing NSURLConnection to hold the data is clean, less code than some of the other answers, is more flexible, and requires less thought about reference management.
// DataURLConnection.h
#import <Foundation/Foundation.h>
@interface DataURLConnection : NSURLConnection
@property(nonatomic, strong) NSMutableData *data;
@end

// DataURLConnection.m
#import "DataURLConnection.h"
@implementation DataURLConnection
@synthesize data;
@end

Use it as you would NSURLConnection and accumulate the data in its data property:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    ((DataURLConnection *)connection).data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [((DataURLConnection *)connection).data appendData:data];
}

That's it.
If you want to go further you can add a block to serve as a callback with just a couple more lines of code:
// Add to DataURLConnection.h/.m
@property(nonatomic, copy) void (^onComplete)();

Set it like this:
DataURLConnection *con = [[DataURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
con.onComplete = ^{
    [self myMethod:con];
};
[con start];

and invoke it when loading is finished like this:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    ((DataURLConnection *)connection).onComplete();
}

You can extend the block to accept parameters or just pass the DataURLConnection as an argument to the  method that needs it within the no-args block as shown
Comment: This is a fantastic answer that worked really well for my case.  Very simple and clean!
Answer: THIS IS NOT A NEW ANSWER. PLEASE LET ME SHOW YOU HOW I DID
To distinguish different NSURLConnection within same class's delegate methods, I use NSMutableDictionary, to set and remove the NSURLConnection, using its (NSString *)description as key.
The object I chose for setObject:forKey is the unique URL that is used for initiating NSURLRequest, the NSURLConnection uses.
Once set NSURLConnection is evaluated at
-(void)connectionDidFinishLoading:(NSURLConnection *)connection, it can be removed from the dictionary.

// This variable must be able to be referenced from - (void)connectionDidFinishLoading:(NSURLConnection *)connection
NSMutableDictionary *connDictGET = [[NSMutableDictionary alloc] init];
//...//

// You can use any object that can be referenced from - (void)connectionDidFinishLoading:(NSURLConnection *)connection
[connDictGET setObject:anyObjectThatCanBeReferencedFrom forKey:[aConnectionInstanceJustInitiated description]];
//...//

// At the delegate method, evaluate if the passed connection is the specific one which needs to be handled differently
if ([[connDictGET objectForKey:[connection description]] isEqual:anyObjectThatCanBeReferencedFrom]) {
// Do specific work for connection //

}
//...//

// When the connection is no longer needed, use (NSString *)description as key to remove object
[connDictGET removeObjectForKey:[connection description]];

Answer: One approach I've taken is to not use the same object as the delegate for each connection.  Instead, I create a new instance of my parsing class for each connection that is fired off and set the delegate to that instance.
Comment: Much better encapsulation with respect to one connection.
Answer: Try my custom class, MultipleDownload, which handles all these for you.
Comment: on iOS6  can't use the NSURLConnection as the key.
Answer: I usually create an array of dictionaries. Each dictionary has a bit of identifying information, an NSMutableData object to store the response, and the connection itself. When a connection delegate method fires, I look up the connection's dictionary and handle it accordingly.
Comment: Ben, would it be okay to ask you for a piece of sample code? I'm trying to envision how you're doing it, but it's not all there.
Comment: In particular Ben, how do you look up the dictionary? You can't have a dictionary of dictionaries since NSURLConnection doesn't implement NSCopying (so it can't be used as a key).
Comment: Matt has an excellent solution below using CFMutableDictionary, but I use an array of dictionaries. A lookup requires an iteration. Its not the most efficient, but it's fast enough.
Answer: One option is just to subclass NSURLConnection yourself and add a -tag or similar method. The design of NSURLConnection is intentionally very bare bones so this is perfectly acceptable.
Or perhaps you could create a MyURLConnectionController class that is responsible for creating and collecting a connection's data. It would then only have to inform your main controller object once loading is finished.
Answer: in iOS5 and above you can just use the class method
sendAsynchronousRequest:queue:completionHandler:
No need to keep track of connections since the response returns in the completion handler.
Answer: As pointed out by other answers, you should store connectionInfo somewhere and look up them by connection.
The most natural datatype for this is NSMutableDictionary, but it cannot accept NSURLConnection as keys as connections are non copyable.
Another option for using NSURLConnections as keys in NSMutableDictionary is using NSValue valueWithNonretainedObject]:
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
NSValue *key = [NSValue valueWithNonretainedObject:aConnection]
/* store: */
[dict setObject:connInfo forKey:key];
/* lookup: */
[dict objectForKey:key];

Answer: I like ASIHTTPRequest.
Comment: I really like the 'blocks' implementation in ASIHTTPRequest - it's just like Anonymous Inner Types in Java. This beats all the other solutions in terms of code cleanliness and organisation.
Answer: I decided to subclass NSURLConnection and add a tag, delegate, and a NSMutabaleData.  I have a DataController class that handles all of the data management, including the requests.  I created a DataControllerDelegate protocol, so that individual views/objects can listen to the DataController to find out when their requests were finished, and if needed how much has been downloaded or errors. The DataController class can use the NSURLConnection subclass to start a new request, and save the delegate that wants to listen to the DataController to know when the request has finished. This is my working solution in XCode 4.5.2 and ios 6.
The DataController.h file that declares the DataControllerDelegate protocol). The DataController is also a singleton:
@interface DataController : NSObject

@property (strong, nonatomic)NSManagedObjectContext *context;
@property (strong, nonatomic)NSString *accessToken;

+(DataController *)sharedDataController;

-(void)generateAccessTokenWith:(NSString *)email password:(NSString *)password delegate:(id)delegate;

@end

@protocol DataControllerDelegate <NSObject>

-(void)dataFailedtoLoadWithMessage:(NSString *)message;
-(void)dataFinishedLoading;

@end

The key methods in the DataController.m file:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;
    NSLog(@"DidReceiveResponse from %@", customConnection.tag);
    [[customConnection receivedData] setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;
    NSLog(@"DidReceiveData from %@", customConnection.tag);
    [customConnection.receivedData appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;
    NSLog(@"connectionDidFinishLoading from %@", customConnection.tag);
    NSLog(@"Data: %@", customConnection.receivedData);
    [customConnection.dataDelegate dataFinishedLoading];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;
    NSLog(@"DidFailWithError with %@", customConnection.tag);
    NSLog(@"Error: %@", [error localizedDescription]);
    [customConnection.dataDelegate dataFailedtoLoadWithMessage:[error localizedDescription]];
}

And to start a request: [[NSURLConnectionWithDelegate alloc] initWithRequest:request delegate:self startImmediately:YES tag:@"Login" dataDelegate:delegate];
The NSURLConnectionWithDelegate.h:
    @protocol DataControllerDelegate;
@interface NSURLConnectionWithDelegate : NSURLConnection

@property (strong, nonatomic) NSString *tag;
@property id <DataControllerDelegate> dataDelegate;
@property (strong, nonatomic) NSMutableData *receivedData;

-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString *)tag dataDelegate:(id)dataDelegate;

@end

And the NSURLConnectionWithDelegate.m:
#import "NSURLConnectionWithDelegate.h"

@implementation NSURLConnectionWithDelegate

-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString *)tag dataDelegate:(id)dataDelegate {
    self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
    if (self) {
        self.tag = tag;
        self.dataDelegate = dataDelegate;
        self.receivedData = [[NSMutableData alloc] init];
    }
    return self;
}

@end

Answer: Every NSURLConnection has an hash attribute, you can discriminate all by this attribute.
For example i need to mantain certain information before and after connection, so my RequestManager have an NSMutableDictionary to do this.
An Example:
// Make Request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:request delegate:self];

// Append Stuffs
NSMutableDictionary *myStuff = [[NSMutableDictionary alloc] init];
[myStuff setObject:@"obj" forKey:@"key"];
NSNumber *connectionKey = [NSNumber numberWithInt:c.hash];

[connectionDatas setObject:myStuff forKey:connectionKey];

[c start];

After request:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Received %d bytes of data",[responseData length]);

    NSNumber *connectionKey = [NSNumber numberWithInt:connection.hash];

    NSMutableDictionary *myStuff = [[connectionDatas objectForKey:connectionKey]mutableCopy];
    [connectionDatas removeObjectForKey:connectionKey];
}


I want to mix a friend's 96kHz .w64 files from Sonar but Logic Pro X can't read them

Question: My friend records jams at 96kHz using Cakewalk Sonar on a PC, and the audio is saved as .w64 (Sony format). I offered to mix the tracks but my Mac's Logic Pro X DAW can't read the files.
There are converters online, but some are limited to 1GB whereas my files are as big as 7GB. I am reluctant to invest in an expensive converter only to find it either doesn't work, or I lose a lot of information in the conversion (after all a WAV file can't hold 7GB since it's limited to 4GB).
My friend wants to keep working at 96kHz and won't go back to provide smaller formats.
Suggestions?
Comment: The reason Sonar uses.w64 format is because the file is too big to store in .wav. The obvious solution would be to chop the files into shorter audio segments  so they can be filed as .WAV. you can do that and rejoin them end-to-end in a different DAW with no data loss.
Comment: There's also the rather obvious fact that he's wasting bandwidth recording at miles (well, kilometers) above the Nyquist for human auditory capability.   Tell him if he wants free mixing work done, he needs to compromise.
Comment: @CarlWitthoft actually, with suitable dithering could could achieve a not-completely-rubbish fidelity in a 2-bit 96kHz file...
Comment: Will your friend not save them as broadcast wave or AIFF? Then you don't have to convert and both formats support 96 kHz.
Comment: @alephzero Broadcast wave definitely supports files larger than 4 GB - up into Exabytes. Not sure about AIFF.
Comment: @ToddWilcox sure, the actual *data* in a .wav flle is (almost always) stored in PCM format which is exactly the same as raw audio data, so there is no size limit. But the RIFF *container* holding the data can only handle 2GB segments of data. Conceptually, you could have several 2GB data segments in one ".wav" file, but AFAIK no software developers have ever considered that as a "standard" way to use .WAV. In any case, the file size limit on 32-bit file systems was another hard limit when working practices for .WAV files were being developed (and enshrined in computer software).
Comment: Or (and you'll lose a friend but have fun in the process) take the 96k files and run them thru a  c, or Matlab, or python script to reduce them to 2-bit sample depth  :-)
Answer: I believe that VideoLan aka VLC media player can read .w64 files and it is also capable of transcoding. You might also be able to split the files leaving the sample rate untouched. As CarlWitthoft pointed out, 96k is probably excessive and may actually be a problem for some track effects etc.
VLC is free open source software and there is an OSX binary available.
You might also check the docs for ffmpeg/libavcodec which may support w64.
Comment: Yes, ffmpeg supports w64 (as does VLC, which is entirely based on ffmpeg).
Comment: Downloaded VLC and it accepts my 7GB .w64 file, but shows duration as 0:00 and nothing plays.
Answer: Sony's Sound Forge application is able to read 96KHz 24-bit .w64 files and convert them to 48KHz 24bit files I can use. But it is very cumbersome (read file, wait for peaks to be gathered, then save and convert). It took me several hours to convert about 20 6GB files.
This worked but is not a good long-term solution. I would prefer a batch processing app, or I will try to talk my friend into producing smaller files.
I would like to know why 96KHz is overkill.


Configuring a PTR record in domains.google for an SMTP server

Question: I've found several threads related to this, but they are all very dated so I want to get some clarification.
I use an AWS ec2 instance with an elastic-ip, I've set up an SMTP (sendonly) mail-server using postfix on ubuntu 18.04, and I manage my DNS through domains.google.  I'm setting up all my MX, SPF, dmarc/dkim records, but I'm confused in how I set up my PTR record.
When I select "PTR", it asks for a host-name and a data-field.  Here is my confusion:
The PTR record is considered a reverse-DNS no?  Shouldn't it be an IP address which points to my smtp.mydomain.com?  When I type the IP address in the host-name field, it appends .mydomain.com so it looks something like:
###.###.###.###.mydomain.com  ->  smtp.mydomain.com
Should it not just be:
###.###.###.### -> smtp.mydomain.com?
Answer: PTR is managed by the owner of the IP. You will need to talk with Amazon about it. The public IPv4 address you are using needs to be an Elastic IP though.
https://aws.amazon.com/blogs/aws/reverse-dns-for-ec2s-elastic-ip-addresses/
Comment: I'll also point out that AWS blocks port 25 outbound as well, without making a request to support to remove the restriction.
Answer: Reverse DNS uses PTR records, but they are not in the zone for your domain, but in the zone matching your IP.
If you IP address is 192.0.2.1, then the PTR record is at the address 18.104.22.168.in-addr.arpa, and its value is the name you want to come back when someone does a reverse lookup for that address (e.g. smtp.example.org).
Having a PTR record inside your example.org zone does not serve any useful purpose (at least when it comes to reverse DNS).
Since the zone which holds your PTR record is shared with the many other people having an IP in the same /24, you can't edit the PTR directly in that zone. But your ISP can provide a way to provide the name you want to see returned, and they will put it in the relevant zone. See tilleyc's answer for details in the case of Amazon.
Answer: The answers are as Tilleyc and jcaron emphasized.
rDNS records are managed through the ip provider.  In this case, through AWS.  Navigate to EC2 dashboard, to Elastic IP, select & configure reverse DNS.  Worked like a charm.  My mail-tester is reporting 9/10 now, I just have to configure DKIM correctly but that is unrelated to PTR records!


Solve $y''(x)^2= (1+y'(x)^2)^n$ where $n \in \mathbb N$

Question: How is the familiar ODE solved?
$$y''(x)^2= (1+y'(x)^2)^n$$
Case $n=3$ is known, with two arbitrary constants
$$(x-h)^2+(y-k)^2 =1$$
Substitution $y'(x)= \tan (u)$ is not helping always.
Comment: You could try $y'=\sinh(u)$, but for general $n$ this will not simplify much.
Comment: $z = y'.{}{}{}{}{}$
Comment: Thanks. Have no special functions ever been constructed ? I ask because the circle case is so well known but the rest are not and there is only a numerical option.
Answer: This is my solution. But at the end one has to use Chebyshev's theorem on the integration of binomial differentials to find values of $n$ for which the last equation can integrated.
$$ y''^2 = (1+y'^2)^n \\ \pm y'' = (1+y'^2)^{n/2} \\
 \pm\frac{y''}{(1+y'^2)^{n/2}} = 1 \\
$$
Assume a solution with a derivative that is not the zero function, then one can multiply with $y'$
$$
 \pm\frac{y'y''}{(1+y'^2)^{n/2}} = y' \\
 \pm \int \frac{y'y''}{(1+y'^2)^{n/2}}dx = y + c \\
$$
If one sets $z = y'$ it can be easily integrated
$$
\int \frac{zdz}{(1+z^2)^{n/2}} = \frac{\left(z^2+1\right)^{1-\frac{n}{2}}}{2-n}
$$
That means
$$
\pm \frac{\left(y'^2+1\right)^{1-\frac{n}{2}}}{2-n} = y + c\\
\frac{y'^2}{(\mp(2-n)(y + c))^{\frac{2}{2-n}}-1} = 1 \\
\pm\frac{y'}{\sqrt{\left( \mp(2-n)(y + c) \right)^{\frac{2}{2-n}}-1}} = 1
$$
Change variables $y + c = u$ so $dy =du$
$$
\frac{du}{\left(\left( \mp(2-n)u \right)^{\frac{2}{2-n}}-1\right)^{1/2}} = \mp dx
$$
Here I recognize it to be of the form
$$
u^p(a+bu^q)^r du
$$
where $p=0$, $q=\frac{2}{2-n}$ and $r=-\frac{1}{2}$, (also $a = -1$ and $b=(\mp (2-n))^{\frac{2}{2-n}}$). For the integral of such forms see the theorem of Chebyshev in integration of differential binomial
Comment: Ok thanks. And. y(x)=?
Comment: check this, I hope it helps !
Comment: Wow! So even when the three conditions are not satisfied, we have incomplete beta function / Hypergeometric function closed form solutions?
Comment: I'm not sure I understand what you mean


how to save Sparql endpoints in RDF format by Apache Jena?

Question: I'm wondering how to save Sparql endpoints in RDF format by Apache Jena (or other tool) ?
I have used
<code>CONSTRUCT { ?s ?p ?o }
WHERE { ?s ?p ?o }
LIMIT 10
</code>
and got the data but I need to save them local in my laptop!
P.S. (I have to handle the DBpedia sparql endpoints)
Answer: Don't do this, this is an extremely inefficient way to take a copy of a public endpoint and is often frowned upon in the same way that bulk web crawling is.
Many public endpoints like DBPedia actually publish data dumps which you can download and work with locally, in the case of DBPedia see http://wiki.dbpedia.org/Downloads39 for the current downloads


Use the Web Share Target API on PWAs in IOS

Question: is it possible to use the Web Share Target API to upload a photo from the mobile gallery into the PWA in IOS? I read in some articles that it is only possible for Android devices but I could not find any replacement for this feature in IOS.
Comment: Right now I don't think Safari supports the Web Share Target API. So no
But you should be able to just use a traditional file upload from within the application to access the gallery. Maybe not what you really want, but I know that and camera access work on iOS.
Answer: It is currently not possible to use the share target API on iOS. Would love to see it too.
Comment: See https://caniuse.com/mdn-html_manifest_share_target


Nginx 502 Bad Gateway - 111: Connection refused, port not being listened to

Question: I'm aware there are many other similar questions but the solutions from those questions I feel I've already got in place.
I've got 3 sites running locally on a VirtualBox Ubuntu 12.04.4 LTS Server, I'm using nginx and php-fpm.
They are configured to run on ports 9001 -> 9003:
server:/etc/php5/fpm/pool.d$ grep 900 *
my-app-deploy.conf:listen = 127.0.0.1:9002
my-app-dev.conf:listen = 127.0.0.1:9001
my-web.conf:listen = 127.0.0.1:9003

server:/etc/nginx/conf.d$ grep 900 *
my-app-deploy.conf:                fastcgi_pass   127.0.0.1:9002;
my-app-dev.conf:                fastcgi_pass   127.0.0.1:9001;
my-app-web.conf:                fastcgi_pass   127.0.0.1:9003;

I've restarted both php-fpm and nginx successfully:
server:$ sudo service nginx restart
 * Restarting nginx nginx
   ...done.
server:$ sudo service php5-fpm restart
 * Restarting PHP5 FastCGI Process Manager php5-fpm
   ...done.

But if I look at what ports are being listened to, I only see 9002 and 9003:
server:$ sudo lsof -i | grep 900
php5-fpm  1020     root    7u  IPv4   8557      0t0  TCP localhost:9002 (LISTEN)
php5-fpm  1020     root    8u  IPv4   8558      0t0  TCP localhost:9003 (LISTEN)
php5-fpm  1021 www-data    0u  IPv4   8557      0t0  TCP localhost:9002 (LISTEN)
php5-fpm  1022 www-data    0u  IPv4   8557      0t0  TCP localhost:9002 (LISTEN)
php5-fpm  1023 www-data    0u  IPv4   8557      0t0  TCP localhost:9002 (LISTEN)
php5-fpm  1024 www-data    0u  IPv4   8557      0t0  TCP localhost:9002 (LISTEN)
php5-fpm  1025 www-data    0u  IPv4   8558      0t0  TCP localhost:9003 (LISTEN)
php5-fpm  1026 www-data    0u  IPv4   8558      0t0  TCP localhost:9003 (LISTEN)
php5-fpm  1027 www-data    0u  IPv4   8558      0t0  TCP localhost:9003 (LISTEN)
php5-fpm  1028 www-data    0u  IPv4   8558      0t0  TCP localhost:9003 (LISTEN)

And I get the following error from nginx:
server:~/vhosts/my-app/logs$ tail -n 1 nginx/error.log
2014/06/20 11:07:36 [error] 2434#0: *4 connect() failed
    (111: Connection refused) while connecting to upstream, client: 192.168.0.10,
    server: my.app.dev, request: "GET /api/test.php HTTP/1.1", upstream:
    "fastcgi://127.0.0.1:9001", host: "my.app.dev"

I'm hoping I've just missed something really basic, but when I added the site on 9002 I don't remember having to do anything else apart from add the new port number to both the conf files
UPDATE The site root is actually serving, it's only the api/test.php page that is returning 502
UPDATE I moved the ports around, I swapped web and dev around so dev is now on the 9001 port, but that's made no difference. I've updated the question to  reflect this.
All 3 ports are serving content - I think it's something to do with redirects I've got setup for the API section.
Here is a diff between the dev and deploy PHP and nginx configs:
server:/etc/nginx/conf.d$ diff my-app-dev.conf my-app-deploy.conf
3c3
<         server_name my.app.dev;
---
>         server_name my.app.deploy;
10c10
<         root /var/www/vhosts/my-app/public_html/mobile;
---
>         root /var/www/vhosts/my-app/public_html/mobile_deploy;
47c47
<                 fastcgi_pass   127.0.0.1:9001;
---
>                 fastcgi_pass   127.0.0.1:9002;

server:/etc/php5/fpm/pool.d$ diff my-app-dev.conf my-app-deploy.conf
33c33
< listen = 127.0.0.1:9001
---
> listen = 127.0.0.1:9002
384c384
< php_admin_value[doc_root] = /var/www/vhosts/my-app/public_html/mobile
---
> php_admin_value[doc_root] = /var/www/vhosts/my-app/public_html/mobile_deploy

And here is the complete conf file for the dev site, on port 9001, that is giving me the 502
server {
        listen 80;
        server_name my.app.dev;

        error_log  /var/www/vhosts/logs/my-app/nginx/error.log;
        access_log /var/www/vhosts/logs/my-app/nginx/access.log  main;

        error_page 404 /404;

        root /var/www/vhosts/my-app/public_html/mobile;
        index index.html index.php;

        client_max_body_size 10M;

        proxy_read_timeout 180s;

        # deny any attempt to access hidden files
        location ~ /\. { deny all; }

        # disable logging for favicon
        location = /favicon.ico {
                log_not_found off;
        }

        location ~* \/api\/[0-9]\/.*\.zip {
                try_files $uri /api/3/nomarket.data.zip;
        }

        location ~* \/api\/picture\/[a-z]+\/? {
                if (!-e $request_filename) {
                        rewrite ^/api/picture/([a-z]+)/? /api/picture.php?type=$1 last; break;
                }
        }

        location /api {
                if (!-e $request_filename) {
                        rewrite ^/api/(.*)$ /api/router.php?rest_data=$1 last; break;
                }
        }

         # allow php files to be executed
        location ~ \.php$ {
                # only call php if the file exists. Very important for security!
                try_files  $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass   127.0.0.1:9001;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_index  index.php;
        }

        # just serve static files, please.
        location / { }
}

Comment: 502 means there's a problem 'upstream'.  Can you access the site on 127.0.0.1:9001 (or whichever port it's on now)?
Comment: What do you mean by access it? Ping it from the Virtual Box server? I can access the site from Chrome on the host system
Comment: Your pool on port 9003 isn't running. Post its configuration.
Comment: Do you mean the full php-fpm conf from /etc/php5/fpm/pool.d?
Answer: Your lsof output looks fairly conclusive that php-fpm is not listening on port 9001 (though you might like to use sudo netstat -plnt for a more concise listing that's faster to generate).
Presumably then, the issue is with php-fpm.  I'd suggest you forget about nginx for the moment, and use telnet localhost 9001 for debugging.  I expect you'll see a failure to connect.  Go back to using nginx once you can get a connection.
I'm guessing that either you have a configuration issue with the site that's supposed to be on port 9001, or php-fpm was for some reason unable to bind to that port.
Either way, the first thing I'd look for is log entries from php-fpm at startup time.  You might need to enable those logs.  See this question for that:  How to configure php-fpm to log logs to log files configured in nginx virtualhosts
Those config file diffs look straight-forward enough.  Maybe check for control characters on those lines (eg Windows style line ends can creep in with some work practices).  Also, remember to check for differences in file permissions as well as file content.
If the problem relates to binding to the port, then using a different port is likely to change the behaviour.  Worth a shot, even if just to rule that out.  You could also look through strace output to see what happens there if/when fpm attempts to bind port 9001.  Eg strace -p [pid] | grep -n 10 9001 .
Comment: So what actually did it was I'd left the name of the server in both php-fpm conf files as `my.app.dev` - changing the *deploy* conf server name to `my.app.deploy` got them both working. If you look in the diffs I posted, nginx shows different server names but nothing comes up in the diff for php-fpm about the server name. So thanks @mc0e for narrowing it down to a problem with php, and I moved it to port 9004 which didn't help, confirming it wasn't that port in particular - I just went through the php configs line by line to spot it
Answer: PHP FPM Pool Names
From your diff it appears you have duplicated PHP pool names in /etc/php-fpm.d.  I am pretty certain only the configuration file that loads last will be in effect.
As a result, with duplicate pool names only the last loaded name/port pair will spin up.
Looking at your data, perhaps my-app-dev.conf and my-app-deploy.conf share the same pool name since it is not shown in the diff.  As a result, only one of these pools is in effect.
I recommend double checking your php pool names.
Comment: there will be an error like :ERROR: An another FPM instance seems to already listen on
ERROR: FPM initialization failed
Comment: Sorry I thought I'd commented on this, it was just an error typing up my question, that wasn't the problem.
Comment: @ADM I think that error only happens if you try to spin up another pool on the same port. This would need to be verified but I don't think that error occurs if you have two pools with the same name but different ports.
Comment: for anyone who had my problem i'll write it here: I had the bad gateway problem, and it ended up being because I had changed `pm = static` to `pm = ondemand` and the `ondemand` setting didn't even exist yet in my installed version of nginx.


Heteroskedasticity in a regression model

Question: $\newcommand{\var}{\mathrm{Var}}$In my textbook I am studying about heteroskedasticity in a linear regression model, and for doing the hypothesis test, it says our hypothesis is: $H_0: \var(u|x_1,x_2,...,x_k)=\sigma ^2$, however than it says:

Because we are assuming that $u$ has a zero conditional expectation, $\var(u|\mathbf{x})=E(u^2|\mathbf{x})$ (where $\mathbf{x}$ is all the regressors $x_1,x_2,x_3,...,x_n$), and so the null hypothessis of homoskedasticity is equivalent to: $$H_0: E(u^2|x_1,x_2,...,x_k)=E(u^2)=\sigma^2$$

Why is this true? I dont understand why we use $u^2$ and then regress the independent variables on it.
Comment: Recall that $Var(u|x)=E(u^2|x)-E(u|x)^2$. If the second term is zero, as is assumed here, then we must have $Var(u|x)=E(u^2|x)$, for any $x$. Under $H_0$ we assume that $Var(u|x)=\sigma^2$. Putting these together, under $H_0$ we must have that $E(u^2|x)=\sigma^2$, for any $x$.
Answer: Becasue $Var(u|x)=E(u^2|x)-E^2(u|x)=E(u^2|x)-0^2=E(u^2|x)=E(u^2)=\sigma^2$, since $u$ has a zero conditional expectation. Here I used the fact that $u$ is independent of $x$. Therefore, (roughly speaking) each function of $u$ is independent of $x$ as well. So in particular $u^2$ is independent of $x$. This means that $E(u^2|x)=E(u^2)$.


Form fields cannot be found until the PDF file is saved again in Acrobat

Question: I am using iText 7 (version 8.0.2) to fill in form fields in an existing original PDF (from a third party). Now I have encountered a strange problem. The form fields cannot be found. However, if I only save the PDF file in Adobe Acrobat (without making any changes), all the fields are found. I can see that the file size increases from 74KB to 145KB.
Is there any tool I can use to analyze the structure of the PDF file in a way that allows me to identify what differs between the files?
Can iText 7 be used to trigger a similar automatic extra save of the file? I have tried to do a "normal" dummy open/save to a new file with iText 7. The file can be opened in Acrobat, but the problem persists in that form fields cannot be found with iText 7.
Unfortunately, I cannot share the specific file, which I would have liked to do.
public void Test() {
  using var pdf = new PdfDocument(new PdfReader("in.pdf"), new PdfWriter("out.pdf"));
  var form = PdfAcroForm.GetAcroForm(pdf, false); // form.GetField("FIELD_NAME") does not work
  var forms = form.GetAllFormFields(); //Empty collection
}

Thanks for helping me out here!
Edit:
Using pdftk to dump the fields the result of the initial file (not re-saved in Acrobat), the result are empty. But with the re-saved file all form-data are there.
pdftk.exe input.pdf dump_data_fields
Edit:
I have examined the files with iText RUP, this is what I found. First original file, second saved in Adobe Acrobat. NB: I do have some PDF knowledge, but I'm not a professional PDF developer. Maybe I'm looking in wrong direction.
Fields are empty, but the form-field name are found under Pages.

Fields array now have data (re-saved file).
Comment: Indeed, there is iText RUPS. There also are a  number of similar tools, e.g. PDFBox PDFDebugger or the "Browse Internal PDF Structure" option of Adobe Acrobat Preflight. But most of all you need to _understand_ what those tools show. Thus, you need to have a fundamental knowledge of the internal PDF structure.
Comment: Ok. It's clearly an error in the original PDF that the fields are not in the **AcroForm** entry **Fields**. You should tell the source of the PDF that their form structure is broken and ask them to provide a complete form definition. In particular the file does not require an "extra safe": it is broken and needs a _repair_. You can implement such a repair based on iText: simply visit all document pages, collect the widget annotations from their **Annots** arrays, determine the root fields of those annotations by following the **Parent** entries, dropping duplicates, and setting the **Fields**.
Comment: Well, without inspecting the file in question I could only guess what causes the prompt to save the changes. But if it is broken in one way, it may also be broken in other ways. Concerning the producer metadata - I doubt that Acrobat Distiller or iText 5.5.3 created the broken form structure. Most likely there were also other PDF processors manipulating the file but not adding to the producer line.
Comment: Can you advice on any "simple GUI editor" to examine the file?
Comment: Thanks, I edited with some iText RUP founding.
Comment: Thanks for the input and sorting this out. I have been struggling with this in my mind for a while. The Producer metadata reads:
`Acrobat Distiller 15.0 (Windows); modified using iTextSharp™ 5.5.3 ©2000-2014 iText Group NV (AGPL-version)`
Can it be an old way of producing the PDF or is it just faulty?
Comment: I did a workaround shown in my answer below (https://stackoverflow.com/a/77528161/2383045).
But when I tested this, I noticed that when I open the original file (or even the one that is fixed) in Adobe Acrobat, the file is flagged as modified in the program. This causes the application to prompt to save the changes even if no adjustments were made in Acrobat. Perhaps the most pragmatic solution is to open the original file in Acrobat and save it (repair it). However, I would have preferred to handle this automatically with iText.
Comment: Perhaps it's not worthwhile to invest effort in resolving the underlying issue if it's inherently broken.
Answer: Thanks to to mkl's comment, I did a method to "repair" the broken PDF based on the KB from iText (https://kb.itextsupport.com/home/it7kb/faq/why-are-the-acrofields-in-my-document-empty):
private static void FixMissingAcroFields(PdfDocument pdf) {
    var root = pdf.GetCatalog();
    var form = root.GetPdfObject().GetAsDictionary(PdfName.AcroForm);
    var fields = form.GetAsArray(PdfName.Fields);

    for (var i = 1; i <= pdf.GetNumberOfPages(); i++) {
        var page = pdf.GetPage(i);
        var annotations = page.GetAnnotations();
        foreach (var annotation in annotations) {
            fields.Add(annotation.GetPdfObject());
        }
    }
}

Then I call it when FormFilds is empty.
var pdf = new PdfDocument(new PdfReader(sourceFile), new PdfWriter(targetFile));
var form = PdfAcroForm.GetAcroForm(pdf, false);

if (!form.GetAllFormFields().Any()) {
    FixMissingAcroFields(pdf);
    form = PdfAcroForm.GetAcroForm(pdf, false);
}
...

I'll also try to report the broken PDF to the source/creator.


google charts addcolumn not working

Question: see code below, i was using inline table and converted to add column and add rows so i could specify the column type - this code will not display any error or render chart...what's wrong - thanks in advance

pH Logger

Comment: Could you make a jsFiddle?
Answer: You are missing the new keyword before the google.visualization.DataTable() constructor call:
var data = new google.visualization.DataTable();

google charts addcolumn not working


ERROR: Could not find a version that satisfies the requirement time (from versions: none)

Question: I'm getting this type of error when installing the library.
Not for all packages, but only for some. Is it because pip version? or Because of python interpreter?
Plz guide me what should I do.
Answer: You don't need to install this package because it's already in the standard library.
Just import time in any Python file.
Comment: Unfortunately that conclusion can't be made; that pip error means that the package isn't available at all. But in this case, since it is `time`, it's common knowledge for Python programmers that this is a standard library which is built-in.
Comment: Look for a tutorial that offers a quick tour through the Python standard library, such as https://docs.python.org/3/tutorial/stdlib.html . Some acquaintance with the standard library is indispensable, as you have discovered.
Comment: So whenever I get this type of error, it means I already have that package?
Comment: then what should I do when this type of error occurs again?
Comment: Type in the package name in Google with the word python, and see what comes up. Maybe you'll find a github, or something in the Python docs :)


align text to the center of icons

Question: i want to align the text under the icons to the icons image
here is the fiddle link:
http://jsfiddle.net/J2N2P/

Smart TV

Tablet

Iphone

Android

Pc

Mac

Comment: Please elaborate on what you have tried to make it work and why it did not work. Dont expect people on SO to just write the code for you.
Comment: Maybe update your question with a more relevant jsfiddle? Without icons nor a description this question is not really good
Answer: change this to your CSS, You'll get align imgs and text in the center:
CSS
.icon_middle span {
   display:block;
   margin: 0 auto;
   text-align:center;
}

.icon_middle img {
    padding: 0 10px;
    display: block;
    margin: auto;
}

Answer: You'll have to place pairs img/span within some container (span or div) and then align them relative to that container. Or, if layout is thought to be more like table, just use table/tr/td and align pairs of img/span within td.

align text to the center of icons


Pandas and matplotlib: Different fonts between showfig and savefig (mac os x backend)

Question: I'm plotting data stored in pandas dataframes through matplotlib, with pd.options.display.mpl_style = 'default'
The plot font is different between the figure that is shown, and the figure that is saved:
Shown figure:

Saved figure:

I realize there are different settings one can apply that will change the look and feel of either individually (matplotlib savefig() plots different from show()), however I haven't been able to find any easy to follow documentation that shows how to set the default fonts while using matplotlib backend: MacOSX. Can someone show how to make the font that appears in the shown figure also appear in the saved figure?
Answer: I found what solves the problem incidentally through another script I have. I have no idea why or how this solves the problem... Entering the code below before the plot is called makes it so the font appears the same as in the figure and the saved pdf:
font = {'family' : 'normal'}
matplotlib.rc('font', **font)


make a proxy with two servers

Question: I want to implement a proxy which has two (A and B) servers in the middle. traffic goes from my computer to server B and then to server A and then gets the data.
I found that with this configuration in ~/.ssh/config:
HOST B
    HostName B
    user debian
    DynamicForward 0.0.0.0:1081

I can use my 1081 port as a proxy. But now I don't know how to proxy all B's traffic through A.
Comment: create a vpn its easier
Comment: @djdomi What do you mean by creating vpn? because of some controlling policies which my ISP has I can't use tools like shadowsocks
Comment: openvpn i. e. if you need to do like
Answer: You want a port on your client to be forwarded to a fixed port on server A:
ssh -L 1080:localhost:1081 A

Here localhost is server A. On port 1081 on server A you must have a dynamic (SOCKS5) proxy:
ssh -D 1081 B

Putting it all together:
ssh -t -L 1080:localhost:1081 A -- ssh -D 1081 B

if you use password based authentication between host A and B, or
ssh -f -L 1080:localhost:1081 A -- ssh -D 1081 B

if you use public key authentication and want your ssh to go work in the background.
Comment: I get this error: Pseudo-terminal will not be allocated because stdin is not a terminal.
Host key verification failed.
Comment: If you use password based authentication between host A and B, you need to force the allocation of a (pseudo-)terminal on server A, so you can enter your password. I edited the answer accordingly.

make a proxy with two servers