mux unknown revision error while pushing application to cloud foundry

Question: I'm trying to deploy a Go Web application using mux for routing, onto Cloud Foundry. My application contains a couple of other dependencies as well, mentioned below. However, there is a problem with either the go.mod file, the manifest file, or the gorilla/mux repository's go.mod file (which is highly unlikely).
This is the go.mod file that's created on entering go mod init and then go build .
<code>module deployment_automation_tool

go 1.15

require (
    github.com/gorilla/mux v1.8.0
    github.com/jinzhu/gorm v1.9.16
    github.com/mattn/go-sqlite3 v1.14.6
)
</code>
This is the manifest:
<code>---
applications:
  - name: deployment_automation_tool
    buildpacks:
      - go_buildpack
    env:
      GOPACKAGENAME : deployment_automation_tool
</code>
However, I keep getting this error:
<code> **ERROR** problem retrieving main package name: go: email@example.com: reading github.com/gorilla/mux/go.mod at revision v1.8.0: unknown revision v1.8.0

 **ERROR** Unable to determine import path: exit status 1
   Failed to compile droplet: Failed to run finalize script: exit status 12
   Exit status 223
</code>
Comment: Just a quick question. Does your foundation have Internet access? Go seems to be having issues fetching a dependency, it would get that from the Internet. Many CF foundations have restricted Internet access, so verifying you can connect to Github from inside a container would be a good first step. You may need to enable a proxy to access the Internet, if access is restricted by your platform operations team.
Comment: Although it exists within a firewall, It does have internet access. I initially had that concern as well, but it seems to be an issue with Go modules rather than the internet connectivity
Answer: I solved this issue, by using dep, instead of Go modules. It's mentioned in its official docs that it is deprecated, but I found that to work with the go_buildpack perfectly.
I'll update the answer if I find a way to push this to CF with go modules.


Finding approximation to eigenvalues from minizing Rayleigh quotient and from diagonalization

Question: Suppose I want to find an approximation to the smallest eigenvalue of $y''=\lambda y$, with $y(0)=y(1)=0$.
One way to do it is to write the ansatz $y=x(1-x)+ax^2(1-x)^2$, compute the Rayleigh quotient,
$$R[y]=\frac{\int_0^1 yy''dx}{\int_0^1 y^2dx}\propto\frac {2\,{a}^{2}+14\,a+35}{{a}^{2}+9\,a+21},$$
and compute its critical point to get the value $\lambda\approx -9.8697$, pretty close to the exact value. Fine.
I thought another way would be to represent the second derivative as a matrix acting on the space spanned by the normalized functions $f_1=\sqrt{30}x(1-x)$ and $f_2=\sqrt{630}x^2(1-x)^2$, namely
$$M_{ij}=\int_0^1 f_i f_j'' dx.$$
This gives
$$M=\left( \begin {array}{cc} -10&-2\,\sqrt {21}
\\ -2\sqrt{21}&-12\end {array} \right),$$
whose eigenvalues are $-1.78$ and $-20.22$, completely off.
I expected the diagonalization would be equivalent to minimizing the Rayleigh quotient. Is that not the case?
Answer: You want to extremize $G(y):=\langle y,y''\rangle$ subject to the condition $\langle y,y\rangle = 1$, where $\langle u,v\rangle:=\int_0^1u(x)v(x)\,dx$ and $y(x)=a_1f_1(x)+a_2f_2(x)$. Using the method of Lagrange multipliers, we can recast this problem as the unconstrained extremization of
\begin{align}
\tilde{G}(y)&=G(y)-\lambda(\langle y,y\rangle - 1)
=\sum_{i,j=1}^2(M_{ij}-\lambda\langle f_i,f_j\rangle)\, a_ia_j+\lambda. \tag{1}
\end{align}
To find the critical points of $\tilde{G}$, we have to solve the equations
\begin{align}
\frac{\partial\tilde{G}}{\partial a_1}&=0
\implies (M_{11}-\lambda\langle f_1,f_1\rangle)\, a_1 +
(M_{12}-\lambda\langle f_1,f_2\rangle)\, a_2 = 0, \tag{2a} \\
\frac{\partial\tilde{G}}{\partial a_2}&=0
\implies (M_{21}-\lambda\langle f_2,f_1\rangle)\, a_1 +
(M_{22}-\lambda\langle f_2,f_2\rangle)\, a_2 = 0. \tag{2b}
\end{align}
The system of equations $(2)$ has nontrivial solutions if $\lambda$ is a solution to the equation
$$
\det(M-\lambda F)=0, \tag{3}
$$
where $F$ is the matrix with elements $F_{ij}=\langle f_i,f_j\rangle$. If the functions $f_1, f_2$ are orthonormal, then $F$ is equal to the identity matrix, in which case the solutions to $(3)$ are the eigenvalues of $M$. In your problem, however, the functions $f_1, f_2$, although normalized to $1$, are not orthogonal; indeed, $\langle f_1,f_2\rangle=\sqrt{\frac{27}{28}}.$
You can verify that one of the solutions to $(3)$ coincides with the value that you found minimizing the Rayleigh quotient.
Comment: Ah, the orthogonality is missing! Thanks.


Locking fields on a content type

Question: Using Drupal 7:
I have several content types with their own sets of fields, but I also have a set of fields that they must all share in common. That is easy enough through the administrative UI, but I'm writing a module that programmatically will add the fields to all node content types that I specify. Additionally, I do not want the administrator to be able to remove or edit those fields through the administrative UI.
How can I make it so that as an administrator is managing content types that the admin cannot modify or remove these fields that I have specified?
Alternatively, I know that I can create a separate entity and force field existence that way, but then I loose access to a lot of the functionality already built into the node entity, especially the function hook_node_access which is also a requirement for this module.
Anyone have any suggestions or know how to solve this?
Answer: Refer to the field api documentation here. You do not have to add permissions to block the delete. All you need to do is add the "locked" attribute to the field definition.

locked (integer): Whether or not the field is available for editing.
  If TRUE, users can't change field settings or create new instances of
  the field in the UI. Defaults to FALSE.
Comment: Awesome. That is way easier than I thought it would be. Thanks for the help.
Answer: There is a module for that names "Field Lock".
Of course it uses the API field definition "locked" as mentioned before.
Here is a short description from the module page:

Field lock adds additional level of permissions so certain users can
  lock a field, enter code herepreventing others from editing or
  deleting it.
Answer: For existing fields that are provided by (eg, media_gallery or commerce)
You can run-once the snippet from http://atlantic-canary.net/es/how-to-lockunlock-a-field-in-drupal
<code><?php
$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);
?>
</code>
I did it for myself in an update hook, to ensure that my extension to media_gallery could expose some settings.
<code>/**
 * UNLOCK the description field provided by media_gallery so we can tweak settings.
 */
function niwa_media_update_7002() {
  $field = field_read_field('media_description');
  $field['locked'] = FALSE;
  field_update_field($field);
}
</code>
In my case I just wanted to limit the text formats that were available as an image caption, as full_HTML was causing problems. better_formats.module could not help me until I'd unlocked the field.

Locking fields on a content type


Como enviar Imagens via AJAX para o php

Question: Boa tarde, gostaria de pedir a ajuda de vocês.
Eu estou com um sistema onde eu preciso enviar uma Imagem de um <input type="file>" para uma pagina PHP via $.ajax() para nela, eu poder fazer upload desta imagem para uma basta, enquanto pego o caminho e armazeno ela no banco via $_pdo.
Eu fiz uma extensa pesquisa na internet e achei vários sites ensinando a fazer, porem eu não entendi, as únicas coisas que eu entendi era que eu devia usar um comando chamado formData() e passar alguns parâmetros no $.ajax().
Porem eu não entedi:

como usar o formData()
quais parâmetros devo passar no $.ajax()
se eu posso passar outros tipos de informações junto com a imagem
Como eu consigo armazenar o valor de uma imagem em um <elemento hidden> e trazer esta informação para o $.ajax()

Alguém ae poderia me ajudar?
Comment: Possível duplicata de [upload sem refresh com FormData, jquery](http://pt.stackoverflow.com/questions/43405/upload-sem-refresh-com-formdata-jquery)
Answer: Você precisa criar um objeto FormData com input da imagem que você quer fazer upload:
var fd = new FormData();
fd.append('file', $('#inputFile"));

Depois, fazer a chamada ajax "POST" passando o FormData como parametro "data".
$.ajax({
    url: 'http://dominio/pagina.php',
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
        alert(data);
    }
});

Na sua página php, você pode usar o $_FILES para receber o arquivo.
Sim, você pode passar outros dados. o FormData é dicionário do tipo chave/valor, só adicionar outros elementos e valores fazendo append.
Tem um exemplo legal pra se você se basear aqui: https://www.formget.com/ajax-image-upload-php/
Comment: Antes de responder use a busca http://pt.stackoverflow.com/search?q=%5Bajax%5D+upload
Comment: Verdade, já tinha a resposta, obrigado @GuilhermeNascimento

Como enviar Imagens via AJAX para o php


Method to find the set S of reals $λ$ such as $rg($M-I3)<3 given a matrix

Question: Considering the endomorphism $f$ of $R^3$ of
\begin{bmatrix}
-3 & 5 & -5\\
-4 & 6 & -5\\
 -4& 4 &-3
\end{bmatrix}
relatively of the canonical base bc of $R^3$
find  the set S of reals $λ$ such as $rg($M-$λ$I3)<3
What method should I use? I tried the Gaussian elimination but it becomes awkward and difficult at some point. Can you give some details?
Comment: Where does λ play  a role?
Comment: Does rg denote the rank?
Comment: Sorry, a typo! In rg(M-λI)
Comment: Use Sarrus's rule to compute the characteristic polynomial.
Comment: Per Bernard's suggestion, the usual approach is to calculate $\det(M - \lambda I_3)$ as a function of $\lambda$.
Answer: Assuming rg means rank, you know that $rg(M-\lambda I_3)\leq 3$. Find the set A of $\lambda$'s for which the rank is 3 (think about when is the rank of a matrix equal to its dimension) and the answer will be $S=\mathbb{R}-A$.


How can I make the animation of a circle continous with hovering like this gif in d3.js?

Question: I'm new to d3.js. this is the animation of a circle that I like a lot. It is something like an infinite animation.

I would like to copy this animation to generate it in d3.js, but I think my knowledge is insufficient, this code is the closest I have been able to copy the animation.
Then my idea is that I can have a mouse hover effect as you can see in the image. How can I do it? thank you very much.
this is my code and this is my current result:

<code>var width = document.getElementById('circles').offsetWidth-70;
  var height =(width/2)+100;
  var scale = d3.scale.linear()
    .range(["yellow","orange","red"])
    .domain([0,60]);

  var data = [0,10,20,30,40,50,60];

  var svg = d3.select("#circles").append("svg")
      .attr("width", width+"px")
      .attr("height", height+"px");

  //circle orange
  svg.append("circle")
  .attr("cx",80)
  .attr("cy",80)
  .attr("r",30)
   .attr("fill","orange")
  .style("stroke-width","1")
  .style("stroke","orange")
  .on('mouseover', function(){
    d3.select(this).transition().ease("bounce").duration(500).attr("r",32)
  })
  .on('mouseout', function(){
    d3.select(this).transition().ease("bounce").duration(500).attr("r",30)
  })

  //circle yellow
   svg.append("circle")
  .attr("cx",80)
  .attr("cy",80)
  .attr("r",22)
  .attr("fill","yellow")
  .style("stroke-width","1")
  .style("stroke","yellow")
  .style("opacity","0.9")

  .on('mouseover', function(){
    d3.select(this).transition().ease("bounce").duration(500).attr("r",24).style("opacity","1")
  })
  .on('mouseout', function(){
    d3.select(this).transition().ease("bounce").duration(500).attr("r",22).style("opacity","0.9")
  })

     var circles = svg.selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("r",function(d) { return d; })
    .attr("transform","translate(80,80)")
    .attr("fill","none")
    .style("stroke-width","1")
    .style("stroke",function(d) { return scale(d) });

  function transition() {
    // Update data, max d is 60:
    data = data.map(function(d) { return d == 60 ? 0 : d + 10});

    var i = 0;
    // Grow circles
    circles
       .data(data)
       .filter(function(d) { return d > 0 })
       .transition()
       //.ease(d3.easeLinear)
       .ease("linear")//set the ease here
       .attr("r", function(d) { return d; })
       .style("stroke", function(d) { return scale(d) })
       .style("opacity",function(d) { return d == 60 ? 0 : 1 })
       .duration(1000)
       //.on("end",function(){if(++i==circles.size()-1) { transition(); } });
        .each("end", function (d,i) {
          //.on("end", function (d,i) {
           if(++i==circles.size()-1) { transition(); }
        });

    // Reset circles where r == 0
    circles
      .filter(function(d) { return d == 0 })
      .attr("r", 0)
      .style("opacity",1)
      .style("stroke",function(d) { return scale(d); });

  }
  transition();
</code>
http://plnkr.co/edit/kz2tbxoS9lsfy2oMDzhY?p=preview
Comment: Something like [this](https://stackoverflow.com/a/45354816/7106086)?
Comment: @AndrewReid thanks to you I was able to improve my code, I am getting closer to what I want.
Answer: This is a good case to learn d3.transition functionality.
Like @AndrewReid's reference and your code already there for your expected effect.
In your code(if I understand correctly), you directly produce the emanating effect with data updating the circle radius and control each circle's life cycle directly with selection group number.
Indeed, you can directly use d3.transition property to control the circle transition life cycle to produce emananting effect.
Here some reading material for d3.transition life cycle:

A Life of a transition
Working with Transition

Here's my code:
In my implementation, I use data to decide the emananting circle number and
use transition.on to listen each transition cycle done and reset the property.
<code>//DOM.svg is the syntax in observablhq, in browser, replace with your way
const svg = d3.select(DOM.svg(250,250));

const data = Array.from(Array(CircleNumber).keys());

// use this emanating function to control the execution cycles
function emananting(num){

        svg.selectAll('circle.emanting')
         .transition()
         .duration((d,i)=>{
          return 2500;
        })  // duration to control each circle emananting duration
         .delay((d,i)=>{
          return i*500;
          }) // delay to control between each circle's space
         .attr('opacity',0)
         .attr('r',50)
         .on('end',(d,i,g)=>{
            // after each transition end, trigger these codes
            d3.select(g[i])
              .attr('r', 10)
              .attr('opacity',1);
               // control flow from listening to the last transition    done!
               // remove the num < 10 condition , it will be infinite
               if (i===5 && num < 2){
                    console.log(num);
                    emananting(num+1);

                }
            });
 }
 // Here create the center circle body
 svg.append('circle')
 .classed('CircleBody',true)
 .attr('r',10)
 .attr('stroke','yellow')
 .attr('fill','orange')
 .attr('opacity',1)
 .attr('cx',125)
 .attr('cy',125);

// Here create the emanting circle
svg.selectAll('circle.emanting')
            .data(data)
            .enter()
            .append('circle')
            .attr('class','emanting')
            .attr('id', (d,i)=>{
                return 'number' + i;
                            })
            .attr('r',10)
            .attr('stroke','orange')
            .attr('fill','none')
            .attr('opacity',1)
            .attr('cx',125)
            .attr('cy',125);
 // control flow
 emananting(0);
</code>
Here some demo on @observablehq
https://beta.observablehq.com/@weitinglin/demo-how-can-i-make-the-animation-of-a-circle-continous-with-h
Comment: thanks for your time. but, something happens with your example or with the page. the consumption of RAM is very high, it blocks my browser.
Comment: sorry, now I'm fixing the problems
Comment: it fixed now, but I think these also arouse another issue when implementation of infinite animation, one should consider the RAM or other performance issue ><
Comment: https://beta.observablehq.com/@weitinglin/demo-how-can-i-make-the-animation-of-a-circle-continous-with-h
Comment: thank you very much, I wanted to do it just like the gif, I have updated my question now, you can see the current result and I think with your help I am almost at the same point. animated circles from the beginning are active.
Comment: can you help me please to have the gif like the first image?
Comment: @yavg I update the demo https://beta.observablehq.com/@weitinglin/demo-how-can-i-make-the-animation-of-a-circle-continous-with-h, does it near what you expected? I think I just add a radial gradient effect on the outer  circle. (I use the d3.js v5 version, so some syntax is changed now, ex d3.ease )
Comment: wow! It's just what I want. I'm not very good at d3.js and I only drive v3. I will try to convert it to the v3 version. Is it possible to have the animation of infinite continuous circles? thank you very much friend!
Comment: great man, can you help me please with a similar question please? https://stackoverflow.com/questions/49261253/how-can-i-convert-this-code-that-is-in-d3-v5-to-d3-v3-it-is-an-animation-of-a-c
Comment: Can you convert your code to my pnlkr please? I am not able to adapt it
 :(
Comment: @yavg Here is the conversion to v3 https://beta.observablehq.com/@weitinglin/v3-version-demo-how-can-i-make-the-animation-of-a-circle-conti I'm not familiar with d3.v3, because I was learning it from v4.
Comment: @yavg I also use generator to let it be infinite without overloading!
Comment: I want to use your code, but I am unable to replicate your code in a plnkr, I get some errors. Can you please update my plnkr with your code? I would greatly appreciate it


Kohana validation: correct syntax for range rule

Question: In setting up validation for one of my models, I'm having trouble getting the correct syntax for the 'range' rule.  Every variation seems to pass only the (first) min parameter and not the (second) max.
/**
 * @var   array  Validation rules
 */
public function rules()
{
    return array(
        'title' => array(
            array('not_empty'),
            array('max_length', array(':value', 50)),
        ),
        'time' => array(
            array('not_empty'),
            array('date'),
        ),
        'date' => array(
            array('not_empty'),
            array('date'),
        ),
        'limit' => array(
            array('digit'),
            array('range', array(':value', 1), array(':value', 255)),
        ),
    );
}

I also tried array('range', array(':value', array(1, 255))) to no avail.
Any suggestions?
Answer: The correct syntax for Range Rule need 3 param and not 2.
As you can see in the documentation: http://kohanaframework.org/3.2/guide/api/Valid#range
So the code must be like this:
array('range', array(':value', 1, 255)),

Answer: And be carefull, the range is ]min;max[ not [min;max], so the limits are excluded.
array('range', array(':value', 1, 255)) => [2;254]


Can I get a sense of how good Logic Pro is at MIDI -> MP3 conversion without installing MacOS?

Question: I'm interested in converting MIDIs to MP3s.
I've heard that Logic Pro is pretty good at this, but installing Logic Pro and MacOS is quite a hassle for me (I use Linux)
Are there web sites that let you download both the original MIDI and the MP3 produced by Logic Pro to get a sense of how good it is?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/133088/discussion-on-question-by-mwb-can-i-get-a-sense-of-how-good-logic-pro-is-at-midi).
Answer: Judging by your other questions it seems you don't quite understand how far midi is from real music. It's like expecting an highly evocative and emotionally acted stage performance generated from morse code.
But it all depends on how far off from the real thing you're willing to go. If you simply want to hear what a specific midi file sounds like there's plenty of options, like musescore (https://musescore.org/en) If in the midi file the channels are mapped to generic midi instruments it will use a very simple sound library to translate the midi signals to audio.
The closer you want to get to a real sounding human performance the more manual effort you'll need to put into it. Midi is like paint-by-numbers; it simply tells you what note to play when, with which velocity and how long. It doesn't tell you what the attack, decay, sustain or release of each individual note needs to be. What instrument specific technique should be used, e.g. a staccato can be played a dozen different ways on a violin. etc. etc.
This is all information that will need to be added on top of the midi data.
And yes, this is something you can do in Logic. Or any other DAW. But make no mistake, it will be a looooong journey and you'll need to invest a lot of time, energy (and probably money too) into it.
There's one more option if you're interested in turning midi into music using orchestral instruments exclusively: you could use Noteperformer. https://www.noteperformer.com
It's a plugin however so you'll need to buy/rent one of the host programs it's supported by. It uses A.I. which tries to provide all of that extra information that's necessary to come closer to a real performance. It's still way off, and in my experience, you'll still be massaging the midi to get it better, but still ... it's way less effort than doing it yourself with a DAW and VST's.
Comment: " It's like expecting an highly evocative and emotionally acted performance generated from morse code" - of course it would be perfectly reasonable to expect an evocative stage performance from morse code, but there are a couple of stages of interpretation that need to take place first. I assume that's your point, rather than suggesting that MIDI *can't* be involved in the production of 'real music'?
Comment: @topomorto yes exactly. Good point
Answer: My answer on your other question dove quite deep into the practicalities of making MIDI sound 'real' and why it can be tricky, especially when you just have the MIDI file and want to apply sounds to it to make the most of the midi data you have. Does converting MIDI files to MP3 files require creativity?
But I think there may be a more fundamental missunderstanding of what Logic is and what it is not.
If you sent me a MIDI file to run through Logic to check out what happens by default I would happily import it, set my export locators and export it. Posting here you would receive, not garbage, but silence. I would see the MIDI in logic as either one track or a number of tracks (depending on the MIDI file type) and when I pressed play in Logic it would also reproduce silence.
You see the soundsets like general MIDI, TiMidity, various soundfonts etc are a totally different thing. They are preset collections of sounds small enough (in the case of the older ones) to be stored somewhere on a 90's computer or on an electronics device of yore so it could reproduce music from a MIDI file in the way of an old fashioned piano roll or similar. The snare sound for a given version of general MIDI, or any other MIDI sound collection that followed is just that, THE snare sound, the one sample that knows to play back the info contained in MIDI channel x on note y. There may be a couple of alternate snare sounds in the soundset but thats it.
Logic, on the other hand is silent with the same MIDI snare info. Once I have the MIDI imported then the left of the screen is where I can load what I would like to be played back by that snare information, choosing from 4 drum machines, a dozen synths of different types, a recorded sample playback device, or any other of the countless third party plugins I could have installed .
Once I decided on a particular drum machine to use, this may be the screen I was presented with;

All the controls in the pop up window you can see control the parameters for the snare ONLY, and in truth that's only a tiny subset of alterations you may want to make to a MUCH larger pool of available snare sounds at your disposal. The blue blocks in the background are the midi info from the file. The stuff on the left is how the audio produced (by the virtual instrument in the popup window) from the MIDI file will be processed and effected before being combined with all the other MIDI tracks into full quality audio or mp3.
You see, there is no default MIDI>mp3 process, it's all user defined. I could take a great MIDI file and make it sound HORRIBLE, or I could make it sound alright. Logic is one of the software's that current chart topping music is created on, it can output mp3's of music as professional as any artist you care to think of, it's a creative platform and just like other programs of it's type (Reaper, Cubase, ProTools etc.) it's not anything automatic.
It's also a MIDI editor (amongst other things). When I was talking on the other question about editing parameters to make the MIDI info sound more real it might look a little like this -

The list on the pop up menu are all the parameters mentioned in answers to your other question that are used to make MIDI information sound more real, but are specific, in many cases, to a particular sound-generating plugin.
So to summarise, Logic is not a MIDI>mp3 processor, well it is, but a 100% manual one, a professional tool. It comes bundled with enough audio creation and processing plug-ins to make something that sounds amazing (once you've edited the midi to something that properly resembles the original song). It's also a multi track recorder for analog audio/real instruments.
Most small scale tools designed to apply a generic soundest to a MIDI file will produce suboptimal results, I'm afraid the best you can expect is just not that great... You may not want to do any manual manipulation yourself, but I'd highly recommend getting a DAW like Reaper (which is free to try and can work on Linux), throwing in a MIDI file and seeing exactly how a DAW is setup and what it does/does not do.


Existence proof of a closest point

Question: In $(X,d) $ be a metric space. Define $d_A: X \rightarrow \mathbb{R} $ by $d_A(x)= \inf \{ d(x,a): a\in A \}$. Prove that in $\mathbb{R}^ n, A \subset X $ is closed implies that $(\forall x \in X)(\exists $ an element $a \in A)$ such that $d_A(x) = d(a,x).$
I want this proof to be rigorous. First I tried this $a$ does not exist but I could not find a contradiction because I could not comment on such thing $\inf \phi$. I do not even know if the proof is necessary or it directly follows by definition.? Can you give me a starting point and route such that I can use closedness to prove this fact.?
Comment: What metric are you using on $\mathbb{R}^n$?
Comment: Question did not specifically indicate it. So I assumed it to be usual euclidian metric
Comment: Then you can use a compactness argument.
Answer: Let $l=d_A(x)$. Then for all $n\in \mathbb{N}$, there exists a point $a_n\in A$ such that $l\le d(x,a_n)\le l+\frac{1}{n}$. Since $a_n\in B_{l+1}(x)$ for all $n\in \mathbb{N}$. Here $B_{l+1}(x)$ is the clsoed ball of radius $l+1$ centred at $x$. Then there is a convergent subsequence of $\{a_{n_k}\}$. Let $a=\lim_{k\to \infty} a_{n_k}$. Then we have $d_A(x)=d(a,x)$.
Comment: I could not spot where you used the closedness of A?
Comment: Since each $a_n\in A$, it follows that $a$ is in the closure of $A$, which is $A$ itself.
Comment: How did you conclude that there is a convergent sequence?
Comment: Bolzano–Weierstrass theorem
Comment: That depends on the metric.
Comment: Right. X has to be a complete metric space.
Comment: The space $(\mathbb{R},d)$ I described below is complete, so that is not sufficient to conclude the existence of a minimiser.
Comment: @copper.hat You are absolutely right. I need something stronger so that Bolzano–Weierstrass theorem holds.
Answer: This is not true in general.
Define the (railroad express)  metric on $\mathbb{R}$ by  $d(x,y) =\begin{cases} 0 , & x=y \\
|x|+|y|, & \text{otherwise}\end{cases}$.
The set $A=(1,\infty)$ is closed in this metric, but,
with $x=1$, we have
$d(x,a) >1$ for all $a \in A$, while $\inf_{a \in A} d(x,a) = 1$.
Comment: Isn't $ \inf _{a\in A} d(x,a) = 2$  by the definiton of metric?
Comment: You are correct, I will fix when I get to my laptop.

Existence proof of a closest point


$\frac{7}{5} \equiv 11 \pmod{12}$. Why is it $11$?

Question: I know this equation is true but I don't get the reason $\frac{7}{5}$ is congruent to $11$ here.
The quotient is supposed to be $1.4$ in non modular arithmetic and I don't get where $11$ has come from.
Comment: Modulo 12 we have that $7=-5$, so you should expect the quotient to be $-5/5=-1$. Behold! Modulo 12 we also have $11=-1$. Isn't modular arithmetic wonderful!
Comment: @JyrkiLahtonen Yes, but is division even defined for composite modulus?  It is a matter of convention, but I'm surprised that $7/5 \equiv 11 \pmod{12}$ is even defined.
Comment: You can divide by a residue class that has a multiplicative inverse (i.e. coprime to the modulus). I do agree with Morgan. Writing it $7\cdot 5^{-1}$ is better. It becomes mandatory to write it like that when you're working in a non-commutative ring.
Answer: The multiplication modulo $12$ is rather different from that in the rational numbers. But the understanding of division is the same. We want to be able to say (working modulo $12$) that if $$a\cdot b=c$$ then $$b=\frac ca$$
And that is what is happening here, because we have $5\cdot 11\equiv 7 \bmod 12$ and the fraction is just another way of expressing the same fact. You don't have $5\cdot 11=7$ in the integers or rationals.

As an aside, there is an additional issue here. We know that in the integers we can't divide by zero. Modulo $12$ we have "zero divisors" as well - for example $2\cdot 6 \equiv 3\cdot 4 \equiv 0$. We are always safe if we are dividing by numbers which are coprime to $12$, but multiples of $2$ or $3$ need special treatment - either there are no answers, or there are multiple possibilities. For example $$2\times 3\equiv 6 \times 3\equiv 10\times 3\equiv 6$$ so there is no definite value for $\frac 63$ which could be equal to $2, 6, 10$ by analogy with the usual division.
Answer: $$5 \cdot 11 = 55 \equiv 7 \mod 12.$$
In general, by $\frac{a}{b}$ we mean a number that, when multiplied by $b$, will give the value $a$. This definition is also used in modular arithmetic. So $\frac{7}{5} \equiv 11 \mod 12$, because both give the value $7$ when multiplied by $5$ (modulo $12$).
Answer: You can't just divide by $5$ and look at $1.4$. Instead you have to write $7/5=7\cdot 5^{-1}\mod 12$ and thus have to find the inverse of $5\!\!\!\mod \!\!12$. As $5\cdot 5=25\equiv 1\mod 12$ we have: $$7\cdot 5^{-1}=7\cdot 5=35\equiv 11 \mod 12.$$
Comment: You can actually divide by 5 and look at 1.4.  7/5 = 14/10 = 21/15 = 1.4 mod 12.
Comment: @DanielV $14/10$ can either be $5$ or $11$, actually, since $10\cdot5\equiv10\cdot11\equiv14$.
Comment: @columbus8myhw Ah right, because $(12, (14, 10)) \ne 1$...I guess that is just another reason to leave division undefined for non-prime modulus.
Answer: $\frac{7}{5}$ is not an integer, the congruence relation $\bmod n$ is defined over the integers only.
On the other hand there is such thing as an inverse when working with modular arithmetic. Just like when working in the real numbers we have an inverse for $a$, we also have inverses in modular arithmetic. The inverse of the integer $a\bmod n$ is an integer $b$ so that $ab\equiv 1 \bmod n$ (just like in real numbers $a\cdot\frac{1}{a}=1$), we shall denote the inverse of $a$ as $a^{-1}$. It is also interesting to note not every integer has an inverse $\bmod n$ , in general $a$ has an inverse $\bmod n$ if and only if $a$ and $n$ are relatively prime.
So what is the inverse of $5\bmod 12$? it is the number $k$ so that $ak\equiv 1\bmod 12$. We can find it by trying:
$1\cdot 5=5$ no
$2\cdot 5=10$ no
$3\cdot 5=3$ no
$4\cdot 5=8$ no
$5\cdot 5=1$ yes
$6\cdot 5=6$ no
$7\cdot 5=11$ no
$8\cdot 5=4$ no
$9\cdot 5=9$ no
$10\cdot 5=2$ no
$11\cdot 5=7$ no
Hence the inverse of $5$ is $5$ itself (this rarely happens).
With this in mind we can know calculate $7\cdot5^{-1}=7\cdot5=35\equiv 11\bmod 12$

There are much better ways to obtain the inverse of a number, such as logarithmic exponentiation along with fermat or euler's theorem or via the euclidean algorithm.
Answer: The other answers have pointed out the right way to make the calculation. You should refer to them as they promptly answer your question. But I'll try to focus on the implicit question... the "$1.4$" confusion.
First, what is $1.4$? This is a representation. Namely, the decimal representation. That's how you should think of it: a name. It is like how $2$  is equal to  $10$ in binary. The "number" $1.4$, in reality, is $14.10^{-1}$.
The decimal representation comes from a fact in analysis that we can always write a given real number $x$ as a series $x=\sum c_n10^n$. Then, we represent $x$ as $c_nc_{n-1}...c_0.c_{-1}c_{-2}...$.
So, your question has in fact a chance to be interpreted in this context: Is $7.5^{-1}=1.4$? Namely: is $7.5^{-1}=1+4.10^{-1}$?. It turns out that your question, sadly, does not make sense: $10$ is not invertible in your ring!
This goes on to telling: carrying on a representation that has in itself so much "analysis" in its heart as the decimal representation (note that real numbers will be series: limits.) has to be taken with great care.
Now, suppose you were at $\mathbb{Z}_{11}$
Does the equation $7.5^{-1}=1+4.10^{-1}$ make sense? Yes! $10^{-1}=-1$ (and indeed, equal to $10$ itself).
So, let's check if the equality holds:
On one side: $7.5^{-1}=7.(-2)=-14=-3$
On the other side: $1+4.10^{-1}=1-4=-3$
So, in fact, we can say that $7.5^{-1}$ equals $1.4$ in $\mathbb{Z}_{11}$! But note that we have to explicitly expose what we mean by $1.4$, and that things don't carry on as easily. Note also that $1.4$ is simply a name for $-3$ here.
Comment: I apologize for not accepting your recent spam flag. I didn't notice that the poster was the asker, so my interpretation was wrong. Things have taken a turn for worse since. Our definition of spam is a lot narrower than what applies elsewhere in the internet, and I knee-jerk reacted. Sorry.
Answer: $$
5 \cdot 11 = 55 = \underbrace{12 \cdot 4}_{\equiv 0} + 7 \equiv 7 \mod 12.
$$


Download library using Libraries CDN

Question: Does anyone knows how to programmatically download a library from https://cdnjs.com using Libraries CDN ?
Comment: Downloading libraries seems not to be the purpose of that module.
Answer: @cilefen is correct: The purpose of the Libraries CDN API module is not downloading a library, but making the libraries found on a CDN available for your site; if then you are using the Libraries API module, it avoid the needs to download the libraries you need.

Libraries CDN API is an API module to query CDN services to automatically provides libraries on your site.

t also provides an integration with Libraries API. If your module depends on a library that needs to be downloaded and installed in sites/all/libraries and if this library is also hosted on a CDN, this module allows you to use the CDN version of the library very easily, without the need to download the library.
Comment: Thanks for the answer. My bad !
Still, I am looking forward to download the libraries. Do you think there is a way to do it ?
Answer: While this is not the purpose of the Libraries CDN API Module, the module page does say that it's possible:

Libraries CDN API is an API module to query CDN services to automatically provides libraries on your site.
It is bundled with two CDN plugins: CDNJS and jsDelivr.
  Check the very simple API to understand how to query a CDN and how to create your own CDN plugins too.
It also provides an integration with Libraries API. If your module depends on a library that needs to be downloaded and installed in sites/all/libraries and if this library is also hosted on a CDN, this module allows you to use the CDN version of the library very easily, without the need to download the library.
Basically, the module alter the libraries array and adds variants to it, these variants gets their files from the cloud, the module is also able to download a local copy of the library.

Basic API information and examples are available on the module page.

Download library using Libraries CDN


Correctly predicting salt and sugar in the proper sequence.

Question: We have $10$ canisters, $5$ containing sugar and $5$ containing salt. What is the probability of naming them all in the correct order? (example: salt, sugar, sugar, salt, sugar, salt, salt, ...)
It's different from predicting $10$ coins head or tails, because there are limited quantities of each.
Thanks.
Comment: Table sugar has bigger crystals than table salt so you should be able to identify them with probability 1.
Comment: Can we taste a canister in between naming it and naming the next one?
Comment: @Michael: That wouldn't help, because you have to get them all right. So at each stage you have to assume that all your previous guesses were correct.
Answer: You have $\dbinom{10}{5}=252$ different options, so the probability is $\dfrac{1}{252}$
Comment: If the order doesn't matter, it is a Combination.
 If the order does matter it is a Permutation. So shouldn't you be doing a permutation?
Comment: It might be nice to explain why that is so, i.e. that you are picking which canisters will be full of sugar, hence implicitly determining the canisters which will contain salt.
Comment: @MathApprentice: You have *sugar* and *salt*. I think it's a good enough description to allow you to assume that you cannot tell the difference between a *salt* and a *salt* or a *sugar* and a *sugar*. In other words, there is no such thing as *order* here (except for the order between the salts and the sugars of course).
Comment: Then, @barakmanos, we have 10 canisters, each containing white powder. what is the probability of naming the white powders in the correct order? Ordering still matters with respect to the names.
Comment: @user2127595: You simply have $252$ options to choose from, so the probability that you guess correctly is the inverse of that. As hard as I think about it, there is nothing else to explain.
Comment: @MathApprentice: If they have labels (1 to 10) on them, then you're right. In fact, if there is anything unique about them then you're right. But if all there is to say about them is "white powder", then it can be assumed that they are distinguishable only by that character. And in this case, since it's the only specified character, they are not distinguishable at all (in between themselves), hence the answer to your question is $1$. In short, given such question with a list of possible characteristics, you can assume that there is no other characteristic involved.
Comment: Let's bring it down to 3 containers. If we had to name them in the correct order, wouldn't there be 1/8 possibilities of being correct?
Comment: @MathApprentice: What is the contents of each container? 2 salts and 1 sugar? 2 sugars and 1 salt?
Comment: @MathApprentice: The assumption is that you know there are 5 sugars and 5 salts, so you aren't going to make a guess that contains, say, 4 sugars and 6 salts.  So instead of $2^{10}$ possible guesses, there are only $\binom{10}{5}.$  About order: the order of the salts and sugars matters of course, but that's not what $\binom{10}{5}$ refers to.  To make a guess, you have to guess which five of the ten canisters are salt. (The rest are sugar.)  In this, order doesn't matter.  If I guess that canisters 1, 3, 4, 6, and 7 are salt, that's the same as guessing that 6, 4, 7, 1, and 3 are salt.
Answer: An easy way to look at this problem is to first simplify it by assuming there are only $4$ canisters.  Let A = salt and B = sugar.  Then the possible outcomes are AABB, ABAB, ABBA, BAAB, BABA, BBAA.  To determine the number of arrangements of A and B so there that are exactly $2$ of each, just "place" the $2$ As and the $2$ Bs must fill in the other spots.  There are $4 \choose 2$ = $6$ ways to place the $2$ As.  So if we were to guess the order for this simplified example, assuming we remembered to guess a pair of As and a pair of Bs, we would have a $1$ in $6$ chance of guessing correctly.  For $10$ canisters the logic/method is the same except it would be ${10 \choose 5}^{-1}$ = $1$ / $252$ = about $0.3968254$% probability.
Yes this is different than predicting $10$ fair coin flips but if you first told us that you got $5$ heads and $5$ tails, then it would be the same as this sugar/salt problem.
Answer: If we assume that each arrangement of $5$ salt and $5$ sugar canisters are equally likely, then any given arrangement is uniquely determined by the placement of, say, the $5$ sugar canisters among the $10$ canisters total.  For example, we can describe one arrangement as $(2, 3, 5, 7, 10)$, meaning that the sugar canisters are found in positions $2$, $3$, $5$, $7$, $10$ (and the salt canisters are in positions $1$, $4$, $6$, $8$, $9$).  Then clearly, there are exactly $$\binom{10}{5} = 252$$ ways to select $5$ distinct numbers from the set $\{1, 2, \ldots, 10\}$, representing the positions of the sugar canisters, and since each such selection is equally likely (by assumption), the probability of randomly choosing the unique correct representation is $1/252$.


Como deixar em formato moeda?

Question:
<meta charset="UTF-8">
<title>Minha Vida</title>
<link rel="stylesheet" type="text/css" href="css/style.css">

                Corretora
                Ação
                Qtde
                Valor1
                Valor2

                ODPV3
                100
                2.000
                1.000

                ODPV3
                100,00
                2.000,00
                500,00

                WEGE3
                100,00
                1.800,00
                500,00

                Total Investido

Answer: Você pode formatar números em moedas utilizando uma instância da classe Intl.NumberFormat que permite a formatação personalizável de número sensível a linguagem.
Para aplicar o formato a um objeto Number, BigInt ou String use o método Intl.NumberFormat.format()

//Declara e inicie uma instância de Intl.NumberFormat
const fmt = new Intl.NumberFormat(
  'pt-BR',                         //Configura localização como português do Brasil.
  {
    style: 'currency',             //Configura o estilo de formatação como moeda.
    currency: 'BRL'                //Configura a moeda como Real Brasileiro.
  }
)

$(document).ready(function() {
  let total1 = 0, total2 = 0;                      //Traz a declaração dos totais para dentro do escopo do evento ready.
  $('#sum_table tbody tr').each(function() {
    total1 += Number($("td:eq(0)", this).text());  //Faz alguns ajustes para facilitar a leitura do código fonte.
    total2 += Number($("td:eq(1)", this).text());  //Faz alguns ajustes para facilitar a leitura do código fonte.
  });
  //Aplica a formatação.
  $('#sum_table tfoot td#1').text( fmt.format(total1) );
  $('#sum_table tfoot td#2').text( fmt.format(total2) );
});

      Valor1
      Valor2

      2.700
      1.530

      Total Formatado

Para mais informações consulte documentação da API de Internacionalização
Answer: Basta usar a função toFixed() com duas casa decimais.
$('table tfoot td#1').text(total1.toFixed(2));
$('table tfoot td#2').text(total2.toFixed(2));

Como deixar em formato moeda?


Correcting for multiple comparisons in interaction

Question: I have 13 separate hierarchical linear regression models- all models have an interaction term (group by variable of interest) entered as the last step. Since I have 3 dummy coded groups, I have 2 p-values (i.e., a p-value for group A (reference group) vs B, and a p-value for group A (reference) vs C) for each of the 13 models. I want to correct for multiple comparisons, but am having trouble figuring out which p-values I need to correct for. For example, I do not think 0.05 / 26 would be correct as I am not making 26 comparisons (the interaction step is completed in one step). Any thoughts /recommendations other than bonferroni correction would be much appreciated. Thank you.
Answer: First, you can cut your problem in half and improve your analysis by testing the overall significance of the "group by variable of interest" interaction in each model rather than focusing on the individual dummy-variable coefficients as you currently are. The p-values for the individual coefficients depend on your choice of reference value. If you happen to choose the reference level that is in the middle in terms of the magnitude of the interaction, you might have a significant and important difference between the two other groups that is lost due to "insignificant" p-values when they are individually compared against that reference.
A combined test could be a likelihood-ratio test of 2 models in each situation, one with and one without the interaction terms while all other predictors are included.
Second, the Bonferroni correction, despite (because of?) its simplicity is unnecessarily conservative. As the manual page for p.adjust() in R states:

There seems no reason to use the unmodified Bonferroni correction because it is dominated by Holm's method, which is also valid under arbitrary assumptions.

Third, you might be hurting yourself with the multiple parallel models. If you apply your knowledge of the subject matter carefully, you might be able to build a single model that includes all of your predictors of substantive interest and avoid the inevitable loss of power when you try to correct for multiple comparisons among what seem to be otherwise highly similar models.
Comment: Put all the possible interaction terms into a single model and do a likelihood ratio "chunk" $\chi^2$ test of all interaction terms combined.  This provides a perfect multiplicity adjustment.


Criar array ao passar valores pelo POST PHP

Question: Não consegui localizar nada semelhante no forum, não sei se usei as palavras corretas, mas estou com o seguinte problema.
Estou enviando uma sequencia numerica por formulario method POST e depois pego o valor e tento tranformar em array, porém o retorno fica assim:
Array ( [0] => 1,2,3,4,5,6 )

eu preciso que fique assim:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

Meu código está nesta forma:
<?php
$sorteados2 = $_POST['sorteados2'];
$arr2 = array($sorteados2);
print_r($arr2);
?>
<form action="" method="POST">
    <input type="hidden" name="sorteados2" value="1,2,3,4,5,6">
    <button type="submit">Sortear</button>
</form>

Preciso que cada número fique definido separadamente dentro do array, e não agrupados em apeas um.
Existe outra forma de fazer?
Answer: Olá.
Seu campo hidden está enviando uma string com o conteúdo "1,2,3,4,5,6".
Em PHP existe a função explode que transforma uma string em um array, utilizando outra string como separador.
A função espera 3 parâmetros:

O delimitador que será usado como separador de cada item do array
A string que será convertida
Opcionalmente um inteiro indicando o limite máximo para o tamanho do array. Nesse caso, os "pedaços" que poderiam ser elementos do array ficarão na última posição, como uma substring.

$array_sorteados = explode(',', $sorteados2);

Irá retornar:
Array([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6)

E, caso use o limitador (no caso 3)...
$array_sorteados = explode(',', $sorteados2);

... irá retornar:
Array([0] => 1 [1] => 2 [3,4,5,6])

Aconselho a ler a documentação da função, pois existem outros detalhes que não foram mencionados.
Comment: Realmente a informação estava sendo enviada como se fosse apenas uma variavel e o explode com delimitador ao capiturar a informação novamente resolveu meu problema ao recriar o array separando os números corretamente. Obrigado Marcos.
Comment: Disponha estamos aqui para ajudar.
Comment: No caso de resolver o problema, lembre-se sempre de aceitar a resposta.


Can a chord be both major and minor?

Question: So I was messing up with chords the other day and I came with a case where the chord could be both minor and major. I'm wondering if it can be true or if a chord is either, but cannot be both at the same time.
The chord I'm talking about is a Gmin(add♭13) which is also a E♭maj7. I'm playing it thus:
<code>%3/1.6/4.5/3.3/1.3/1.3/1[Gm(add♭13)]
</code>
Comment: I would make a small distinction about your language.  When I first read the title, I was thinking that you were trying to determine if a chord could have both major and minor thirds, arguably making it both major and minor with the same root. I found that the question is actually about analyzing a set of notes to determine which chord tone is the root, where one would make the chord major and another root would make it minor.  This would be an example of how theory and analysis can be subjective and/or ambiguous.  One could interpret it as either chord but convention makes the Eb most likely.
Comment: I put in a chord diagram for your voicing. Please confirm that it's what you meant.
Comment: Yeah thank you! I'm from stackoverflow, hehe, I was not sure how to produce that diagram.
Comment: @sturcotte06 FYI, we use an extension called jTab in code blocks.
Answer: It depends on how you arrange the notes in a chord. The answer is yes, but not on all chords.
If you play a C major chord with a major 6th, you have: C,E,G,A. This is a major chord.
You can rearrange it to create an Am7 chord, if you put the A as the lowest note: A,C,E,G which is a minor 7th chord.
So, in your case, you can read your chord as Gm add b13 or Eb maj7/G (G as the bass); whichever works for you. Usually, you would see this kind of chord as Eb maj7/G rather than Gm add b13.
Comment: I would certainly say that it is much more common and more likely that you would call this chord EbMaj7, more specifically, EbMaj7/G, since G is the lowest note in your voicing.  Add b13 is very uncommon to see, especially outside the Jazz world.
Comment: Perfect, thank you. Could this chord be used for a modal change, since it can be both?
Comment: Sure; Eb could be the Ionian mode and Gm the Phrygian
Answer: The 13th in a minor chord becomes a 5th  when it's flattened. So it reverts in sound to a component of the normal triad.; Thus the chord doesn't really exist. It is Ebmaj7, as you state.
Taking D6th notes and swapping them around produces Bm7, so the answer can be 'yes'.
At a tangent, the Hendrix chord, say, E7#9 could be construed as  both a major and minor chord at the same time, certainly sound-wise, if not technically.
Comment: I'm not from a musical background. The interval between the 5th and the 6th, in the major scale, is a whole tone. In the minor scale, it is a half tone. If I'm refering to the major scale, then I'm adding a flattened 6th. If I'm refering to the minor scale (which 6th is already flattened), i'd add a 6th. That's how I see it, sorry if I don't have the same notation as you =(
Comment: I'm not good with chord notation, but b13 is compared to the major scale. Taking what you just said, I'd call the chord a GminAdd13
Comment: But you stated b13.
Comment: I recently learned that in jazz, the base interval is seen as being from the major scale regardless of the triad. Contrast with classical chord naming where the triad name implies all the unaltered intervals above it. So A Cb E G# is Am(nat. 7) in jazz and Am(#7) in classical. Point being chord naming is far from standardized.
Comment: @ToddWilcox - in A major, 3 is C#. Flatten that for minor, and it is C natural. Cb is equivalent to B. The chord should be A,C,E,G# to make what is known as A minor, major 7th.                                                       Default is, as you say, the major scale notes.
Comment: @Tim - Doh! You are right of course. I started thinking C minor (Eb) and then changed to A minor in my mind and didn't update the third in my mental picture. Thanks for catching that.
Answer: Shevliaskovic and Tim are both right I just want to point something very important about how chords work in general. Because we build chords in thirds and we consider triads (3 note chords) to be the basic unit of a chord, the more notes you have the more triads you can break them into.
For example the E♭Maj7 is spelled:

E♭ G  B♭ D

We can make two different basic triads out of this which are:

E♭ major (E♭, G, B♭)
G minor  (G, B♭, D)

These both are the basic building block of the you noted the chords (Gm(add♭13) and E♭Maj7) can be considered when naming a chord. Depending on what key you are in, where you are going, and where you are coming from one name will make more sense then the other.
As a result of the added tone you can see that both a major and minor triad can be derived and the resulting chord will reflect that whether you call it a major chord or a minor chord. As your chord get bigger in general you add "color" to the sound and the resulting sound is a combination of the sounds not just one or the other.
Another good example of this is the dominant 7th which build off C is:

C  E  G  B♭

We can make two different basic triads out of this which are:

C major (C, E, G)
E diminished  (E, G, B♭)

In this chord we don't just want the typical major chord, we want the dissonance that diminished chord brings, but at the same time we want to be more stable which is found in the major chord. So the chord quality blend in a way we take advantage of.
Answer: Yes. Some said it depends on how you arrange the notes. Wrong. It depends on which note you have in the bass. Play a low C with your left hand and you will hear C6. Play a A and you will hear Amin7, no matter how you arrange notes in your right hand
Comment: Pedro - this is exactly what @Shevliaskovic said.
Comment: Theorizing here: what if I invert the chord so I get the 5th as the bass?
Comment: Then you hear C6/G or Am7/G, depending on context
Comment: `It depends on which note you have in the bass` = `It depends on how you arrange the notes in a chord.`

Can a chord be both major and minor?


#ajax on a managed_file custom form field is not working

Question: I have a custom Drupal 8 form using a managed_file field with an #ajax callback but the ajax callback is never called (example below). I assume that it's because the managed file field type is already using ajax. Is there a way that I can implement my own ajax callback within my custom module to fire after the managed file's own ajax completes?
<code> $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#upload_location' => 'private://',
      '#multiple' => FALSE,

      '#upload_validators'    => [
        'file_validate_is_image'      => array(),
        'file_validate_extensions'    => array('jpg png psd ai bmp eps jpeg pdf tif tiff'),
        'file_validate_size'          => array(56600000)
      ],

      '#ajax' => [
        'callback' => array($this, 'myAjaxCallback'),
        'event' => 'change',
        'wrapper' =>  'im-area',
        'progress' => array(
          'type' => 'throbber',
          'message' => t('Choose City'),
        ),
      ],
    );
</code>
Answer: I don't think you can attach multiple ajax callbacks to a form element. But you could override the callback by extending the core element:
/src/Element/MyManagedFile.php
<code><?php

namespace Drupal\mymodule\Element;

use Drupal\file\Element\ManagedFile;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * My Managed File Element.
 *
 * @FormElement("my_managed_file")
 */
class MyManagedFile extends ManagedFile {

 /**
 * {@inheritdoc}
 */
 public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
    $response = parent::uploadAjaxCallback($form, $form_state, $request);
    $response->addCommand(new AlertCommand('Hello!!!'));
    return $response;
  }

}
</code>
And then use it in the custom form:
<code> $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'my_managed_file',
</code>
Comment: Great answer. Simply works. Upvoted.


Is there any way to restore deleted core block in Drupal 8?

Question: How to restore core/menu or other programmatically created blocks if they have been deleted in D8?
I remember in D6 and D7 was no possibility to delete programmatically created blocks.
But D8 allows to delete any block. If I delete custom block, I can create it again manually, but if I delete for example Page Title block, there is no way to return page title block to my site.
Comment: a) "if I delete for example Page Title block, there is no way to return page title block to my site" is not true, b) if the block was not created programmatically but was a config then you can simply import it again(you have to have the config module installed so you get the import/export UI).
Answer: If you delete some code block in /admin/structure/block
You just need to go on Place block and add block again.

Also Page Title block you can delete and return like this.
In drupal 8 every think is block, menu even a page title.


eval on responseText fails with SyntaxError

Question: I am trying to find a right way to create XML document from responseText. How we will use "eval" here. eval on XML throws SyntaxError.
eval("
This is test
"); --> Will fail

sometimes responseText = "<DATA><static-route><route>0.0.0.0/0</route<nexthop>10.204.247.254</nexthop></static-route></DATA>"
or
responseText = "testing"

parseData(resonseText)

/*create XML Document from the data response */
function parseData (dataSources) {
   try {
        var values = dataSources;

        if (window.ActiveXObject)
            IE = true;
        else if(document.implementation && document.implementation.createDocument)
            IE = false;

              if (IE)
              {
                var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(values);
                //Do more things
              }
              else
              {
                  **//values = eval('('+values+')');**  //Throws SyntaxError
                  var rpcParser = new DOMParser();
                  rpcDocument=rpcParser.parseFromString(values,"text/xml");
                  //Do more things
               }
        }
        catch (e) {
            //Reaches here if use eval function.
        }

};
Thanks,
Vinni
Comment: And what makes you think you should `eval()` it?
Comment: `eval` **only** evaluates JavaScript. `This is test` is not JavaScript.
Comment: so when exactly eval should be used? If server response is in javascript format?
Answer: Eval will only accept valid JavaScript.
This is test
 not valid JS
Comment: That `eval` accepts JSON is a bit misleading. E.g. `eval(JSON_STRING)` would throw an error. Lets just stick with *"it accepts valid JavaScript"* ;)
Comment: I understand that eval works only for Javascript literal. Thanks. Also on what server response eval should be used?


Stance for left handed, right footed boxer?

Question: I've recently started boxing and I'm left hand dominant,right leg dominant and right eye dominant. I feel more comfortable in orthodox but on the pads my coach says my left is stronger. My left would be faster but only very slightly. If I was to draw a bow and arrow I would pull it back with my right. So do I stay orthodox, or move to southpaw?
Comment: Southpaw is for left handed boxing, but what does your coach say about this?
Comment: He told me to box in whatever stance is most comfortable
Answer: This is a personal choice at the end of the day.
Biomechanically a southpaw boxer has the advantage against an orthodox boxer in liver placement and in the fact that their power hand is aligned to it.
The majority of boxers are orthodox so being a southpaw you will see a lot of orthodox boxers while they will not see a lot of southpaws, you will also have the advantage there.
But it all boils down to where you're best at. Pick one and master it, if you get skilled enough you'll be able to switch stances in the middle of a bout.


Inside function How do I use "this.http (Restful)"?

Question: I created an HTTP utilities service and a messaging service.
In the message box, ask the user for consent. And when I agree, I have trouble using the HTTP utility service.
I do not know how to use the HTTP utility service inside the function.
Please help me.
[ Message.service.ts ]
FullScreenConfirm(title, content, fs, ff){
    this.notificationService.smartMessageBox({
        title : title,
        content : content,
        buttons : '[No][Yes]'
    }, (ButtonPressed) => {
        if (ButtonPressed == "Yes") {
            fs(); //success Method
        } else if(ButtonPressed == "No"){
            ff(); //fail Method
        }
    });
}

I purchased the "SmartAdmin" template.
So you can use "notificationService".
[ appManagement.component.ts ]
appDelete(appName) {
    this.messageBoxService.FullScreenConfirm("DELETE", "Are you sure you want to delete?",
    function(){
        this.http.delete(this.http.serverURL + "/delete/" + this.appList.id)
        .then((res) => {
            console.log("SUCCESS");
        });
    },
    function(){
        console.log("FAIL");
    })
}

[ RESULT ]
"ERROR TypeError: Cannot read property 'http' of undefined"
Answer: Classic this scoping issue. With the code in the question, this is isolated to the function it is in and thus has no access to the this object you're trying to access.
To fix this, you'll need to assign a variable to this
appDelete(appName) {
    var self = this;

    this.messageBoxService.FullScreenConfirm("DELETE", "Are you sure you want to delete?",
    function(){
        self.http.delete(this.http.serverURL + "/delete/" + this.appList.id)
        .then((res) => {
            console.log("SUCCESS");
        });
    },
    function(){
        console.log("FAIL");
    })
}

here i assign a reference variable to this named "self" so we can access it within our function.
NOTE: You can get around this quirk by using ES6's arrow function
That would look something like this:
appDelete(appName) {
    this.messageBoxService.FullScreenConfirm("DELETE", "Are you sure you want to delete?",
    () => {
        this.http.delete(this.http.serverURL + "/delete/" + this.appList.id)
        .then((res) => {
            console.log("SUCCESS");
        });
    },
    (err) => {
        console.log(err || "FAIL");
    })
}

Comment: Thank you ... ^^ !  // "()" I first knew this was ES6.
Answer: First you must import it import { Http } from @angular/http, declare it in your constructor private http : Http then you can use it in any fonction like this this.http.post(...).
You should checkout documentation for more details https://angular.io/guide/http
Answer: Inject your dependencies inside your constructor
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response, URLSearchParams  } from '@angular/http';

@Injectable()
export class MyService{

  params: URLSearchParams = new URLSearchParams();

  constructor(
    private http: Http
  ) { }

}

and change your function to ES6 arrow function which binds to this
 function () {
   //code here
 }

 ES6 arrow function

 () => {
   //code here
 }


JQueryUI sortable : Allow sorting only to second list but not back to first

Question: I have two lists I want to use Jquery UI sortable on. The way it is supposed to work is that list One contains a selection of items some of may be dragged to list 2. However sorting within list 1 or dragging back from list 2 to list 1 should not be allowed, finally sorting within list 2 is allowed.
The lists are like this

 Item 1

 Item 2

 Item 3

 Item 4

 Item 1

 Item 2

 Item 3

 Item 4

My current sortable call looks like this
$('#list1, #list2').sortable({
    helper: "clone",
    placeholder: "selected-option",
    forcePlaceholderSize: true,
    dropOnEmpty: true,
    connectWith: '.sortable',
    tolerance: "pointer",
    revert: true,
    cursor: "move",
    receive: function (event, ui) {
        // existing logic

    },
    update: function (event, ui) {
        // existing logic
    }
});

I know that I will have to manipulate the stop, receive functions on the sortable call to achieve this, but am not able figure out how to ..
Answer: $('#list1, #list2').sortable({
  helper: "clone",
  placeholder: "selected-option",
  forcePlaceholderSize: true,
  dropOnEmpty: true,
  connectWith: '.sortable',
  tolerance: "pointer",
  revert: true,
  cursor: "move",
  beforeStop: function (event, ui) {
    if($(ui.helper).parent().attr('id') === 'list1' && $(ui.placeholder).parent().attr('id') === 'list1')
       return false;
    else if($(ui.helper).parent().attr('id') === 'list2' && $(ui.placeholder).parent().attr('id') === 'list1')
        return false;
  }
});

http://jsfiddle.net/py7FN/
Comment: thank you my apologies i was off for couple of days, yes your logic satisfies all my queries but I actually had to split it into two sortable calls as i had to do additional update actions on each list independently and it was becoming cubersome to validate each item all the permutation's involved. I did take your logic of using helper and placeholder object ids... thanks much :D


Why is git not using identity set in ssh config file?

Question: I am trying to connect to my local Gitea server. I have set it up to use the integrated SSH server on port 2222. I am running Windows. Gitea is running fine.
Now I want to connect using Cygwin's git. For testing the connection to my repository I am using the ls-remote command which works fine if I use the GIT_SSH_COMMAND option like this:
GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa" git ls-remote --exit-code -h ssh://username@localhost:2222/username/Repo.git

Next I want to simplify life using ~/.ssh/config:
host gitea
 HostName localhost
 Port 2222
 IdentityFile ~/.ssh/id_rsa
 User username

However, this does fail with error Unable to open connection:
git ls-remote --exit-code -h ssh://gitea/username/Repo.git

Problem: IdentityFile is not applied. This works:
GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa" git ls-remote --exit-code -h ssh://gitea/username/Repo.git

I am certain though, that my ~/.ssh/config is correct, because connecting via directly ssh -vv gitea works. Output (extract):
[...]
debug1: Connecting to localhost [::1] port 2222.
debug1: Connection established.
[...]
debug1: Offering public key: RSA SHA256:XXX /home/username/.ssh/id_rsa
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug2: input_userauth_pk_ok: fp SHA256:XXX
debug1: Authentication succeeded (publickey).
Authenticated to localhost ([::1]:2222).
[...]

So why is git not using IdentityFile from ~/.ssh/config?
Answer: It turned out that setting GIT_SSH_COMMAND="ssh" was enough. This means that git was using some other SSH client. Probably the one of OpenSSH which happened to be on the system path:
$ whereis ssh
ssh: /usr/bin/ssh.exe /cygdrive/c/WINDOWS/System32/OpenSSH/ssh.exe /usr/share/man/man1/ssh.1.gz

I fixed the issue by adding export GIT_SSH_COMMAND="/usr/bin/ssh" to ~/.bash_profile
Comment: This worked for me... I was using Window's Git command on my cygwin command line (as I checked what git it was using by trying 'which git') and realized maybe its not using the ssh command i want. just adding this GIT_SSH_COMMAND="ssh" env var worked for me


Cursors are shifted on iOS

Question: Could anybody help me?
I have an issue related with shifted cursors. Problem is only on in chrome and safari on iOS 11. It looks like

Thanks
Comment: Possible duplicate of [How to fix the iOS 11 input element in fixed modals bug](https://stackoverflow.com/questions/46567233/how-to-fix-the-ios-11-input-element-in-fixed-modals-bug)
Answer: This appears to be related to a WebKit bug wrong caret position for input field inside a fixed position parent on iOS 11 demonstrated by Eirik Luka.
Possible workarounds:

Stretch the dialog to the edges of the window, hiding the rest of the content in the body with display: none
Change the container from position: fixed to position: absolute
Do not use modal dialogs
Comment: Thanks, I realized the second variant.

Cursors are shifted on iOS


How to retrieve user details from mention tweets?

Question: I am in the processing of creating a bot that reads all mentions in userstream Twitter timeline and reply accordingly, however I cannot seem to get the users details who posted the mention in order to reply back, all I receive is the mention status/text.
I am using Python and Tweepy API to achieve this:
import tweepy
from tweepy import Stream

consumer_key = '********'
consumer_secret = '********'
access_token = '***********'
access_secret = '*********'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

class MyStreamListener (tweepy.StreamListener):

    def on_status(self, status):
        print(status.text)

    def on_error(self, status):
        print(status)

    def on_direct_message(self, status):
        print(status)

twitterStream = Stream(auth, MyStreamListener())
userStream = twitterStream.userstream()

Any help would be greatly appreciated
Answer: It needed
print(status.author.screen_name)


Scraping google search for sentences based on keywords in google sheets document

Question: I wish to scrape google search results (only the description text) for sentences based on keywords in a google sheets document.
All words will be in column A.
Example of some of the data:

What I require to do is to search google for: "埴生の宿" jp blog and then go down the search results and copy all sentences that are longer than 14 characters and shorter than 30.
The sentences must be between。 .or the 、 characters or at the start of the description and can include、 as long as it stays within the character limit.
Once a sentence has been scraped it puts the sentence into the adjacent excel row alongside the keyword.  It will repeat this 10 times searching for 10 different sentences for the same word up until column K, then move onto the next word and provide 10 sentences etc.
Is this task possible via google sheets? Or what would be the quickest and easiest way to complete this? There are 40,000 words in column A, so I would need to fetch 400,000 sentences.
Answer: Your best option is likely to write a simple script in Python/similar language which makes use of a SERP or Search Engine Results Page API such as SerpStack to get the descriptions in an easily further searchable way.
You then use your script to read from the CSV/whatever file, search, find and record sentences.
Only problem with this method is it is slow - I'm sure others here can recommend faster APIs and searching methods.
Comment: Is 400,000 possible? Or is it too large a scrape
Comment: It might take too long. I have a GCP Cloud function which does a similar thing by searching inside search results from SerpStack snd it takes a while 10s+ per search. On top of that if you're doing 40k searches it's going to cost you money, $200 from SerpStack for this service. You might be better off trying a python library to scrape the search results locally - it'll be faster and cheaper but it's not something I yet have experience with.


Delta Method around zero is a N(0, 0)

Question: I have this problem: $\sqrt N \hat{\theta} \sim N(0, V)$ where $E(\hat{\theta}) = \theta_{0} = 0$. I must find the asymthotic distribution of $\frac{N}{V}\hat{\theta}^{2}$ but if I use the Delta Method I get that $\frac{N}{V}\hat{\theta}^{2} \sim N(\frac{N}{V}\theta_{0}^{2}, \frac{4\theta_{0}^{2}}{V}) = N(0, 0)$.
Any way to evade $N(0,0)$?
Thanks!
Comment: https://en.wikipedia.org/wiki/Delta_method read second order delta method
Answer: Hint: The delta method is not needed here.  The square of a standard normal random variable is a chi-squared random variable with one degree-of-freedom.

Delta Method around zero is a N(0, 0)


Is it true that sports which use motorized equipment cannot participate in Olympics?

Question: I have heard that sports that use motorized equipment cannot participate in the Olympics, such as Formula One. Is it true or just rumor?
I am talking about those equipments which are used by players while playing.
If this is true, why do they not allow such sports to participate? If it is wrong, is there any sport that uses motorized equipment and has participated in the Olympics?
Comment: Do you mean "motorized" in place of "electronic?"
Comment: @edmastermind29 - Yes. I think "motorized" is more suitable than "electronic".
Answer: Motorsports are not currently part of the Olympics, although there is no rule banning them.  In fact, in the 1900 Olympics in Paris, automobile, motorcycle, and motorboat racing were demonstration events, and in the 1908 Games in London, there were three motorboat racing events as an official part of the games.
However, there haven't been any motorsports in the games since then.  IOC president Jacques Rogge, speaking specifically about Formula One, said in 2012,

Frankly speaking, the concept we are having is the games are about the competition for the athletes not for equipment. Therefore, while having a lot of respect, they will not be included into the Olympic program. (Source)

As a result, it is not likely that we will see motorsports in the Olympics in the near future, although there are a lot of motorsports drivers and fans that would like to see these events included in the Games once again.


Who is the correct owner and group for these system files? (Digital Ocean Droplet running Ubuntu 20.04)

Question: This should be a simple answer for anyone using a Digital Ocean droplet on Ubuntu 20.04. I accidentally ran a command that changed ownership and group of a bunch of files in /var (outside the directory I was working in). I've managed to restore the owner/group on most of the files, but I am not sure what the owner/group for the following files should be:
/var/log/droplet-agent.update.log
/var/log/ubuntu-advantage-timer.log
/var/log/ubuntu-advantage.log

If anybody has a Digital Ocean droplet with these files, will you please post the owner/group info? It could be root:root or it could be root:syslog or it could be anything else for that matter.
Thanks in advance.
Answer: After creating another droplet, I was able to check, and all of these files should be owned by root:root.


How to read multi line multi string registry entry in Visual C++?

Question: I am using Visual Studio 2008. I am working in vc++ mfc application.
I want to know how to read multi line string value from registry.Here type REG_MULTI_SZ indicates A sequence of null-terminated strings, terminated by an empty string (\0).
So far I am able to read only first line. Give me Idea about how I can read multi string at once.
Thanks

I tried Something like this
HKEY hKey;
CString RegPath = _T("SOFTWARE\\...\\...\\");   //Path
if(ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,RegPath,0,KEY_READ|KEY_ENUMERATE_SUB_KEYS|KEY_QUERY_VALUE | KEY_WOW64_64KEY,&hKey))
{
    DWORD nBytes,dwType = REG_MULTI_SZ;
    CString version;
    if(ERROR_SUCCESS == ::RegQueryValueEx(hKey,_T("Options"),NULL,&dwType,0,&nBytes))
    {
        ASSERT(REG_MULTI_SZ == dwType);
        LPTSTR buffer = version.GetBuffer(nBytes/sizeof(TCHAR));
        VERIFY(ERROR_SUCCESS == ::RegQueryValueEx(hKey,_T("Options"),NULL,0,(LPBYTE)buffer,&nBytes));
        AfxMessageBox(buffer);     //Displaying Only First Line
        version.ReleaseBuffer();
    }
::RegCloseKey(hKey);
}

Comment: Show what you have tried so far. Then it' will be mich easier for us to answer your question.
Answer: Suppose your multi string consists of two strings "AB" and "CD".
The layout in memory is like this:
+--------+
|  'A'   |   <-- buffer  // first string
+--------+
|  'B'   |
+--------+
|   0    |    // terminator of first string
+--------+
|  'C'   |    // second string
+--------+
|  'D'   |
+--------+
|   0    |    // terminator of second string
+--------+
|   0    |    // terminator of multi string
+--------+

Therefore AfxMessageBox(buffer) displays only the first string.
You shouldn't read the multi string into a CString, because CString only deals with nul terminated strings. You should read the multi string into a TCHAR buffer and then parse that buffer in order to extract the individual strings.
Basically:
 ASSERT(REG_MULTI_SZ == dwType);
 LPTSTR buffer = new TCHAR[nBytes / sizeof(TCHAR)];
 VERIFY(ERROR_SUCCESS == ::RegQueryValueEx(hKey,_T("Options"),NULL,0,(LPBYTE)buffer,&nBytes));

 CStringArray strings;
 const TCHAR *p = buffer;
 while (*p)               // while not at the end of strings
 {
   strings.Add(p);        // add string to array
   p += _tcslen(p) + 1 ;  // find next string
 }

 delete [] buffer;

 // display all strings (for debug and demonstration purpose)
 for (int i = 0; i < strings.GetCount(); i++)
 {
   AfxMessageBox(strings[i]);
 }

 // now the strings array contains all strings

Comment: That is what I want to know, How to find next strings? As in example shown by you how can I get string `CD`.
Comment: Sorry to say but m still getting same result. It is showing only first line.
Comment: Of course, **you** must parse `buffer`. `AfxMessageBox` stops at the first NUL character, so in my example it will display only "AB".
Comment: See my edited answer. You should get some basics of C/C++/MFC.
Comment: It is showing some Conversion errors, After Solving this issue I will get back.
Comment: I did'nt compile that code, but you should get the idea.
Comment: Why are you mixing `TCHAR` and `char`? And your `delete buffer` is wrong.
Comment: @JonathanPotter you are right, as I said, it's not tested neither I tried to compile. I've corrected it. Thanks.
Comment: Some problem is there in `p += _tcslen(p) + 1 ;` I tried `_mbstrlen` in that place. Now first string it is showing correct After that it is showing some different characters.
Comment: Try `wcslen` or `strlen` instead of `_tcslen` You should be able to sort this out with the debugger.
Comment: The code in my answer works here perfectly both with the Unicode Character Set ans with the Multi-Byte Character Set.
Comment: Do be careful with `RegQueryValueEx()`, it does not ensure the data is null-terminated properly, it reads the data as-is and requires the original writer to have saved proper nulls. To ensure proper nulls regardless of the original data, use `RegGetValue()` instead.
Comment: I'm also doing the same thing but why in my PC it is not working. Only first line m getting correct.


Access excel formulas programatically

Question: I have an excel sheet with formulas and I want to write a script to use these formulas in my project.
I tried using openpyxl library but it only reads the formula (e.g. =SUM(C11:C17)) or if I use load_workbook(file, data_only=True) , it does not update calculations.
Is there a way to use the formulas outside the excel sheet?
Edit:
The table values
| C            |
| ------------ |
| 5            |
| 2            |
| 3            |
| 4            |
| 5            |
| 2            |
| 1            |
| =SUM(C11:C17)|
wb = load_workbook(file, keep_vba=True, data_only=True)

ws = wb["Sheet1"]
c = ws['C11']
print(c.value)

c2 = ws2['C18']
print(c2.value)

ws['C11'] = 0

print(c2.value)

Result:
5
22
22 (expected 17)

Comment: `data_only=True` should work fine.Post some of your code
Comment: you need to use `.value` over the cell to get the value
Answer: If you need to interact with excel openpyxl is not enough, xlwings from Felix Zumstein can do it using com objects.
Other "out of the box" solutions are pycel from Dirk Gorissen that can run formulas in a python environment or XLtoy[] that can extract formulas in a convenient way.
[] I'm the main developer.

Access excel formulas programatically


Erro ao tentar estabelecer conexão entre SQL Server 2014 e Visual Studio

Question: Estou tendo problemas para realizar a conexão do Visual Studio 2010 [c#] com o Sql server 2014. Segui alguns tutoriais mas não tive sucesso.

Porque está acontecendo tal erro?
Comment: Por favor, poste também a parte do seu código em que você se conecta com o banco
Comment: Poste a sua ConnectionString.
Comment: Estava seguindo este tutorial, criei o projeto mas quando fui  adicionar o Service-based Database aconteceu o erro. Segue tutorial:[link]http://msdn.microsoft.com/pt-br/library/ms233763%28v=vs.100%29.aspx
Comment: Não cheguei a configurar uma connection String, pois ainda não vi como fazer..
Comment: Saberiam me informar alguma versão para download do Sql Server em uma versão anterior, utilizo Windows 8 x64 e sempre que tento instalar outra versão ocorre erro de compatibilidade.
Comment: Já viste se o serviço "SQL Server Browser Service" está activo?
Comment: Está em execução.
Comment: Pode ser por causa da firewall: http://msdn.microsoft.com/en-us/library/cc646023.aspx

ou por não estar configurado para aceitar ligações externas: http://support.webecs.com/kb/a868/how-do-i-configure-sql-server-express-to-allow-remote.aspx
Comment: Isto não fornece uma resposta à pergunta. Para criticar ou solicitar esclarecimento de um autor, deixe um comentário abaixo da publicação dele - você sempre pode comentar em suas próprias publicações e quando tiver [pontos de reputação](http://pt.stackoverflow.com/help/whats-reputation) suficientes você poderá [comentar sobre qualquer publicação](http://pt.stackoverflow.com/help/privileges/comment).
Comment: Desativar o firewall resolve? Meu inglês não está ajudando..
Comment: Experimentaste desativar o firewall? Que protocolos de comunicação do SQL Server tens ativos - memory, pipes, tcp?
Comment: shared memory, tcp/ip, named pipes, via
Comment: Já liberou a porta 1433?
Comment: @Pegasus olha esse tutorial de como configurar a porta http://support.webecs.com/kb/a868/how-do-i-configure-sql-server-express-to-allow-remote.aspx
Comment: Acabo de encontrar a resposta no MSDN. Segue link para quem interessar: http://msdn.microsoft.com/en-us/library/e8db82f0-50ed-4531-9209-940006ed34cb(v=sql.110)#connect
Comment: Consegui resolver. Segue o mesmo link em português: http://msdn.microsoft.com/pt-br/library/ms345332.aspx
Answer: Pegasus, tente isso;

Certifique-se de que o nome da instância está correto. (EX: NomeInstancia\NomeBanco)
Certifique-se que a máquina usada como servidor está acessível. (Você pode usar o ping no prompt de comando para verificar se a máquina está ligada)
Certifique-se de que o SQL Server está em execução no servidor. (Se possível vá ao servidor e tente se conectar através do SQL Server Managment Studio com suas credenciais)
Se o firewall estiver habilitado no servidor, você precisará adicionar uma permissão para o sqlbrowser.exe e/ou porta UDP 1434 em exceção.

Fonte: http://goo.gl/hDnMXZ
Answer: Erro 26 é porque o servidor SQL não está em execução. Ou seja, ta desligado. Isso é normal de acontecer quando se reinicializa a máquina. Pra resolver é fácil. Vá no menu iniciar, procure por Microsoft SQL Server Versão(2008,2012,2014) clique e  procure por Ferramentas de Configuração, depois clique em SQL Server Configuration Manager. Ao clicar ele vai uma janela e ai vai vá em  Serviços do SQL Server e procurar por SQL Server(SQLEXpress) dai é só clicar duas vezes e pronto, o server ta up ! Espero ter ajudado !


multi-armed bandit with seasonality

Question: I'm working on implementing a multi-armed-bandit-like approach for determining the best price to offer for a product. Our goal is to optimize profit, meaning, we want to find the price where (price-cost) x number of purchases is greatest. The problem is that there is a known pattern of seasonality within the week. So, if I set the price to the same thing on a Monday vs. a Wednesday, they might have dramatically different volume.
That's my specific situation, but it started me wondering more broadly about using a multi-armed bandit when there are external factors (aside from which "arm" of the bandit you pull) that affects the results you get. Is there a way of taking these factors into account? Perhaps there are results that suggest that if you run the algorithm long enough, it converges in spite of the other factors?
Comment: I like the way you talk about retail in terms of banditry... ;-) One thing to keep in mind is that price sensitivity (demand elasticity) will vary over the week. And if a bargain succeeds in drawing the Saturday buy-for-the-whole-week crowd, it may result in halo effects even for non-promoted items for people who do their whole week's shopping at the place that has the most attractive promotions on each particular Saturday. The whole topic is really much too big for a CrossValidated question (after all, there are people making their living doing just this - like me, for instance).
Comment: I definitely get that! I'm fine with starting out with a simple bandit and working my way up from there. Are there any papers you would recommend reading?
Comment: Sorry, nothing that really comes to mind... Good hunting!
Comment: There is a sizable body of work under the title "contextual bandits", which might be of interest to you.
Comment: thanks! I think that's what I was looking for, just didn't know what it was called.
Answer: There is a sizable body of work under the title "contextual bandits", which might be of interest to you.
A bit more information.
Contextual bandit algorithms attempt to solve the problem of picking the arm of a multi-armed bandit conditioned on some random vector (called the context). There is a discussion of the problem in this blog post. The traditional application is for internet advertising, where say the system sees a user's query (which is the context) and has to pick from one of K possible ads to show.
Answer: The setting you describe resembles non-stationary bandits. In this setting, the means of the arms are allowed to vary over time.
The following papers might be of interest:

A Linear Bandit for Seasonal Environments
Stochastic Multi-Armed-Bandit Problem with Non-stationary Rewards
On Slowly-varying Non-stationary Bandits

Here there are also have these lecture notes which seem relevant.

multi-armed bandit with seasonality


MySQL month over month totals compared to previous month

Question: I'd like to sum the amount column for a given month, as well as the total for the previous month. Right now the first month's total works, but every month thereafter is too high by at least 2 order of magnitude.
SELECT month, year, total, previous_month, previous_year, previous_total FROM (
  SELECT MONTH(p1.start_date) AS month,
    YEAR(p1.start_date) AS year,
    SUM(p1.amount) AS total,
    SUM(p2.amount) AS previous_total,
    MONTH(DATE_SUB(p1.start_date, INTERVAL 1 MONTH)) AS previous_month,
    YEAR(DATE_SUB(p1.start_date, INTERVAL 1 MONTH)) AS previous_year
  FROM trackings p1
  LEFT JOIN trackings p2 ON EXTRACT(YEAR_MONTH FROM DATE_SUB(p1.start_date, INTERVAL 1 MONTH)) = EXTRACT(YEAR_MONTH FROM p2.start_date)
  GROUP BY EXTRACT(YEAR_MONTH FROM p1.start_date)
) AS p3;

Related question: I'm doing the same DATE_SUB 3 times. Is there a way to clean up the date related parts to be more efficient?
Sample: http://sqlfiddle.com/#!2/3013a/1
Comment: Please elaborate with some sample input outputs. I'm not following.
Comment: @JackDev Apologies. Created a SQL Fiddle to show what I meant. The first month adds up correctly, but starting with the second row, the output is not correct (for the total and previous_total)
Comment: I agree with JackDev. Otherwise, it is just guessing.
Answer: Think the problem is you are getting rows counted multiple times on the join. Ie, you have a sum of all the amounts for a month, but each row from that month is being joined with all rows for the previous month.
Solution using a couple of subselect:-
SELECT ThisMonth.MONTH, ThisMonth.YEAR, ThisMonth.TOTAL, PrevMonth.MONTH AS PREVIOUS_MONTH, PrevMonth.YEAR AS PREVIOUS_YEAR, PrevMonth.TOTAL AS PREVIOUS_TOTAL
FROM
(
    SELECT MONTH(start_date) AS `month`,
            YEAR(start_date) AS `year`,
            EXTRACT(YEAR_MONTH FROM start_date) AS YearMonth,
            SUM(amount) AS total
    FROM trackings
    GROUP BY `month`, `year`, YearMonth
) ThisMonth
LEFT OUTER JOIN
(
    SELECT MONTH(start_date) AS `month`,
            YEAR(start_date) AS `year`,
            EXTRACT(YEAR_MONTH FROM DATE_ADD(start_date, INTERVAL 1 MONTH)) AS YearMonth,
            SUM(amount) AS total
    FROM trackings
    GROUP BY `month`, `year`, YearMonth
) PrevMonth
ON ThisMonth.YearMonth = PrevMonth.YearMonth


End date with null value :db2-sql

Question: i have a table my_date

id        Start          END
1       2021-01-13     2021-04-15
1       2021-04-16     2021-11-28
1       2021-11-29        null
2       2021-05-05     2021-09-13
2       2021-09-13     2021-12-31
3       2020-01-09     2021-08-29
3       2021-08-30     2023-04-15

what i want to want to choose the id that have max(end)<= 2021-12-31
so my result should be just

id        Start          END
2       2021-09-13     2021-12-31
Comment: According to the description your result is wrong. It should be the next row `2 - 2021-09-13 - 2021-12-31`.
Comment: @-The Implaer . YES  i will correct it
Comment: max (end_dt) = 2021-11-28 for id = 1 is less than 2021-12-31 as well. Why don't we see the corresponding row in the output?
Comment: 1       2021-04-16     2021-11-28  i donnot want because  id  1 has another record 1       2021-11-29        null that null is consider  oppen date
Comment: Does this answer your question? [Fetch the row which has the Max value for a column](https://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column)
Answer: Try this:
SELECT id, Start, END
FROM
(
SELECT *
, ROW_NUMBER () OVER (PARTITION BY ID ORDER BY Start DESC) AS RN_
FROM
(
VALUES
  (1, '2021-01-13', '2021-04-15')
, (1, '2021-04-16', '2021-11-28')
, (1, '2021-11-29', null)
, (2, '2021-05-05', '2021-09-13')
, (2, '2021-09-13', '2021-12-31')
, (3, '2020-01-09', '2021-08-29')
, (3, '2021-08-30', '2023-04-15')
) T (id, Start, END)
) T
WHERE RN_ = 1 AND END <= '2021-12-31'

dbfiddle link
Answer: You can filter by the date limit, then order by date in descending manner, and finally retrieve the first row only.
For example:
select *
from t
where end <= date '2021-12-31'
order by end desc
fetch next 1 rows only

Result:
ID  START       END
--  ----------  ----------
 2  2021-09-13  2021-12-31

See running example at db<>fiddle.

End date with null value :db2-sql


shape file (GIS) to text

Question: How I can convert a shape file (GIS) to text?
or, How I can extract the information in a shape file?
Answer: Mapwindow (http://mapwindow.org/) is free, open source, and has a convert shp to csv feature.
The csv files it produces are a little strange, but you should be able to manage.
Windows only.
Comment: I not find the option to convert to csv, but I use shape2earth plugin and convert to kml.
Answer: If you are willing to write some code (and you will probably need to anyway as there is quite a bit of information in a shapefile, not all of it of interest for any given application)  check out shapelib. It has bindings to many scripting languages.  It also builds dbfdump which is an executable for dumpint the dbffiles and shpdump that dumps the shp files.
Also of interest if you program in R is the maptools package.
Answer: look into Gdal/ogr bindings
Answer: I wrote a small app that can convert your shapefile to KML. Not exactly text but human readable and shareable across map applications. http://www.reimers.dk/files/folders/google_maps/entry328.aspx
Answer: Try to use MyGeodata GIS Data Formats and Corrdinate systems Converter - online. It uses OGR library mentioned here and alows to convert most used GIS formats to any other GIS format - so for you for example from ESRI ShapeFile to GeoJSON, GML, CSV or other text-based formats.
Answer: There is a web page to view the contents:
http://webprocessresults.com/pgsActv/ShpDump.aspx
The same site offers a free desktop (windows) version:
http://webprocessresults.com/svcs/FreeStuff/FreeStuff.aspx
Answer: If you are using arcGIS and the shapefile is composed of several files you can try just opening the .dbf file in excel and saving it into another format (e.g. csv)- I've done this plenty of times and haven't had any ill effects and its a pretty quick and easy method of converting your shapefiles or doing any drastic edits saving as csv then reimporting them back into GIS for saving as a new shapefile. I will say this is and inelegant solution though ;)
Answer: You can find most of the shp (Shape File) format detailed here: http://en.wikipedia.org/wiki/Shapefile. The full specification is here: http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf.
The shp file format is very simple, but be careful to mind that the length fields are for 16-bit words not 8-bit words. If you forget this you will spend a bit of time debugging what is going wrong when trying to parse out the records.
The dbf generally contains information associated with each shape. You can also parse the dbf file but you will have to roll your own reader. I have done it before, but the easiest may be to load the dbf up into some spreadsheet application and then save it as a csv file then load that. Also, if I remember correctly you have to be careful as some of the sites out there detailing the dbf can be a little off. It had something to do with a different version where some fields are a little different. So if you are rolling your own and you get stuck be mindful that you may be reading it correctly but it is differing from the specification you are using. I think the solution was that was to return to Google and search up some different docs and finally detailed the version I was reading.
The shp and dbf are linked by the record index. The first record in the shp is linked with the first record in the dbf and so forth.
You can fairly easily find format specifications for dbf such as here: http://www.clicketyclick.dk/databases/xbase/format/index.html. If you are willing to roll your own it will not be too much of a project.
In any regard no matter if you choose to roll your own reader for dbf or shp you will need to be mindful of the fields as some are big and others little endian byte ordering. I think this only applies to the shp file.
Answer: You can open dbf file and copy content to another format, for example odt or XLSX.
For open dbf file recommend to use LibreOffice Calc
Answer: If you are really in need of only the content in the shapefile., then looking for the .dbf file would give you a better view. You can directly open ".dbf" file with any excel viewer to look for the content in the shapefile.

shape file (GIS) to text


Problema com escrever em textbox escondida com Selenium

Question: Estou tentando escrever em uma textbox e clicar em um botão (esses elementos estão inicialmente escondidos na página) utilizando selenium (com Java), mas não consigo achar o elemento, já tentei procurar por name, ID, tagname, className, XPath, não consigo manipular de maneira alguma.
Segue print da tela com inspecionar elementos ativo.

O que acontece é que para essa textbox e botão aparecerem na tela eu preciso clicar no botão requerer (até essa parte eu consigo):

Aí os elementos que comentei ficam ativos:

No código abaixo eu peguei a quantidade de elementos que eu encontro na página que tenham o mesmo id, name, tagName, className ou XPath da textbox que quero manipular (as 2 primeiras linhas é para apertar o botão requerer, essa parte está funcionando):

Ou seja, em todas as formas de manipular a textbox retornam que não existe tal elemento (a não ser className, mas desses 10 elementos encontrados nenhum é a textbox que quero manipular, já testei um por um).
Como essa página faz parte de um portal local da empresa em que trabalho, não adianta eu passar um link para verificarem, por isso mandei diversos prints.
Alguém sabe de alguma forma de lidar com esses elementos hidden?
Answer: Você pode utilizar a classe JavascriptExecutor para executar um código Javascript na própria página, e deixar o elemento visível:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('_Justificativa').style.visibility = 'visible'");

Pode setar o valor:
String texto = "Ola Mundo!";
jse.executeScript("document.getElementById('_Justificativa').value = '" + texto + "'");

E caso necessário, pode clicar no elemento também:
jse.executeScript("document.getElementById('_Justificativa').click()");

Comment: Caio, esse código seria para manipular o IE né? Você saberia fazer isso manipulando o chrome? Qualquer coisa tento traduzir meu código pra manipular o IE e testar essa idéia.
Comment: Tentei utilizando esse codigo:
WebElement txb =driver.findElement(By.name("_Justificativa"));

        jse.executeScript("arguments[0].click();", txb);

Mas na linha que tento encontrar o elemento dá erro e o programa para.
Comment: Esse código funciona pra qualquer navegador, creio eu! Eu mesmo uso sempre o Firefox e nunca tive problema, não é para ter dor de cabeça com o Chrome também.

Em relação a esse seu erro, ele se dá pois o elemento está escondido, e o Selenium tenta encontrar o WebElement mesmo assim.
O que imagino que seja viável e funcione, é o que eu publiquei na resposta, que seria uma "injeção" javascript. Tenta usar exatamente como tá ali, e me dá uma resposta pra saber se deu certo!
Comment: Agora eu consegui. Percebi que a textbox e o botão estavam dentro de um iFrame, e ao pesquisar na internet vi que tinha que usar "driver.switchTo().frame(0);" para depois conseguir escrever nele. O javascript dava erro porque não conseguia encontrar nenhum elemento com o nome ou id que eu passava.
Comment: Entendi. Ótimo que conseguiu resolver! Você também consegue mudar para o frame passando o ID dele como argumento, caso precise, e por questões de facilitar a visualização também.
Comment: Muito obrigado pela ajuda. No meu caso não daria certo passar por ID ou por Name porque esses identificadores não são fixos na minha iFrame, cada vez que rodo o programa eles mudam, por isso tive que optar pelo índice.
Answer: Agora consegui resolver.
Para os próximos que tiverem o mesmo problema que eu:
Após ir subindo no inspecionar elemento notei que toda aquela div que englobava a caixa de texto e o botão era um iFrame, vi nesse site (https://www.guru99.com/handling-iframes-selenium.html) que precisava dar os seguintes comandos:
driver.switchTo().frame(0);

        driver.findElement(By.name("_Justificativa")).sendKeys("teste");

No caso o "0" do "driver.switchTo().frame(0)" é o índice do meu iFrame, caso tenha mais de um iFrame na página será necessário verificar qual é o que você precisa manipular, pode usar o comando "driver.findElements(By.tagName("iframe").size());" para identificar a quantidade de iFrames na página.
Pra mim isso resolveu.