What is the relationship between the 5th and minor 7th in dominant chords?

Question: I've been trying to understand the theory behind dominant sevenths and have been reading a lot of articles. There's just one thing I couldn't understand-- the basic relationship of the minor 7th to the 5th.
Wikipedia says:
In music theory, a dominant seventh chord, or major minor seventh chord,[a] is a seventh chord, usually built on the fifth degree of the major scale, and composed of a root, major third, perfect fifth, and minor seventh. Thus it is a major triad together with a minor seventh, denoted by the letter name of the chord root and a superscript "7".[3] An example is the dominant seventh chord built on G, written as G7, having pitches G–B–D–F:
What do they mean by it being built on the fifth degree of the major scale? I played around on the keyboard trying to figure out a relationship of Bb to G and I couldn't make one out.
Take key of C and the C7. The dominant 7th is root-major 3rd-perfect 5th-minor 7th. That's easy, but what's the relationship of Bb to G? G major triad is just 5-7-9 of the C and Gmaj7 adds an 11. Moreover, since we're talking C, it's guaranteed to be all white keys, yet the minor 7th is black.
It seems like the minor 7th is just injected in there arbitrarily and doesn't seem connected to anything else in the key, which is alright, but I know there's supposed to be a relationship.

I maybe figured it out by playing around but I won't answer my own question because I'm not sure and don't want to spread errors, but here's what I got.
If you think in the key of C only you can't figure out where the minor 7th comes from and therefore what builds C7, but you can figure out what G7 will be and where that minor comes from. The knowledge of the key of C gives you knowledge of G7. It appears to be just 3 degree-stepovers (i.e. 1 to 3 or 2 to 4 is a stepover) of the notes in the key of C, starting at the 5th. I'm trying to be careful not to call them whole steps because that has a different meaning, and it indeed makes the dominant chord sound when played. Since the 5-7-9 of a given key is guaranteed to be a major chord in the 5th position (perfect fifth triad that many know from the I-ii-iii-IV-V-vii-dim model), that gives us the triad base we need. Now all we need is to bring in the 7th, specifically a minor 7th, which if instead of switching keys to the key of the fifth, we confine ourselves to the key that our fifth is the fifth of, the 7th is a natural minor (I thought this had to do with 'relative minor' but now I don't think so). BTW I apologize if I sound both naive and then over the top. I'm learning this all on my own by reading and thinking about it.
So to get the C7 dominant, we have to think backwards and find what C is the perfect 5th of, and that would be F. Now stay in the key of F and take 3 "steps-overs" or hops, from it's 5th ('-') =>  C-E-G-Bb. There's our Bb, linked to both a 5th and to a tonic. It's linked to the tonic F and C is the fifth of F, so there's a union there, the union of root, fifth and minor 7th note I was looking for. That's the best I've been able to figure it out. Maybe I'm making it overly complex but at least I found this connection.
I'm certain this has everything to do with the circle of fifths but I'm not good at learning or remembering things top down if I haven't build up to it from simpler primitives and working through logic, but basically to find the X7 chord, walk back p steps to key of Y where X is Y(5). Make an ordered set of all the note degrees n of Y (do re mi) and then play the odd degree n of Y 4 times (i.e. to the 7th; 4*2-1=7) starting at Y(5), or in symbols:
for z=0 to z=3:
note n = y(tonic) as 0 + 5 + 2*z // returns 5-7-9-11 of F or 1-3-5-7min of C ==> we got our translation
So again, simplified, walking back until you find what C is the fifth of -> F. Then taking the 5-7-9-11 of F (staying in key), is the same as the 1-3-5-7 of perfect 5th (skewed scale of C) or the 1-3-5-min7 of pure C (breaking keys or crossing keys if you look at it from that way, as I did in the beginning)
BTW yes I'm just figuring this out in real time and yes the math notation makes it easier for me to understand. Maybe someone else shares my frame and it helps them. Of course if I'm wrong, correct me and stop the error propagation.
Comment: The confusion is really an issue with terminology: "the relationship between the 5th and minor 7th" should read "the relationship between *scale-degree 5* and the minor 7th," since the dominant seventh is built on scale-degree 5.
Comment: Here's why. The M7 is a M3+m3+M3. The m7 is a m3+M3+m3. How about the other two combinations? (1) M3+m3+m3. This lets you transition from M3+m3+M3 to m3+M3+m3 ... first,  one note changes between M3+m3+M3 and M3+m3+m3 (major7 interval to minor 7), then one note (the third dropping down, changing the chord from major to minor) changes between M3+m3+m3 and m3+M3+m3. In other words the dom7 isn't naturally occurring ...it's a by-design transitional chord built on the 5th because the 5th is harmonically closest to the 1. (Circle of 5ths,,, each key up is a fifth higher, the minimal harmonic diff.)
Comment: @Richard I'm a huge fan of clear language. It's sometimes the only thing that keeps you out of the woods. I'll remember your phrase, the scale-degree 5. So C7 is really F based. F is the power behind the throne setting the tone. I also caught another pattern which is obvious if you think about it or write it down. hopping forward lands you on C(m)7 if you stay in F but taking one step back does as well. And it's the 4th of F (as C was the fifth). I feel like the more angles I hit this the easier to remember.
Answer: You start out from C. You pick the 5th scale degree
G
Then add the major third of that
B
and the perfect fifth
D
and the minor seventh
F
All notes are part of the C-ionian scale. No B♭ anywhere.
Comment: Yes but that's G7, right? You have to step back to get the correct name. Naive (what I was and am) would be to think that starting on C gets you C7. No no no. That was the trap and my error. You have to know how to back step somehow. Maybe there's a heuristic or algorithm or maybe rote memorization. Out of three options- stay on the tonic of the named Dom chort (nope), check out the key of the perfect fifth forward, i.e. G (nope, my second error). Only the third way, backing up to make C the 5th is the way forward. Back is the way forward.
Comment: @gcr what do you mean by "correct name"?
Answer: Let's take key C. So C is I. The dominant of that is G. So the dominant chord is built off the 5th note of C, which is G. So the dominant seventh will be 1-3-5-7, based on the diatonic notes of key C. They're G B D F. Note that the F is the 7th (from G) but isn't a major 7th note (in key G). It doesn't need to be, as we're in key C, not key G. It just happens to be m3 away from its 5th note. As in G B D >(m3)F.
Now, let's look at the chord C7. That's not from key C! It's from key F. That's why it has B♭ in it, and not B♮. C E G B♭. True, C7 does get used a lot in key C, but most times it leads to chord F - no surprise now, I hope. By understanding the circle of fourths/fifths, you'll see a pattern emerge which makes dominants - tonics clear.
Comment: Put another way, a V chord is made up of scale degrees 5-7-2-4 of the home key.
Comment: @Aaron - or even 5-7-9-11 of the home key.
Comment: Oh yeah the famous circle of fifths! Some day I will unlock its secrets. So high level I understand but I want a quicker understand and I decided that you have two options for deriving a dominant chord if you start on C. You can move up five and return the G7. Or you can go back 5 degrees and get the C7. If you want the Dom chord itself, go back. If you want its 5th degree's dom, go forward. I don't know how they work with this in the real world but that's how I model it.
Comment: 5 forward or 4 back, it's the same answer! And really, it's worth *knowing* the circle, bit like times tables, musos need the circle.It's only 12 bits, so not too onerous, and you'll see a couple of patterns repeat within it. You won't regret learning it. Honest.
Comment: In the real world, a song has a key, a major (or relative minor) that will be our static reference point for a certain part of a piece (for standard music). So we can go up from Cmaj (as the I) to find G7 as our 5th, or we can go down from G (as the I) 4 steps to find C7 (note, same as going 5 degrees up from the G, we get to a C7). The pattern is not symmetrical, but in general we would chose one or the other as our key, and for a time in a piece the only relationships we would have to worry about would be the ones relating to one particular starting point.
Answer: You seem to be confused by the fact that "dominant" means two different things here.  Originally, "dominant" meant the fifth degree of the scale.*  Eventually, it came to denote chords built on that pitch (and even the related key based on that pitch).
One of the chords built on the dominant scale degree is derived from the major triad by adding the seventh.  Because the diatonic seventh above the fifth scale degree is a minor seventh, this chord comprises a major third, a perfect fifth, and a minor seventh.  Because this chord came into being as a chord built on the dominant, it came to be called the "dominant seventh."  Eventually, however, this term came to denote the shape of the chord independent of any key, regardless of what scale degree it is built on.
So, the dominant seventh chord of the key of C is G7 (G-B-D-F), but a C dominant seventh chord, C7, is C-E-G-B♭.  The C7 chord is not, as Tim notes, one of the chords of C major, though pieces in C major may "borrow" it from the related key of F major.
In the first instance, "dominant" means "the seventh chord built on C major's dominant scale degree, which is G."  In the second instance, it means "the chord with the shape of a dominant seventh built on the note C," without regard to which key we're in, or even whether we're in a key at all.
At least, that's how classical theory would see it.  But during the 20th century, as jazz and also classical harmony expanded the notion of consonance, the idea that C7 would have to imply movement toward F became weaker and weaker.  For example, in a C blues, you are very likely to hear C7 as the tonic chord.  Still, we retain from traditional theory the name "dominant seventh" to describe its shape even though it no longer has a dominant function.

* Actually, in the middle ages, it meant something subtly different, but with the development of harmonic music it came to denote the fifth degree of the scale.
Answer: Think of it in modes. When you say major scale here, you're actually referring to ionian, scale associated with the first degree. There are 7 degrees in ionian, and each degree has their own scale associated with them, called the modes. That is where you get the notes you will need to build your chords. So the notes of C ionian are C D E F G A B. Think of chord building in terms of formulas and scale degrees, and disregard whether the degree is a minor or major second or third for now. Since the basic chords are made from stacking third, if you want a diad you get C E, if you want a triad you get C E G and if you want a 7 chord you get C E G B.
Now, the since the fifth degree of a scale is the dominant, the dominant degree in c ionian will be G. To find the mode associated with G in the key of C ionian, just build the scale using the notes in C ionian, starting with G. From that, we will have G A B C D E F. This gives us the mixolydian mode. To get a 7 chord, just use the formula 1 3 5 7, and the chord you get is G B D F. Note that you have to use the formula on the mode associated with the scale degree to obtain the correct chord.
So really when you ask why C dominant is the way it is, you're confused because you're using the 1 3 5 7 formula on C ionian. That will give you C E G B, which is a C major 7.  When you want a C dominant chord, the mode associated with that is C mixolydian. The notes of C mixolydian are C D E F G A Bb. So apply the 1 3 5 7 formula and you get C E G Bb, which are the notes of a C dominant chord. So I hope you can understand that the Bb in a C dominant isn't arbitrary.
Answer: I've found a route I use to introduce the idea of the function of a dominant 7th chord to folks who have little or no music theory. Take the dominant 7th of C major as an example: G-B-D-F. Invariably, somebody asks "where does the F come from?" My introductory reply goes like this: human ears love the sound of a dissonant chord leading straight to a consonant chord. If a keyboard is handy, I might play C-C#dim-Dm, then ask how strong is that sound of the harsh diminished leading directly to Dm? Answer: very strong. Then play a perfect cadence G major: G-B-D to C major C-E-G. Ask if that is strong. Answer always is STRONG. Then I'll add the F. Does that sound strong? Answer usually is VERY STRONG. Yes, our ears love the little added dissonance of the b7 leading to the root chord. Often you get a light bulb moment re: our ears perceiving and brain reacting to consonance and dissonance. From there, it seems easier to start talking theory!


How to show remaining time of downloading and total file size in browser?

Question: I have this code:
<code>$file="http://domain/path/file.flv?hash=hashcode";

header('Content-Type: video/x-flv');

header('Content-Disposition: attachment; filename=myvideo.flv' );

readfile($file);
</code>
And when I access download.php it starts downloading, and in the browser shows:
1 KB, 2 KB, ... 1MB, 2MB, ....
What I want to know is how to show the text below in the browser when downloading the file, something like this:
2MB/29MB remaining 5 minutes...
I mean, at the bottom of the browser (where the file is downloading) - Chrome, or in the "Downloads" window - Firefox
I tryed this:
<code>header('Content-Length: ' . filesize($file));
</code>
but it doesn't work.
Comment: Here is the answer I sure that, It will help you.

http://stackoverflow.com/questions/6052208/unable-to-show-download-progress-of-file-from-new-server-worked-on-previous-ser#
Answer: If I understand you right, you want to control the way your browser shows uploading process, unfortunately you can't do it..
You may use an uploading library like http://www.uploadify.com/ to do it, and there you can control the way the upload looks.
Comment: No, that is not what I want. So, I wanna grab the right size of file from an url like: http://domain.com/path/videofile.flv?hash=somehashcode


How to change build machine type with CMake

Question: I am learning how to use CMake,
I am converting a working project from Visual Studio to Cmake and building with NMake. The current project builds for both x64 and x86. My OS is windows 10
My current CMakeLists.txt is very simple:
cmake_minimum_required(VERSION 3.13.0)

project(example CXX)

ADD_DEFINITIONS(-DUNICODE)
ADD_DEFINITIONS(-D_UNICODE)

set(CMAKE_CXX_FLAGS -G"NMake Makefiles")

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(SimManager
    Source/main.cpp
    )

set_target_properties (${PROJECT_NAME} PROPERTIES
    CXX_STANDARD 17
    CXX_STANDARD_REQUIRED TRUE
    CXX_EXTENSIONS FALSE
    )

The commands I'm using to build are:
cmake -G"NMake Makefiles ..
nmake
The error I get is
fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'x86'
I understand the way NMake chooses which compiler to use, x86 or x64, is by opening the appropriate console terminal. I am using Select x64 Native Tools Command Prompt for VS 2017
The command line for the linker that gets executed is:
command "C:\PROGRA~2\MIB055~1\2019\ENTERP~1\VC\Tools\MSVC\1425~1.286\bin\Hostx86\x86\link.exe /nologo @CMakeFiles\example.dir\objects1.rsp /out:SimManager.exe /implib:SimManager.lib /pdb:E:\Projects\example\Debug\example.pdb /version:0.0 /machine:X86 /debug /INCREMENTAL /subsystem:console kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\example.dir/intermediate.manifest CMakeFiles\example.dir/manifest.res" failed (exit code 1112) with the following output: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'x86'

I can see it has /machine:X86 set in it. I am not setting this in CMakeLists.txt. How can I make it use a 64 bit linker?
I tried adding suggested arguments to the cmake call, it did not make a difference
cmake -G"NMake Makefiles" --build build64 --config Release -host_arch=amd64 -arch=amd64 ..
Also tried adding to CMakeLists, same error is still there
set(CMAKE_SYSTEM_PROCESSOR AMD64)
set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "-m64" LINK_FLAGS "-m64")
set(ARCH amd64)

I would prefer to make the changes in the CMakeLists.txt if possible, so I can make the command line calls as show as possible. This project is not intended to build for 32 bit.
Thanks
Comment: see CMAKE_SYSTEM_PROCESSOR and CMAKE_SYSTEM_NAME
Comment: set(CMAKE_SYSTEM_PROCESSOR  AMD64)?
Comment: tried it, still same error
Comment: show all cmake and make log + show cmakecashe
Comment: CMakeCache is here: https://pastebin.com/YXG6SfKu   CMakeLists.txt is in the question above, I had to ommit some lines
Comment: According to the `CMakeCache.txt`, you project is configured exactly for x86. Either "x64 Native Tools Command Prompt for VS 2017" gives you x86 build environment (for unknown reason), or.. you have previously configured your project for x86 and forgot to clear CMakeCache before changing environment.
Comment: Maybe Im mistaking, but CMake doesn't care which command prompt I use, only NMake does, right? CMakeCache is generated before running NMake, so as long as CMakeLists is configured correctly is should generate the right CMakeCache. I delete everythign from the folder every time I run
Comment: It is CMake who fill `CMakeCache.txt`, so it is very concerned about the environment used for configuration. Removing build folder when building in new environment is OK.
Comment: Please check in this [older post](https://stackoverflow.com/questions/41762898/fatal-error-lnk1112-module-machine-type-x64-conflicts-with-target-machine-typ)
Answer: Try adding the following in the CMakeLists.txt:
target_link_options(target PRIVATE /machine:x64)

See documentation.
Or you can edit the CMakeCache.txt and change the following variable:
CMAKE_MODULE_LINKER_FLAGS:STRING=/machine:x64


postfix specify limited relay domain while allowing sasl-auth relay

Question: I'm trying to set up postfix to allow relaying under a limited set of conditions:

The destination domain is one of a pre-defined list
-or-
The client successfully logs in

Here's the relevant bits o' config:
smtpd_sasl_auth_enable=yes
relay_domains=example.com
smtpd_recipient_restrictions=permit_auth_destination,reject_unauth_destination
smtpd_client_restrictions=permit_sasl_authenticated,reject

The problem is that it requires that BOTH restrictions be satisfied, rather than either-or. Which is to say, it only allows relaying if the client is authenticated AND the recipient domain is @example.com.
Instead, I need it to allow relaying if either one of the requirements is satisfied. How do I do this without resorting to running SMTP on two separate ports with different rules?

Note:
The context is an outbound-use-only (bound to 127.0.0.1) MTA on a shared web server which all site owners are allowed to relay mail to one of the "owned" domains (not server-local, though), and for which a limited set of "trusted" site owners are allowed to relay mail without restriction provided they have a valid SMTP login.
Answer: And of course I figure it out 6 minutes after posting the question.
You can put permit_sasl_authenticated in your smtpd_recipient_restrictions setting and remove the smtpd_client_restrictions altogether.
smtpd_sasl_auth_enable=yes
relay_domains=example.com
smtpd_recipient_restrictions=permit_auth_destination,
     permit_sasl_authenticated,reject_unauth_destination

The fact that this option is not documented in http://www.postfix.org/postconf.5.html#smtpd_recipient_restrictions has proved to be a source of not an insignificant amount of frustration in this case.
Comment: Yep. Great documentation and super useful errors in the logs make working with Postfix uber fun.


If $f(z)$ is holomorphic on $D: \{z\mid z \lt 1 \}$, and there are infinite points $z_n \in D$ so that $f(z_n)=0$, is $f(z)=0$ for every $z \in D$?

Question: If $f(z)$ is holomorphic on $D: \{z\mid z \lt 1 \}$, and there are infinite points $z_n \in D$ so that $f(z_n)=0$, is $f(z)=0$ for every $z \in D$?
It reminds me of the identity theorem, but no sure if that's the correct direction.
Any hint will be great. Note: It might be untrue, just need a way to refute it.
Answer: Probably you know that the map $C : z \to \frac{z-i}{z + i}$ send the upperhalf plane $\{(x,y): y>0 \}$ in a 1-1 way onto the unit disc $D$. The function $g(z):=\sin(z-i)$ has infinite zeros in the upperhalf plane. Then $f(z) = (g \circ C^{-1})(z)$ is holomorphic non zero and has infinite zeroes in $D$.
Answer: To give another example, the function $f(z)=\sin \frac{1}{z}$ has an essential singularity at the origin, and infinitely many zeros in any interval of the form $[0,\epsilon]$ for all $\epsilon>0$.
Thus, the shifted function $f(z+1)=\sin \frac{1}{z+1}$ is a valid counter-example.


Count rows/cases in PSPP

Question: I open a .sav file in PSPP (an open-source alternativ to SPSS) with

get file=...sav

Now I would like to see how many rows there exist.
Comment: "I cannot guarantee..." sentence is hard to understand. Give more details that would be in line with SPSS.
Answer: show n in regular old SPSS would do what you want. It doesn't appear to be in the list of commands for PSPP though.
Another possibility would be to compute your own variable based on the casenumber ($casenum), and then print the maximum casenumber. Something like below would do this.
compute #mynumber = $casenum.
freq var #mynumber /format = notable /statistics = maximum.

I think you have to have the variable defined before running a frequency (i.e. I don't think you can do freq var $casenum.). I don't have PSPP around to check, so let me know if this works in that program.
Comment: 1. "show n" does not work in PSPP,
2. Your code works!
3. "freq var $casenum." does not work as you guessed

Count rows/cases in PSPP


Como exibir o estado em um geochart?

Question: Estou a exibir um geochart ao nível de estado. Ao configurar com a região do Brasil funciona, como podem ver abaixo, porém não com o código do estado, por exemplo: BR-SP

google.load('visualization', '1', {
  'packages': ['geochart', 'table']
});
google.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {

  var data = google.visualization.arrayToDataTable([
    ['State', 'Views'],
    ['BR-AL', 300],
    ['BR-SP', 300],
    ['BR-RJ', 400]

  ]);

  var geochart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  var options = {
    region: 'BR',
    resolution: 'provinces',
    width: 800,
    height: 600,
    colorAxis: {
      colors: ['#acb2b9', '#2f3f4f']
    }
  };

  geochart.draw(data, options);

}

A nível de estado:

google.load('visualization', '1', {
  'packages': ['geochart', 'table']
});
google.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {

  var data = google.visualization.arrayToDataTable([
    ['State', 'Views'],
    ['Sao Paulo', 300],
    ['Campinas', 300],

  ]);

  var geochart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  var options = {
    region: 'BR-SP',
    displayMode: 'markers',
    width: 800,
    height: 600,
    colorAxis: {
      colors: ['#acb2b9', '#2f3f4f']
    }
  };

  geochart.draw(data, options);

}

Answer: Amigão, ai está, da forma que você quer, ele usa que quando dá um clique ele muda de State para City e coloca em Markers.
Dê uma olhada no que eu fiz aqui, voce vai conseguir pegar.
Fiz com base no dele, Boa Sorte, Caso não seja isso que queira, comente ai me explicando melhor :D

google.load('visualization', '1', {
      'packages': ['geochart', 'table']
  });
  google.setOnLoadCallback(drawRegionsMap);

  function drawRegionsMap() {
      var data = google.visualization.arrayToDataTable([
      // Results For US States
      // State format must be "BR-**"
      // US represents region, while the ** section represents the individual state
      ['State', 'Views'],
          ['BR-SP', 300],
          ['BR-PE', 300],
          ['BR-AM', 400]

      ]);

      var view = new google.visualization.DataView(data)
      view.setColumns([0, 1])

      var options = {
          region: 'BR',
          resolution: 'provinces',
          width: 556,
          height: 347
      };

      var chart = new google.visualization.GeoChart(
      document.getElementById('chart_div'));
      chart.draw(data, options);

      var geochart = new google.visualization.GeoChart(
      document.getElementById('chart_div'));
      var options = {
          region: 'BR',
          resolution: 'provinces',
          width: 556,
          height: 347,
          colorAxis: {
              colors: ['#acb2b9', '#2f3f4f']
          } // orange to blue
      };
      google.visualization.events.addListener(geochart, 'regionClick', function (eventData) {
          // maybe you want to change the data table here...
          options['region'] = eventData.region;
          options['resolution'] = 'provinces';
          options['displayMode'] = 'markers';

          var data = google.visualization.arrayToDataTable([
          // Add Results for Individual State
          // Format needs to match what is below so that it locates the correct position
          // Additional information can be added to array
          // Uses first value in 2nd column to determine scale for markers
          // Use AJAX to load this on regionClick
          ['City', 'Views'],
              ['Recife, PE', 200],
              ['Manaus, AM', 300],
              ['Santos, SP', 400],
              ['Campinas, SP', 400],

          ]);

          geochart.draw(data, options);
          var table = new google.visualization.Table(document.getElementById('table'));
          table.draw(data, null);

      });
      geochart.draw(data, options);

  };

Comment: amigão dei uma pesquisada rápida aqui no api e no grupo do google charts, e diz assim:
"Not all countries have province-level maps in the GeoCharts, and it looks like Brazil is one of the ones that doesn't have them.  In order to zoom in on the region, you would have to use Google Maps".

Básicamente o brasil não está com esse tipo de zoom, pode testar no region, coloque: region: 'BR-SP', ele da erro.
Mas se colocar por ex: region: 'US-AL' ele vai dar o zoom.

Infelizmente oque resta a ser feito é ou usar o google maps ou simplesmente usar markers.

O google infelizmente não atualizou para nós
Comment: E o "Zoom" a nível de estado? O que preciso é que quando clicar em um, ele dê zoom no estado e apareça os marcadores.
Comment: E pelo visto está assim desde 2012.

Fonte: https://groups.google.com/forum/#!topic/google-visualization-api/G4MObm_ztXY

Para usar google maps: https://developers.google.com/chart/interactive/docs/gallery/map
Answer:

google.load('visualization', '1', {
  'packages': ['geochart', 'table']
});
google.setOnLoadCallback(drawRegionsMap);

function drawRegionsMap() {

  var data = google.visualization.arrayToDataTable([
    ['State', 'Views'],
    ['Sao Paulo', 300],
    ['Campinas', 300],

  ]);

  var geochart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  var options = {
        region: 'BR',
        displayMode: 'markers',
        width: 800,
        height: 600,
        colorAxis: {
            colors: ['#acb2b9', '#2f3f4f']
        }
    };

  geochart.draw(data, options);

}

Comment: Andrey, o que estou tentando fazer é que mostre apenas o estado no chart. Um exemplo é quando você clica em um estado do US nesse link: https://leachcreative.com/demos/us-geochart/

Como exibir o estado em um geochart?


Should data for both sub-groups be transformed when checking for sub-group differences when only one is non-normal?

Question: Tabachnick and Fidell (2012) recommend examining the normality (outliers, skewness, kurtosis) of a variable separately/by group/sub-group if one is planning to do a group-based analysis (e.g., t-test, ANOVA).
If one finds that a particular variable is normal for one group (e.g., older adults) but non-normal for another group (e.g., significant skewness and/or kurtosis for younger adults) should both groups data be transformed to (a) address the skewness and/or kurtosis of the younger adults group and (b) allow the groups to be compared in the t-test/ANOVA?
Presumably only transforming one of these groups would lead to a meaningless significant difference between the groups because, of course, the mean of the square root group will be different than the mean of the raw data group.
Comment: Could you tell us a little about how you are assessing normality? Perhaps the situation is not as complicated as it seems. It is often the case that a common transformation will symmetrize the distributions in the worst groups without badly damaging the symmetries in the other groups. When such a common transformation cannot be found, heed the recommendation at the end of oce's answer: since you have thereby discovered an interesting difference among groups, investigate it!
Comment: I do not understand how a test to compare skewness or kurtosis across groups would be directly relevant to this question.
Comment: Thanks for your comments oce and whuber! I had asked the question for a friend who found significant skewness and kurtosis (S and K divided by appropriate standard error was significant at p<.001) for questionnaire scale and sub-scale totals differed between older adults and younger adults in a large sample of several hundred people. Therefore the power to find 'significant' non-normality (due to the diminished standard error) is large. Tabachnick and Fidell suggest that with large samples and visually not-too non-normal distributions should be ok, and this is what my friend decided to do.
Comment: Sorry whuber, my comment had accidentally posted before I finished writing it (though your comment may still hold for my completed comment that I re-posted). The tests just examined if the data was significantly kurtotic or skewed within a group - and did not compare if the groups differed from each other significantly. Just in several cases, the older adults data would be significantly skewed and/or kurtotic for a particular scale/sub-scale while the younger adults would not be (or vice versa). maybe this crude look at differences in normality between the groups is not the best way to go.
Comment: Thank you for your patient clarification, Patrick.  It would be well to distinguish between a *significant* difference and an *important* one.  As discussed extensively elsewhere on this site, it is very easy to identify tiny, unimportant deviations from normality in medium to large datasets.  What you should focus on is *how* and *by how much* the groups depart from appearing normal.
Answer: (This should be a comment but I can't comment so put as an answer)
I agree you should transform both group as you have suggested.I don't know what you variable is, but normally, if one group of data is normal, and the other is not, this sounds a bit worrying if the data collection procedure is okay. It may be the sample were not random enough, or it could be data collection method issue, like ceiling effect (say if you are testing how many word one can remember out of 7, and most young ppl can remember all, so this could cause the non-normal data)  So before you transform data, I would suggest you to look into why one group is normal while the other is not.
Comment: Thanks oce, I have passed on your suggestions to my friend! The data was not random - it was a convenience sample of older and younger adults - and that may be partially responsible for the discrepancy. But, as I noted above in my comments to whuber, after exploring whether common transformations could help the data (they tended to make things worse :/) my friend decided to leave the data untransformed since there was a large sample (several hundred respondents) and the skewness and kurtosis tended to be not tooooooo bad (maybe z scores of 3.5 to 9 at the worst). Hopefully this is defensible.


Prove that $\forall x \in \mathbb{R}:f(x + 2\pi) = f(x)$

Question: I'm trying to prove that if  $f : \mathbb{R} \rightarrow \mathbb{R} \phantom{2}$ is a function that  verifies :
$\exists\, K \in \mathbb{R^+}, \phantom{1}\forall\, x,y \in \mathbb{R}: \lvert f(y)-f(x) \rvert \le K\lvert \cos y - \cos x \rvert$
then $\forall x \in \mathbb{R}:f(x + 2\pi) = f(x)$
Maybe it could be useful the fact that I recently proved that f is a Lipschitz function since  by mean value theorem
$\dfrac{|\cos y - \cos x|}{|y-x|}\le 1 \implies |\cos y - \cos x|\le|x-y|$ $\forall x,y \in \mathbb{R} $ as $\cos$ is differentiable over all of $\mathbb R$.
So
$$\exists\, K \in \mathbb{R^+}, \forall\, x,y \in \mathbb{R}: |f(y)-f(x)| \le K|\cos y - \cos x|\le K|x-y|$$
The proof seems easy but I'm not sure how can I prove it, any suggestions?
Comment: Wouldn't taking $y = x+2\pi$ give this to you immediately?
Answer: Hint: Substitute $y= x+2\pi$ in the given inequality.
Answer: Put $y=x+2\pi.$ We get $|f(x+2\pi)-f(x)|\leq K|\cos(x+2\pi)-\cos x|=0$ as $\cos$ is $2\pi$-periodic.


Local present of $\mathcal{L}$-geodesic

Question:

$X=\dot{\gamma}(\tau)$. I want to locally present the $\mathcal{L}$-geodesic , let $X=X^i e_i$, $\{e_i\}$ is the basis in a local coordinate. So,
$$
\nabla_XX=X^iX^j_ie_j +X^iX^j\Gamma_{ij}^ke_k   \\
\nabla R =g^{ij}\partial_iR e_i           \\
\frac{1}{2\tau}X=\frac{1}{2\tau}X^i e_i    \\
Ric(X,\cdot)=X^iR_{ij}dx^j
$$
As I know the 3.2.1 is a tensor equation,  but the $Ric(X,\cdot)$ is not a vector, how to understand it ?
Answer: In a local coordinate, the 3.2.1 can be presented as
$$
u_{\theta\theta}^k+u_\theta^iu_\theta^j\Gamma_{ij}^k-\frac{1}{2}g^{jk}R_{,j}
+\frac{u_\theta^k}{2\tau}+u_\theta^iR_{ij}g^{jk}=0
$$
In fact ,$2Ric(X,\cdot)$ should be $2g^{-1}Ric(X,\cdot)$. I use $\theta$ as the parameter of curve i.e. $\theta=\tau$.

Local present of $\mathcal{L}$-geodesic


error ASPPARSE: Could not load type error with msbuild on teamcity

Question: I'm receiving error ASPPARSE: Could not load type error when building a project on team city.
The file it is failing on is a folder which is not referenced in the project but is just there for source control.
C:\TC\Agents\3\work\fd3ea8938fa12582>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_compiler -v /DummyDeployWeb -p C:\TC\Agents\3\work\fd3ea8938fa12582\Project C:\TC\Agents\3\work\fd3ea8938fa12582\PreCompiled\Project-fixednames -u
ERROR
/DummyDeployWeb/common/files/somefilename.ascx(1): error ASPPARSE: Could not load type 'Project.somefilename'
How can I get the project to build and ignore these folders that arent referenced?
Answer: The ASP.NET compiler knows nothing about project files, it simply processes the entire contents of the folder you point it at.
There is no way to tell the compiler to exclude specific files and so if this is a requirement for you then one solution would be to move these files out of the folder before you run the compiler and then copy them into the deployment folder after the compilation is complete.


convergence of series of function in distributions

Question: I'm trying to prove that:
$$\lim_{n\to\infty} t_n(x) = -\delta'(x)$$
where
$$t_n(x) = \begin{cases}-n^2, & 0\leq x < \frac1n\\ n^2, & -\frac1n< x < 0\end{cases}$$
Help will be appreciated!
Comment: What have you tried to solve this problem? What definition of $\delta'(x)$ are you using?
Comment: I tried to use the definition of convergence of series of function in distributions
Answer: What is nice with the distributions is that if $f_n \to \delta$ (in the sense of distributions) then $f_n' \to \delta'$ (where $f_n'$ is the distributional derivative, which is the usual derivative if $f_n$ is differentiable).
So integrate $t_n$ to obtain $f_n(x) = -\int_{-1}^x t_n(y)dy$ and show that $f_n \to \delta$ in the sense of distributions, ie that for any $\varphi \in C^\infty_c $ :
$$\lim_{n \to \infty } \int_{-\infty}^\infty \varphi(x) f_n(x)dx = \varphi(0)$$
Comment: Why is the lower boundary of the integral -1? thank you!
Comment: @user2600366 (compute $f_n(x) = \int_{-1}^x t_n(y)dy$) it is to make the integration constant such that $f_n$ is compactly supported
Comment: @user2600366 are you stuck somewhere ?


How can I implement auto search on multiple fields using completion sugesstor, and is there a way to auto map multiple field value to completion field

Question: I have been struggling to find a way to implement elastic search auto complete.
My requirement is like this, In my index I have fields a,b,c,d
I want to show the top 5 search suggestion in the order
(a,b,c)
d
I am using Nest 7.17,
I tried using multi match query, term suggest but none of them work as I want
So I read about completion suggestion and how I can add weight to the input but currently I am struggling with 2 things

I want to have a completion field which have multiple field value in it
I am trying to find a way to auto add it in index
Answer: Question 1: I want to have a completion field which have multiple field value in
it?
Answer: You can assign multiple values as array
field = [ "Alphabet Inc", "Google", "Youtube", "Playstore"]
Question 2: I am trying to find a way to auto add it in index?
Answer: There is only one weight field to increase relevance/score. You need to create a function, either you need to create a formula for example a, b, c, d.
<code>if a:
  weight = 4
if b:
  weight = 3
if c:
  weight = 2
if d:
  weight = 1
</code>
This article might be helpful for you.
https://taranjeet.medium.com/elasticsearch-using-completion-suggester-to-build-autocomplete-e9c120cf6d87


dispatching commands sequentially on file save? Coffee init

Question: The code :
atom.workspace.observeTextEditors (editor) ->
  editor.onDidSave ->
    view = atom.views.getView(atom.workspace.getActiveTextEditor())
    atom.commands.dispatch(view, 'platformio-ide-terminal:insert-custom-text-1')
    .then () -> atom.commands.dispatch(view, 'platformio-ide-terminal:insert-custom-text-2')

Why doesn't atom allow me to sequentially execute commands from different packages in my init file like this?
Answer: It's hard to say why it isn't working with that little information provided

does dispatching any of those commands work (e.g. in the console)?
is it the chaining that isn't working?
are there any errors in the console?
did you restart Atom after updating the init file?

I've refactored your code to use ES6, since I prefer async/await over "thenable" syntax. In order to use it, rename init.coffee to init.js:
atom.workspace.observeTextEditors(editor => {
  return editor.onDidSave(async () => {
    const view = atom.views.getView(atom.workspace.getActiveTextEditor());

    await atom.commands.dispatch(view, 'platformio-ide-terminal:insert-custom-text-1');
    await atom.commands.dispatch(view, 'platformio-ide-terminal:insert-custom-text-2');
  });
});

Take note that I tested the snippet using commands of which I'm sure that they are available. However, I set them back to those from your example (again: make sure they work!)


GridLayout doesn't fill the screen

Question: I'm trying to use Gridlayout. I want my grid's buttons to fill the screen but I have a problem doing that. I notice that the layout itself fill the screen but his children are not filling the layout. This is the output:
https://i.stack.imgur.com/XoKH8.png
I searched a lot on the internet but most of the answers are offering to replace the GridLayout to LinearLayout or RelativeLayout But I have to stay with GridLayout.
Also I dont want to give the buttons specific size but rather stay with the structure in the linked picture.
Here is my code:
    <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0.5dp"
android:columnCount="4"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:rowCount="5"
tools:context=".Level1" >

<Button
    android:layout_width="0dp"
    android:layout_column="0"
    android:layout_row="0"
    android:text="0" />

<Button
    android:id="@+id/b_1"
    android:layout_column="1"
    android:layout_gravity="fill_horizontal"
    android:layout_row="0"
    android:text="1" />

<Button
    android:id="@+id/b_2"
    android:layout_column="2"
    android:layout_gravity="fill"
    android:layout_row="0"
    android:layout_rowSpan="3"
    android:text="2" />

<Button
    android:id="@+id/b_3"
    android:layout_column="3"
    android:layout_row="0"
    android:text="3" />

<Button
    android:layout_width="0dp"
    android:layout_column="0"
    android:layout_row="1"
    android:text="0" />

<Button
    android:id="@+id/b_4"
    android:layout_column="1"
    android:layout_gravity="fill_vertical"
    android:layout_row="1"
    android:layout_rowSpan="3"
    android:text="4" />

<Button
    android:id="@+id/b_6"
    android:layout_column="3"
    android:layout_gravity="fill_vertical"
    android:layout_row="1"
    android:layout_rowSpan="3"
    android:text="6" />

<Button
    android:layout_width="0dp"
    android:layout_column="0"
    android:layout_row="2"
    android:text="0" />

<Button
    android:id="@+id/b_5"
    android:layout_column="2"
    android:layout_row="3"
    android:text="5" />

<Button
    android:layout_width="0dp"
    android:layout_column="0"
    android:layout_row="3"
    android:text="0" />

<Button
    android:layout_height="0dp"
    android:layout_column="0"
    android:layout_columnSpan="4"
    android:layout_row="4"
    android:text="0" />

</GridLayout>

Answer: Try this way,hope this will help you to solve your problem.
GridLayout : "GridLayout does not provide support for the principle of weight, as defined in weight. In general, it is not therefore possible to configure a GridLayout to distribute excess space in non-trivial proportions between multiple rows or columns ... For complete control over excess space distribution in a row or column; use a LinearLayout subview to hold the components in the associated cell group."
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <Button
            android:layout_width="match_parent"
            android:layout_weight="0.20"
            android:layout_height="0dp"
            android:text="1" />

        <Button
            android:layout_width="match_parent"
            android:layout_weight="0.80"
            android:layout_height="0dp"
            android:text="4" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <Button
            android:layout_width="match_parent"
            android:layout_weight="0.80"
            android:layout_height="0dp"
            android:text="2" />

        <Button
            android:layout_width="match_parent"
            android:layout_weight="0.20"
            android:layout_height="0dp"
            android:text="5" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <Button
            android:layout_width="match_parent"
            android:layout_weight="0.20"
            android:layout_height="0dp"
            android:text="3" />

        <Button
            android:layout_width="match_parent"
            android:layout_weight="0.80"
            android:layout_height="0dp"
            android:text="6" />
    </LinearLayout>
</LinearLayout>

Comment: First of all thank you very much for your efforts, I really appreciate it.But unfortunately like I said I have to use the GridLayout /:
Answer: Based on previous answer by @Haresh Chhelana, it worked like so just sharing my solution:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_1">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_weight="0.50"
            android:layout_height="0dp"
            android:src="@drawable/bt_elsa" />

        <ImageView
            android:layout_width="match_parent"
            android:layout_weight="0.50"
            android:layout_height="0dp"
            android:src="@drawable/bt_daniel" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_weight="0.50"
            android:layout_height="0dp"
            android:src="@drawable/bt_anna" />

        <ImageView
            android:layout_width="match_parent"
            android:layout_weight="0.50"
            android:layout_height="0dp"
            android:src="@drawable/bt_elmo" />

    </LinearLayout>
</LinearLayout>

sample
source: https://github.com/eduardocerqueira/sing

GridLayout doesn't fill the screen


Is there a way to send email using port 465 only?

Question: I'm trying to send email via port 465 since my ISP has blocked the port 25.
openssl s_client -crlf -connect example.com:465
EHLO example.com
AUTH LOGIN sdgfsdgfdgdfg
dfgdfgdf
mail from: email@example.com
rcpt to: firstname.lastname@example.com
data
From: Karmo <email@example.com>
To: Karmo <email@example.com>
Subject: Email from Postfix

Hi!
.

quit

But according to syslog, it still tries to connect to GMail using port 25:
Jul 29 21:58:26 vagrant postfix/smtp[30536]: connect to alt1.gmail-smtp-in.l.google.com[2a00:1450:4010:c04::1a]:25: Network is unreachable

Is there a way to send an email to GMail or any external server using port 465 only? It has same result when I run it with sudo.
Answer: If you want to test if gmail smtp port 465 is reachable from your network, just type in a telnet alt1.gmail-smtp-in.l.google.com 465 command. If you don't get an error message back, it is reachable.
There is a possible solution, that you could set up an outgoing mail proxy on another port (f.e. port 24) on some of your servers, if you have, although I don't think it worked in your place (probably you want to use gmail exactly for the same purpose).
The openssl command, which you are calling, is only a tcp port connector. It is practically a telnet client, the only difference that it encrypts data. It hasn't anything to do to your mail logs, even if you are connecting your own postfix with that.
I think, you should set up your postfix to use the gmail port 465 as an outgoing mail server. This can be done by setting the default transport to the smtps:alt1.gmail-smtp-in.l.google.com:465 or some similar.


Set cookies from html form

Question: I try to set cookies from my html form wit onsubmit event. But console return "Uncaught ReferenceError: setCookies is not defined"
This is a piece of my code:
<form action="page.html" method="POST" onsubmit=" return setCookies(this)" id="myFormId">
      <input name='user' placeholder='user'>

      <input name='password' type='password' placeholder='password'>

      <button type='submit'>Try</button>
    </form>

HWETEYT

I try make my function as a global but result the same.
Answer: Since you have added the src attribute to the script tag, the code written inside is ignored. Thus you have to split the script as two scripts;

Set cookies from html form


How find this limits with hardly form?

Question:
show that:
$$\lim_{n\to\infty}n\left[\left(\dfrac{1}{\pi}\left(\sin{\left(\dfrac{\pi}{\sqrt{n^2+1}}\right)}+
\sin{\left(\dfrac{\pi}{\sqrt{n^2+2}}\right)}+\cdots+\sin{\left(\dfrac{\pi}{\sqrt{n^2+n}}\right)}
\right)\right)^n-\dfrac{1}{\sqrt[4]{e}}\right]=-\dfrac{1}{\sqrt[4]{e}}\left(\dfrac{31}{96}+\dfrac{\pi^2}{6}\right)$$

I only solve this :$$\lim_{n\to\infty}\left(\dfrac{1}{\pi}\sum_{i=1}^{n}\sin{\left(\dfrac{\pi}{\sqrt{n^2+i}}\right)}\right)^n=\dfrac{1}{\sqrt[4]{e}}\tag{1}$$
use
$$\sin{x}\approx x,\Longrightarrow \dfrac{1}{\pi}\sin{(\dfrac{\pi}{\sqrt{n^2+i}})}=\dfrac{1}{\sqrt{n^2+i}}+o(\dfrac{1}{\sqrt{n^2+i}})\to \dfrac{1}{n}\left(1+\dfrac{i}{n^2}\right)^{-\frac{1}{2}},n\to\infty$$
and note
$$(1+x)^{-1/2}=1-\dfrac{1}{2}x+o(x)$$
so
$$\lim_{n\to\infty}\left(\dfrac{1}{\pi}\sum_{i=1}^{n}\sin{\left(\dfrac{\pi}{\sqrt{n^2+i}}\right)}\right)^n=\lim_{n\to\infty}\left(\dfrac{1}{n}\sum_{i=1}^{n}\left(1-\dfrac{i}{2n^2}+o(i/n^2)\right)\right)^n=e^{-\frac{1}{4}}$$
But I can't solve my problem,Thank you
Answer: The binomial theorem says
$$
\begin{align}
\left(1+\frac{k}{n^2}\right)^{-1/2}
&=1-\frac12\frac{k}{n^2}+\frac38\frac{k^2}{n^4}+O\left(\frac{k^3}{n^6}\right)\\
\left(1+\frac{k}{n^2}\right)^{-3/2}
&=1+O\left(\frac{k}{n^2}\right)
\end{align}
$$
We can use the Taylor series for $\sin(x)$ to get
$$
\begin{align}
\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)
&=\frac\pi{n}\left(1+\frac{k}{n^2}\right)^{-1/2}
-\frac16\frac{\pi^3}{n^3}\left(1+\frac{k}{n^2}\right)^{-3/2}
+O\left(\frac1{n^5}\right)\\
&=\pi\frac1n-\frac\pi2\frac{k}{n^3}+\frac{3\pi}8\frac{k^2}{n^5}+O\left(\frac{k^3}{n^7}\right)\\
&-\frac{\pi^3}6\frac1{n^3}+O\left(\frac{k}{n^5}\right)\\
&+O\left(\frac1{n^5}\right)
\end{align}
$$
Sum to get
$$
\begin{align}
\sum_{k=1}^n\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)
&=\pi\frac{n}n-\frac\pi4\frac{n^2+n}{n^3}+\frac\pi{16}\frac{2n^3+3n^2+n}{n^5}+O\left(\frac1{n^3}\right)\\
&-\frac{\pi^3}6\frac{n}{n^3}+O\left(\frac1{n^3}\right)\\
&+O\left(\frac1{n^4}\right)\\
&=\pi-\frac\pi4\frac1n-\left(\frac\pi8+\frac{\pi^3}6\right)\frac1{n^2}+O\left(\frac1{n^3}\right)
\end{align}
$$
Divide by $\pi$ and use the power series for $\log(1+x)$ and $e^x$
$$
\begin{align}
\log\left(\frac1\pi\sum_{k=1}^n\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)\right)
&=-\frac14\frac1n-\left(\frac18+\frac{\pi^2}6\right)\frac1{n^2}+O\left(\frac1{n^3}\right)\\
&-\frac1{32}\frac1{n^2}+O\left(\frac1{n^3}\right)\\
&+O\left(\frac1{n^3}\right)\\
&=-\frac14\frac1n-\left(\frac5{32}+\frac{\pi^2}6\right)\frac1{n^2}+O\left(\frac1{n^3}\right)\\
n\log\left(\frac1\pi\sum_{k=1}^n\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)\right)
&=-\frac14-\left(\frac5{32}+\frac{\pi^2}6\right)\frac1n+O\left(\frac1{n^2}\right)\\
\left(\frac1\pi\sum_{k=1}^n\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)\right)^n
&=e^{-1/4}\left(1-\left(\frac5{32}+\frac{\pi^2}6\right)\frac1n+O\left(\frac1{n^2}\right)\right)\\
n\left[\left(\frac1\pi\sum_{k=1}^n\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)\right)^n-e^{-1/4}\right]
&=e^{-1/4}\left(-\left(\frac5{32}+\frac{\pi^2}6\right)+O\left(\frac1n\right)\right)\\
&\to-\left(\frac5{32}+\frac{\pi^2}6\right)e^{-1/4}
\end{align}
$$

My answer agrees with Paramanand Singh's. As a check, with $n=1000000$
$$
\begin{align}
n\left[\left(\frac1\pi\sum_{k=1}^n\sin\left(\frac{\pi}{\sqrt{n^2+k}}\right)\right)^n-e^{-1/4}\right]&=-1.4027616010762190386\\
-\left(\frac5{32}+\frac{\pi^2}6\right)e^{-1/4}&=-1.4027635617171364019\\
-\left(\frac{31}{96}+\frac{\pi^2}6\right)e^{-1/4}&=-1.5325636922290372132
\end{align}
$$
It looks as if the question is in error.
Comment: Thanks robjohn for helping me out. After much effort I couldn't find an issue in my calculation. Your calculation is much more detailed and also indicates the error terms properly. +1
Answer: You seem to be on the right track and I guess we can try to get more reasonable estimates using further terms of the expansion. First we need to use $\sin x \approx x - \dfrac{x^{3}}{6}$ to get $$\begin{aligned}\frac{1}{\pi}\sin\left(\frac{\pi}{\sqrt{n^{2} + i}}\right) &\approx  \frac{1}{n}\left(1 + \frac{i}{n^{2}}\right)^{-1/2} - \frac{\pi^{2}}{6n^{3}}\left(1 + \frac{i}{n^{2}}\right)^{-3/2}\\
&\approx \frac{1}{n}\left(1 - \frac{i}{2n^{2}} + \frac{3i^{2}}{8n^{4}}\right) - \frac{\pi^{2}}{6n^{3}}\left(1 - \frac{3i}{2n^{2}} + \frac{15i^{2}}{8n^{4}}\right)\\
&\approx \frac{1}{n}\left(1 - \frac{3i + \pi^{2}}{6n^{2}} + \frac{9i^{2} + 6i\pi^{2}}{24n^{4}}\right)\end{aligned}$$ and then summing from $i = 1$ to $i = n$ we get $$\begin{aligned}\sum_{i = 1}^{n}\frac{1}{\pi}\sin\left(\frac{\pi}{\sqrt{n^{2} + i}}\right) &\approx \frac{1}{n}\left(n - \dfrac{\dfrac{3n(n + 1)}{2} + n\pi^{2}}{6n^{2}} + \dfrac{\dfrac{3n(n + 1)(2n + 1)}{2} + 3n(n + 1)\pi^{2}}{24n^{4}}\right)\\
&= \left(1 - \frac{3(n + 1) + 2\pi^{2}}{12n^{2}} + \frac{(n + 1)(2n + 1) + 2(n + 1)\pi^{2}}{16n^{4}}\right)\\
&\approx \left(1 - \frac{1}{4n} - \frac{2\pi^{2} + 3}{12n^{2}} + \frac{1}{8n^{2}}\right)\\
&= \left(1 - \frac{1}{4n} - \frac{4\pi^{2} + 3}{24n^{2}}\right)\\\end{aligned}$$ and therefore using logs we get $$\begin{aligned}\left(\sum_{i = 1}^{n}\frac{1}{\pi}\sin\left(\frac{\pi}{\sqrt{n^{2} + i}}\right)\right)^{n} &\approx \exp\left(n\log\left(1 - \frac{1}{4n} - \frac{4\pi^{2} + 3}{24n^{2}}\right)\right)\\
&\approx\exp\left(-n\left(\frac{1}{4n} + \frac{\pi^{2}}{6n^{2}} + \frac{5}{32n^{2}}\right)\right)\\
&= \exp\left(-\frac{1}{4} - \frac{\pi^{2}}{6n} - \frac{5}{32n}\right)\\ \end{aligned}$$ We can now see that the desired limit is equal $$\begin{aligned}L &= \lim_{n \to\infty}n\left(\exp\left(-\frac{1}{4} - \frac{\pi^{2}}{6n} - \frac{5}{32n}\right) - \exp(-1/4)\right)\\
&= e^{-1/4}\lim_{n \to\infty}n\left(\exp\left(- \frac{\pi^{2}}{6n} - \frac{5}{32n}\right) - 1\right) = -\frac{1}{\sqrt[4]{e}}\left(\frac{\pi^{2}}{6} + \frac{5}{32}\right)\end{aligned}$$ There might be some calculation mistake in above or there is some typo in the question.
Comment: Where are all the necessary controls on the terms you neglect?
Comment: We cannot know--unless one keeps track rigorously of the terms neglected, which is not done at present. This is my point since the very first comment.
Comment: @Did: from the form of the limit expression it is clear that we need to consider the terms up to the order of $1/n^{2}$ and the argument can be easily justified by writing $o(1/n^{2})$ for the terms neglected. When raising to power $n$ this leads to terms up to order of $1/n$ and thats what we need in the last step.
Comment: No. For example, in the first expansion of the sines, you are keeping terms of order $1/n^5$ hence using $\sin(x)\approx x-x^3/6$ with $x$ of order $1/n$ is not sufficient.
Comment: @Did: even if I use $\sin x=x-(x^3/6)+(x^5/120)$ I will get a term like $\pi^{4}/120n^{5}$ and it will not contribute to any term of order $1/n$ in final expression dealing with $\exp$. In fact the term $i \pi^{2}/4n^{5}$ which I have considered in my calculation does not contribute anything in the final expression for $\exp$.
Comment: Then why mention it? The trouble comes from a non rigorous use of the symbol $\approx$, which leaves open the door for all sorts of forgotten terms.
Comment: @Did: I think your main concern is regarding the use of $\approx$. It would have been better had I written $= \cdots + o(1/n^{k})$ for some suitable $k$. By the way I am unable to find any missing terms which may have impact on the final result.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18498/discussion-between-paramanand-singh-and-did).
Comment: @ParamanandSingh: Luckily, no terms contributing significantly to the result were missed. However, Did is correct: to be sure, one must keep track of the error terms.

How find this limits with hardly form?


Árvore de categorias no MongoDB, como modelar?

Question: Boa noite, pessoal.
Como o MongoDB muda muita nossa maneira de modelar um banco da dados, me deparei com uma dúvida que pode ser até meio besta.
Estou fazendo uma Restful API utilizando o Lumen e o MongoDB como base de dados,e quero criar uma coleção de categorias de produtos, e estas categorias tem suas respectivas categorias mães e filhas. Como no exemplo abaixo:

categoria mãe

categoria filha
categoria filha

categoria filha
categoria filha

categoria filha

categoria mãe

categoria filha
categoria filha
categoria filha

Como seria a maneira mais correta de esquematizar isso numa só coleção?
Ou a forma mais correta seria, de alguma maneira, colocar estas categorias dentro da coleção de produtos?
Comment: O mais correto depende do modelo de negócios. Um tipo de estrutura X pode não ser adequada para um modelo de negócios X, mas pode ser a melhor opção para um modelo Y. A questão da forma como está, torna-se ampla e suscetível a respostas baseadas em opiniões.
Comment: Apenas para ajudar, pesquise sobre "adjacency" e "nested". Exemplo nesse artigo: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
Comment: A partir do link que você me sugeriu consegui reformular minha pergunta ao google, e não pra minha supresa, a resposta estava na própria documentação do MongoDB. Postarei como resposta para esta pergunta para ajudar os demais. Valeu.
Answer: Na própria documentação do MongoDB existem 5 padrões que você pode seguir dependendo de sua aplicação ou gosto.
Considerando a seguinte imagem, vou citar dois padrões que estão disponíveis na documentação do Mongo:

Child Reference:
db.categories.insert( { _id: "MongoDB", children: [] } )
db.categories.insert( { _id: "dbm", children: [] } )
db.categories.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ] } )
db.categories.insert( { _id: "Languages", children: [] } )
db.categories.insert( { _id: "Programming", children: [ "Databases", "Languages" ] } )
db.categories.insert( { _id: "Books", children: [ "Programming" ] } )

E o Parent Reference:
db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
db.categories.insert( { _id: "dbm", parent: "Databases" } )
db.categories.insert( { _id: "Databases", parent: "Programming" } )
db.categories.insert( { _id: "Languages", parent: "Programming" } )
db.categories.insert( { _id: "Programming", parent: "Books" } )
db.categories.insert( { _id: "Books", parent: null } )

Fonte: http://docs.mongodb.org/manual/tutorial/model-tree-structures/
Comment: Muito obrigado pela sua resposta, também irei estudar sobre como bancos não relacionais funcionam e sua resposta foi muito útil, a imagem que você postou era o que imaginava. +1


Why a non-field ring cannot be algebraically closed?

Question: For instance, it seems that any polynomial in tessarines/bicomplex numbers has roots in tessarines.
So, they seem to be more algebraically closed despite being not a field.
On the other hand, split-complex numbers are not algebraically closed, and their algebraic closure seems to be tessarines.
So, why only a field can be algebraically closed?
UPDATE
Is there a notion of rings that are algebraically closed except for the polynomials with coefficients that are divisors of zero?
Answer: Take a non invertible element $a$, and consider for example the polynomial $ P (X) = aX - e$ where e is the unit element
Comment: @Anixx I think you need to clarify your question (by editing the question), rather than shifting the goalposts in the comments.
Comment: Thanks. But is there a notion of rings that are algebraically closed except for the polynomials with coefficients that are divisors of zero?
Comment: @Anixx That seems to be a completely different question. Note that the coefficient $a$ in the polynomial $P(X)$ in this answer is not necessarily a zero-divisor, it's just non-invertible.
Comment: Yes, but algebras that have non-zero-divisor non-invertible elements are intuitively not closed anyway.
Comment: What about division algebras that are not fields (e.g. quaternions)?
Comment: https://math.stackexchange.com/questions/1071874/is-there-an-algebraic-closure-for-the-quaternions
Comment: @AlexKruckman edited
Comment: @saulspatz thanks, I think that part is answered by the link.
Answer: For a non-commutative case, we would have to consider non-commutative polynomials?  With indeterminate $X$, for degree $1$ they would look like
$$
a + bXc + dXe + fXg = 0
$$
and quadratics even worse with terms like $aXbXc$.


Trigonometry Inequality

Question: This is the first time I'm posting here. If you can also tell me how to format this like a pro, I'll be very grateful.
1st question:
Prove the following inequality:
$$0^{\circ} < a, b, c < 180^{\circ}$$
$$\sin a \times \sin b \times \sin c \le \sin\left(\frac{a+b}{2}\right) \times \sin\left(\frac{a+c}{2}\right) \times \sin\left(\frac{a+b}{2}\right)$$
2nd question:
Prove the following inequality:
$$a + b + c = 90^{\circ}$$
$$\sin a \times \sin b \times \sin c  \le \frac{1}{8}$$
Comment: Welcome to math.SE. For some basic information about writing math at this site see e.g. [here](http://meta.math.stackexchange.com/questions/5020/), [here](http://meta.stackexchange.com/a/70559/155238), [here](http://meta.math.stackexchange.com/questions/1773/) and [here](http://math.stackexchange.com/editing-help#latex).
Comment: Is the question how to _prove_ these inequalities?  If so, I'd say that explicitly.
Comment: Yes, that is the question. Thank you.
Answer: First inequality
By Jensen we have
$$\sin\left(\frac{a+b}{2}\right) \geq \frac{\sin(a)+\sin(b)}{2}$$
By AM-GM we get
$$\frac{\sin(a)+\sin(b)}{2} \geq \sqrt{ \sin(a) \sin(b)}$$
Combining we get
$$\sqrt{\sin(a) \sin(b) } \leq \sin\left(\frac{a+b}{2}\right)$$
Similarly you get
$$\sqrt{\sin(a) \sin(c) } \leq \sin\left(\frac{a+c}{2}\right)$$
$$\sqrt{\sin(b) \sin(c) } \leq \sin\left(\frac{b+c}{2}\right)$$
Multiplying them you get the desired inequality.
Second Inequality:
By AM-GM:
$$\sin a \times \sin b \times \sin c  \le  \left( \frac{\sin(a)+\sin(b)+\sin(c)}{3} \right)^3$$
Now, by Jensen:
$$\frac{\sin(a)+\sin(b)+\sin(c)}{3} \leq \sin(\frac{a+b+c}{3})=\frac{1}{2}$$
Combining the two Yields the desired result.
Answer: Hint for Question2:
$$\sin{a}\sin{b}\sin{c}=\frac{1}{2}[\cos(a-b)\sin{c}-\cos(a+b)\sin{c}]=\frac{1}{4}[\sin(a-b+c)+\sin(c-a+b)-\sin(a+b+c)-\sin(c-a-b)$$
Comment: First of all, thank you. I reached that point myself, but don't know how to continue. I also reached this point for the 1st question:

$$\sin(a+b-c)+\sin(a+c-b)+\sin(b+c-a)\le\sin(a)+\sin(b)+\sin(c)$$

----------

And this point for the 2nd question:
$$2[\cos(2a)+\cos(2b)+\cos(2c)-1]\le1$$

Trigonometry Inequality


Trying to fix errores with the admin_menu module

Question: I have a Drupal 8 installation that went bad after installing admin_menu module.
and now the website is down with this error.

stderr: PHP Fatal error:  Call to undefined function user_access() in /var/www/clients/client1/web7/web/modules/admin_menu/admin_menu.module on line 149

I've tried to delete the admin_menu module with Drush, given website is completely out of order and it gives me this error.

PHP Fatal error:  Call to undefined function variable_del() in /var/www/clients/client1/web7/web/modules/admin_menu/admin_menu.install on line 22
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to undefined function variable_del() in /var/www/clients/client1/web7/web/modules/admin_menu/admin_menu.install, line 22

So I've looked into admin_menu.install and I have commented out its code.
function admin_menu_uninstall() {
  // Delete variables.
/*  variable_del('admin_menu_components');
  variable_del('admin_menu_margin_top');
  variable_del('admin_menu_position_fixed');
  variable_del('admin_menu_tweak_modules');
  variable_del('admin_menu_tweak_tabs');
  variable_del('admin_menu_show_all');
  variable_del('admin_menu_display');
  variable_del('admin_menu_cache_server');
  variable_del('admin_menu_cache_client');
  // Unused variables still should be deleted.
  variable_del('admin_menu_devel_modules');
  variable_del('admin_menu_devel_modules_enabled');
  variable_del('admin_menu_devel_modules_skip');
*/
}

It appears it was also done in a patch here.
Since it worked, I put the module back on and tried to overcome the issue and deleted content of admin_menu_page_bottom() function at line 150 in admin_menu.module and this brought the website back online.

Is it okay to remove this function content? and why is this module still not functional? have anyone else managed to get this working on Drupal?
Is it okay to do this in Drupal 8 to unsintall admin_menu removal with above procedure and is there anything that I am missing?
Comment: This module is super old (last release March 2015) long before Drupal 8.0.0 was released and stable. It could just be a port that was started and never finished. That said, hardly anyone uses this module anymore - they use Admin Toolbar.
Comment: I am not sure why admin menu isn't working but I do know many are now using https://www.drupal.org/project/admin_toolbar and https://www.drupal.org/project/toolbar_themes in 8 instead. Same functionality and it builds on core toolbar.
Answer: Admin menu hasn't had any development effort for comfortably more than 2 years now. It doesn't have a Drupal 8 release to speak of; the chances of getting the module working without major surgery to the code are pretty slim.
If you can get the module successfully uninstalled by commenting out some code, then definitely do it (then probably delete the module folder so you don't accidentally enable it again).
The Admin Toolbar module is its successor. It integrates with the core toolbar, and has a sub-module which provides the tools menu that you'll be familiar with from Drupal 7 (with clear cache links etc).


pgAdmin - Como instalar "system tray plugin"?

Question: Utilizo pgAdmin 4 no Linux Mint 19.3 cinnamon.
Sempre que abro o programa, além do navegador, aparece uma pop-up dizendo:

Note: Installing  a system tray plugin will prevent this window being
  shown.

Já procurei, mas não consigo encontrar a que plugin ele se refere. O pgAdmin funciona normal, mas gostaria de evitar essa janela.
Imagem da janela:
Answer: Instalei o applet Collapsible Systray e resolveu.
Agora ao invés da janela, apenas aparece um ícone ao lado do relógio.
Comment: Acho que é o ideal pois é isso que o nome do applet promete fazer.


Standard deviation formula

Question:
I faced the below formula for standard deviation.
Is it correct or no? If it is How can I simplify or expand it.
$$ \sigma(S) \ =  \sum_{s \in S} \frac{s^2}{|S|} - avg(S)^2 $$
Comment: It is wrong for standard deviation, as it will have squared units. However, you meant variance. What formula do you use for calculating variance?
Comment: What you have there is a formula for variance. It's okay algebraically but you shouldn't use it that way for any numerical calculation.
Comment: Thanks @Glen_b for clarification....
Answer: No, it's not correct. What are $S$ and $s$ here? We use $X$ and $x$ instead.
The population variance, which uses Greek letter is:
$$\sigma^2=\frac{1}{N}\sum^N_{i=1}(x_i-\mu)^2$$
However, since you probably don't know the true mean, which is $\mu$, you should use the sample variance, in English letter:
$$s^2=\frac{1}{n-1}\sum^n_{i=1}(x_i-\bar{x})^2$$
where $\bar{x}$ is the average of X.
So the sample standard deviation is:
$$s=\sqrt{\frac{1}{n-1}\sum^n_{i=1}(x_i-\bar{x})^2}$$
Comment: This misses the point about an equation for a sample version of $var(X)= \mathbb{E}[X^2] - (\mathbb{E}[X])^2$. Reasoning through it in my head, the given formula is equivalent to the usual MLE for variance. This is why I asked about which formula the OP wants to use for calculating variance.
Comment: I would have thought $s$ is $x_i$ and $|S|$ is $n$, with the expression in the question being either $\frac{1}{n}\sum\limits^n_{i=1}x_i^2-\mu^2$ for a population or $\frac{1}{n}\sum\limits^n_{i=1}x_i^2-{\bar x}^2$ for a sample
Comment: @Dave, I understand what you mean, you want to use the stat formula (I have the book Statistical Inference by George Casella too). However, if the person use avg(). I would assume he or she is not trying to use the theorem. :-)

Standard deviation formula


Why we need different menu item types?

Question: While I was studying hook_menu, I came across menu item types and I found that there are 6 types of menu item types as follows :
1] MENU_CALLBACK
2] MENU_DEFAULT_LOCAL_TASK
3] MENU_LOCAL_TASK
4] MENU_NORMAL_ITEM
5] MENU_LOCAL_ACTION
6] MENU_SUGGESTED_ITEM
I have read the documentation on Drupal.og and doc says that we have different application of each menu item type.
But I am not able to differentiate when to use which menu item type?
can I anyone help me to understand that which menu item type should be used ?
If any one explains use of each menu item type with example then it will be appreciated.
Answer: I realize this is a bit late, but just in case it helps anyone who stumbles across this...
1) MENU_CALLBACK - Menu callbacks are a special type of page that isn't meant to be viewed by a user. They are used as an endpoint for APIs (such as AJAX requests). Menu callbacks sort of act as a way for an API to "call a function".
2) MENU_DEFAULT_LOCAL_TASK - The default local task is just the local task that is selected by default. An example of this is the "view" tab on nodes. See more about local tasks below.
3) MENU_LOCAL_TASK - Local tasks are tabs. When viewing a node as an admin, several tabs are visible (view, edit, etc). Each of those tabs a local task.
4) MENU_NORMAL_ITEM - This is a page. Simple as that.
5) MENU_LOCAL_ACTION - Local actions are similar to local tasks, except they are meant to conduct an action, rather than display information. An example of this is the "Add Content" link that displays on the Content Administration page.
6) MENU_SUGGESTED_ITEM - This is almost exactly like a regular menu item, except it's disabled by default. This can be used by module makers to suggest a menu item to the user, but leave it up to the user to actually enable it.

Why we need different menu item types?


DbEntityEntry.State vs DbPropertyEntry.IsModified

Question: Estou com uma dúvida sobre essas duas maneiras de especificar se uma entidade foi modificada. Eu geralmente utilizo DbEntityEntry.State com o EntityState.Modified quando faço uma alteração muito grande no model e quero que todas elas sejam persistidas no banco de dados, e utilizo o DbPropertyEntry.IsModified com true quando quero especificar que apenas uma propriedade foi modificada.
Então supondo que que eu tenha um model e que atualizo várias propriedades dele (mas não todas) durante um processo. Logo em seguida marco o model (e não as propriedades modificadas) como EntityState.Modified através da propriedade DbEntityEntry.State.
Quando eu aplicar as mudanças através do DbContext.SaveChangesAsync() todas as propriedades do model serão atualizadas no banco ou apenas as que foram realmente modificadas? Será gerado um comando UPDATE de SQL que incluirá todos os campos do model na atualização?
Answer:
Quando eu aplicar as mudanças através do DbContext.SaveChangesAsync() todas as propriedades do model serão atualizadas no banco ou apenas as que foram realmente modificadas?

Todas as propriedades são atualizadas, a menos que você especifique quais não serão, assim:
var entry = context.Entry(obj);
entry.State = EntityState.Modified;
foreach (var nome in new[] { "Prop1", "Prop2", "Prop3" })
{
    entry.Property(nome).IsModified = false;
}

Será gerado um comando UPDATE de SQL que incluirá todos os campos do model na atualização?

Se você não especificar quais devem ser excluídos (ou ainda, incluídos), sim. Será com todos os campos.
Se quiser especificar exatamente quais campos serão atualizados, use o seguinte clichê:
db.Entidades.Attach(entidade);
db.Entry(entidade).Property(x => x.Prop1).IsModified = true;
db.Entry(entidade).Property(x => x.Prop2).IsModified = true;
db.Entry(entidade).Property(x => x.Prop3).IsModified = true;
db.SaveChanges();

Comment: Vlw, sanou minha dúvida.


Setar atributos em um único bloco JS

Question: Existe alguma maneira de fazer isso? Eu to repetindo muito código com o setAttribute em um único elemento, então estou pesquisando se existe alguma forma de fazer isso de um jeito mais organizado e otimizado, mas não achei ainda.
Abaixo vai um EXEMPLO do que to fazendo e um EXEMPLO do que queria fazer se possível:

Link qualquer que irei utilizar no exemplo:

Código JS que estou fazendo pra setar os atributos:
document.querySelector('.teste').setAttribute('href', 'https://www.teste.com')
document.querySelector('.teste').setAttribute('title', 'Site de Teste')
document.querySelector('.teste').setAttribute('id', 'idteste')

Como eu queria se possível ou algo similar:
document.querySelector('.teste').setAttribute(['href', 'title', 'id'], ['https://www.teste.com', 'Site de Teste', 'idteste'])

Teria algo similar a isso ja nativo do JavaScript?
Comment: Nativamente não tem.
Answer: Poderia fazer usando uma função, passando como parâmetros o elemento, e os atributos e os valores como arrays, e fazer um for em qualquer uma das arrays setando os atributos:

function setAttr(el, atts, vals){
   for(var x=0; x<atts.length; x++){
      el.setAttribute(atts[x], vals[x]);
   }

   console.log(el);
}
setAttr(document.querySelector('.teste'), ['href', 'title', 'id'], ['https://www.teste.com', 'Site de Teste', 'idteste']);
link

Outra forma (ainda melhor) é passando dois parâmetros: o elemento e um objeto com pares atributo:valor para a função e fazer um for...in:

function setAttr(el, atts){
   for(var x in atts){
      el.setAttribute(x, atts[x]);
   }
   console.log(el);
}
setAttr(document.querySelector('.teste'), {'href': 'https://www.teste.com', 'title': 'Site de Teste', 'id': 'idteste'});
link

Pra ser bastante sincero, eu preferiria repetir mesmo como você está
  fazendo. Usar uma função para aplicar atributos, na minha opinião, é
  trocar 6 por meia-dúzia. Não vejo muita vantagem e acho que fica até pior de ler.

Neste caso, eu apenas atribuiria o elemento a uma variável para não repeti-lo várias vezes:
var el = document.querySelector('.teste')
el.setAttribute('href', 'https://www.teste.com')
el.setAttribute('title', 'Site de Teste')
el.setAttribute('id', 'idteste')

Answer: Podes simplificar atributos desta maneira:
document.getElementById("test").href = "http://www.cnn.com/";
document.getElementById("test").id= "novoID";
document.getElementById("test").required = false;
document.getElementById("test").disbled= false;

Em vez de procurarespor ID podes usar getElementByClass para procurares por class.
Mas penso que não podes mudar mais que um atributo de uma só vez usando arrays, corrijam se tiver errado.
Comment: Este código vai buscar o elemento `test` ao DOM `4` vezes, que é precisamente o que o autor está a tentar evitar.

Setar atributos em um único bloco JS


Change $form_state in AJAX callback

Question: I am creating a form which uses the form API '#ajax' attribute, and I need to make changes to $form_state when the AJAX-enabled button is pressed. Here's what I've got:
Inside my form builder function:
...
$form['some_fieldset']['add_more'] = array(
      '#type' => 'button',
      '#value' => t('Add more rows'),
      '#ajax' => array(
        'wrapper' => 'some-fieldset',
        'callback' => 'my_module_settings_ajax',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );

...

And here's the callback function:
function my_module_settings_ajax($form, $form_state) {
  // Make a change to $form_state
  if ($form_state['some_fieldset']['add_more']) {
    $form_state['values']['some_fieldset']['table'][] = array('first_field' => '',
                                                                'second_field' => '');
  }

  return $form['some_fieldset'];
}

The change I've made to $form_state seem to be lost once the callback has finished. Is there any way to make a change to $form_state in this function, or there any other function I should use for this instead?
EDIT
As it turns out, the callback is the wrong place to do this logic. Instead, at the top of the form builder function, I added this:
// Respond to AJAX-triggger:
// Add new row
if ($form_state['triggering_element']['#name'] == 'add_more') {
  $form_state['values']['some_fieldset']['table'][] = array('first_field' => '',
                                                                'second_field' => '');
}

Of course, I had to give the button the name:
$form['some_fieldset']['add_more'] = array(
  '#type' => 'button',
  '#name' => 'add_more', // <-- Right here
  '#value' => t('Add more rows'),
  '#ajax' => array(
    'wrapper' => 'some-fieldset',
    'callback' => 'my_module_settings_ajax',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

And now it works!
Answer: You need to pass $form_state as reference; the AJAX function needs to be defined as in the following example:
function mymodule_settings_ajax($form, &$form_state) { /* … */ }

Comment: Of course, didn't think of that. Unfortunately, it didn't have any effect - any change made to $form_state is ignored in the form builder, and the next time the AJAX call is made, $form_state is reverted. Could it be that the form has already been generated by the time the callback executes? Is there a way to run a custom submit-handler for this button instead?
Comment: To clarify, you need the & to pass by reference rather than by value. Without it you are only modifying a copy of $form_state.
Comment: Yes, if you don't do this, you only modify a local variable.
Comment: Try to change the type from button to submit
Answer: I'm not sure that it's a direct answer to your question, but it may work for you use case: Instead of changing the $form_state add values to your $form. If you don't want them to show just use #hidden.

Change $form_state in AJAX callback


Grouped gallery content with Views

Question: I have an gallery content type with a title-, image-, and text select list field. This content type is used for a gallery where the select list values works as a kind of category for the gallery(a bit like a taxonomy). Using Views I have gotten all the published values printed out group according to there select list values. However I would like to print out an headline above each of the grouped images. Like this:
headline1
item1, item2, item3...
headline2
item4, item5, item6...
The headline is one of the values from the select list field and the grouped items below is the content where this specific value is chosen from the select list field(during upload). Its easy to get stuff printed out and sorted using Views but it seems to be more difficult to get and headline in there.
Anyone know if this is possible, maybe using preprocess for views or views-view.tpl.php files? I have gotten this to work with the grouping feature for table layout, but would like to have it printed out in unformatted html instead.
Answer: This should already be happening. Which version of Views?
If, as you said, the headlines ARE the values of the select list, then they should be showing up above each group automatically.
In Views 3:
Under Fields, add the select_list_field and check "Exclude from display"
Under Style settings (unformatted), choose Grouping Field: select_list_field
It will group by the select list item, and display that select list item's name (ie, the headline) above the group.
Comment: Thx, i got it now. Also found semantic views pretty useful:).

Grouped gallery content with Views


SQLite Database Security and Tampering

Question: I just wanted to do a quick sanity check with StackOverflow to confirm my suspicion. I'm creating an app and was tempted to use FMDB in Swift to store some data.I am treating this data as public in the sense that I assume it can be tampered with (and thus untrusted). This is because, after all, unlike a web app, this app runs on a user's device and thus they can access the .sql file and alter the database.
If I wanted to store information like if a user purchased something, unlocked certain weapons, or other data that I do not want to be altered in any way, I should not use a local database on the user's device.
Would you say this is correct and safe to proceed under this assumption? If I was looking to use the database to persist something important that took place, what would be a good approach? encryption with the key in the app, or maybe a hash or something?
Comment: Of the key/hash is stored on the device, what do you gain?
Comment: @CL I can store that using iOS KeyChain, which I was told is rather hard to crack but I guess at the end of the day anything can be gotten. You could even look in memory. http://stackoverflow.com/questions/18326846/sqlcipher-how-safe-is-sqlcipher-has-it-been-hacked seems to address this a lot. What do you think?
Comment: hey @Rob do you want to answer and i'll mark this as answered to give you credit? Thank you.
Answer: If you want to secure your database, FMDB includes hooks for SQLCipher, which you have to obtain separately. See the various FMDB Encryption Methods that you can use once you have SQLCipher included in your project.

SQLite Database Security and Tampering


What to do about impossibly fast transitions in Well-Tempered Clavier prelude 15?

Question: Do composers really mean that one should play what they write exactly? For example, in The Well-Tempered Clavier, prelude 15.
In measure 2, last 3 notes: does Bach really intend that one should keep the left hand on the G while playing the B, then remove the G on the left hand while playing the G on the right hand, then replace the G with the left hand and play the E with the right hand?
Same principle for measure 7 with the right hand: keeping the C during the first 3 notes looks impossible for any concert pianist in the world at the speed requested, unless we cheat.
So what is the spirit of Bach: should we play differently than what he writes?
Comment: One would imagine Bach, of all people, would be reasonably certain of what he wrote.
Answer: Considere a two-manual harpsichord. I think the notation is what was intended.
Comment: Bach didn't always write for a specific instrument, but he did own some harpsichords and clavichords (and lutes).
Answer: Bach rarely notated whether notes were legato or staccato.
I would be perfectly idiomatic to play all the left hand 8th notes from the beginning to the middle of bar 3 staccato, in which case the problem doesn't arise.
The idea that "everything should be played perfectly legato as written" is an unfortunate consequence of the way people are now taught to play the piano. It has never applied to any other instrument (including other keyboard instruments) and doesn't apply to most piano music either.
We can't be sure what instrument Bach wrote this for, but we can be pretty sure it wasn't a piano, since in his lifetime the piano was still a fairly experimental instrument, and he disliked the ones that he tried.
On a good harpsichord played in a resonant wood-panelled room like a typical 18th century music room, the amount of resonance when the key is released makes the question academic rather than practical in any case.
This makes the point pretty well, and you can see exactly how long (not!) Newman holds down the left hand top Gs in the first two bars.


Elementary question about real analysis

Question: Suppose $A \subseteq \mathbb{R}$, and let $x \in [a,b]$. Put
$$ F(x) = \int_{[a,x]} \chi_A dm $$
Then of course we know that $F $ is differentiable for almost all $x \in [a.b]$ and
$$ F'(x) = 1  \; \; \text{for almost all } x \in [a,b] \cap A $$
Can someone explain to me why does it follow that $F'(x) = 1 $ implies that there exists $\epsilon$ and $\delta >0$ such that
$$ 1 \geq \frac{ m( [x , x +h] \cap A )}{h} > 1 - \epsilon \; \; for\; \; 0 < h < \delta$$
and
$$ 1 \geq \frac{ m( [x , x +k] \cap A )}{k} > 1 - \epsilon \; \; for \; \; 0 < k < \delta$$
Comment: If $A=\emptyset$, then $F' = 0$.
Answer: $$F(x+h)-F(x)=\int_{[x,x+h]}\chi_{A}dm=m([x,x+h]\cap A)$$
Comment: How does this answer the question? If the set $A$ has measure zero, then $F(x+h)-F(x) = 0$, and there is no way it can satisfy the condition above?
Answer: This is not true. If $A$ is the Cantor set, then $F=0$ and so $F'=0$ everywhere.
Comment: Can someone explain the downvote?

Elementary question about real analysis


startActivityResult Problem on Quick Search Box in Android?

Question: How to do the startActivityResult() for the Quick Search Box? that is if i click a button in my activity. it should wake up the QSB and search. i click the suggestion button. it will return the string which is shown as a suggestion. how to do it? which intent action i have to use and how ? Any Idea?
EDIT:
i am using android:searchSuggestIntentAction="android.intent.action.VIEW" attribute. its reloads the current Activity.Why? which intent action i have to use and how ?
Answer: onSearchRequested() will pop up the search box, but you need to set up some infrastructure first.
Comment: Thanks for reply. i completed that what you have said in your answer. when i click my suggestion it reloads my activity. Why? i just want to drop a pin on that map.. the problem is the current Activity reloads. why?
Comment: I'd suggest you make quick search work on a blank Activity first.
Comment: it does not work. now the blank activity reloads. when we click the back butto its shows ActivityThread Exception. for that check my Previous question?http://stackoverflow.com/questions/2848106/activitythread-exception-in-android


What is the interval between two enharmonic notes?

Question: The interval between, say, C4 and D4 is a major 2nd.
What is the interval between B#3 and C4?
Is it still a 2nd?
For lack of a better term would it be something like a minor minor 2nd?
Answer: You have:

B# - C: Diminished 2nd (same as B-Cb)
B - C: Minor 2nd
B - C#: Major 2nd (same as Bb - C)
Bb -C#: Augmented 2nd

If I'm not mistaken, there are also double diminished and double augmented intervals, like Bb - Cx but rarely used
Generally the interval qualities are: Diminished, Minor, Major, Augmented or Diminished, Perfect, Augmented.
Comment: @Shevliaskovic my understanding is that technically, F#-Gb is an enharmonic interval and both notes are separated by a comma. On a violin you would make a slight difference (Bb should not be played exactly the same as a A#), which is impossible on a piano.
Comment: @Shevliaskovic to avoid an extended discussion, I can thankfully redirect you to this answer http://music.stackexchange.com/a/11816. This would in theory be a problem if one violin played an A# and another one a Bb, but having both notes written at the same time on the sheet would seem very experimental to me. The point was: a diminished second is not exactly a unison as there is a very thin difference between a sharp and a flat or between a chromatic and a diatonic tone.
Comment: Worth mentioning that on a keyboard instrument, this is recognized as a unison, but there is a difference on other instruments such as string instruments (where a sharp is played differently as a flat, e.g. in F#-Gb diminished 2nd).
Comment: @PierreArlaud F#-Gb would be a unison both in a piano and a guitar. What is exactly your point?
Comment: I play double bass and I've never heard of this. I try to play A# and Bb the same. Otherwise how would a violin or double bass play with a piano? won't it sound out of tune in times like this?
Comment: Didn't know that; I'll take a look. It seems interesting
Comment: @Shevliaskovic obviously string players playing with instruments that have fixed tuning like a piano need to play in the same tuning system, but a string quartet or a string orchestra doesn't have those constraints. This is not really a matter of different *names* for the *same note* but of similar pitches having different *harmonic and melodic functions* in common-practice western music. For example CPE Bach was very fond of diminished octaves (e.g. C to C flat),  which had a different harmonic function from major sevenths (e.g. C to B) and his "spelling" of the notes follows the function.
Comment: Aside from enharmonics in common-practice harmony and/or unequal temperaments, these intervals also pop up in computer notation software - for example if you want to convert some notation from G flat major to F sharp major, that might be described as "transposing the music by an interval of a diminished 2nd".


Percentage calculation in php

Question: I am trying to caluclate a percentage below (which by the way I need to be rounded up, but it keeps displaying 100. How can I calculate percentage in php using below's example:
    $totalmarks += (int)$questionData['questionmarks'];
    $studentmarks += (int)$questionData['studentmark'];
    $percentage = $studentmarks / $studentmarks * 100;

echo $percentage;

Answer: Your formula is wrong. You are dividing studentmarks  by itself. It has to be divided by totalmarks. Currently its like saying $percentage = 1/1 * 100; which will always result in 100.
$percentage = ($studentmarks / $totalmarks) * 100;
$percentage = round($percentage,2);

Comment: Aorry bout that bad mistake, was doing this 5am and ended up going to sleep straight after haha. Sorry but thanks for answer
Answer: Easiest way (IMHO) is to always divide totalmarks with 100 and then multiply it with value you want percentage of (students)
$percentage = ($totalmarks / 100) * $studentmarks

Answer: I hope this code may help you :)
$totalmarks += (int)$questionData['questionmarks'];
$studentmarks += (int)$questionData['studentmark'];
$percentage = ($studentmarks /   $totalmarks) * 100;
echo $percentage;

Answer: To round up you need to use ceil()
echo ceil(($questionData['studentmark'] / $questionData['questionmarks']) *100);

Comment: You should replace questionmarks with studentmarks in your formula

Percentage calculation in php


Azure DevOps Pipeline - Updating BuildNumber

Question: I have attempted to update the build number in Azure DevOps Pipelines for quite some time now, and looked through various stackoverflow questions and documentation, and I simply cannot figure out how to fix my problem.
The Build Number I would like to set would be: $(year:yy)$(DayOfYear)$(rev:.r).
This apparently works on pipelines using the graphical interface (The pipelines were not made by me)
What I have tried so far:
- task: UpdateBuildNumber@0
  inputs:
    buildNumber: '$(year:yy)$(DayOfYear)$(rev:.r)'

Write-Host "##vso[build.updatebuildnumber]$(year:yy)$(DayOfYear)$(rev:.r)"

And a couple of variations of those as well. Each time, I get the error:

##[error]TF209010: The build number format $(year:yy)$(DayOfYear)$(rev:.r) contains invalid character(s), is too
long, or ends with '.'. The maximum length of a build number is 255
characters. Characters which are not allowed include '"', '/', ':',
'<', '>', '', '|', '?', '@', and '*'.

I have tried making variables for each of the dates, and using the variables instead, but that does not work either.
Any help would be greatly appreciated.
Answer: It because all those variables are available only if you give it in the name: in your YAML, not in other tasks.
From the docs:

The following table shows how each token is resolved based on the previous example. You can use these tokens only to define a run number; they don't work anywhere else in your pipeline.

So, the only option it just to configure the name: $(year:yy)$(DayOfYear)$(rev:.r).
Comment: Thank you very much! Hope you have a wonderful day!!


I can't create AWS glue job 4.0 with cloudformation

Question: I want to create AWS GLUE job(GLUE version 4.0) with cloudformation, but have this error:
Glue Version 4.0 is only supported for Glue ETL,                                                                                Ray and Streaming jobs.
Here is my template resource code
  TestJob:
    Type: AWS::Glue::Job
    Properties:
      Connections:
        Connections:
          - !Sub job-${Env}
      Command:
        Name: !Sub job-${Env}
        ScriptLocation: !Ref JobScriptLocation
      ExecutionProperty:
        MaxConcurrentRuns: 1
      MaxRetries: 3
      DefaultArguments:
        "--enable-metrics": true
        "--enable-spark-ui": true
        "--extra-py-files": s3://aws-glue-studio-transforms-560373232017-prod-eu-central-1/gs_common.py,s3://aws-glue-studio-transforms-560373232017-prod-eu-central-1/gs_derived.py
        "--spark-event-logs-path": s3://test/sparkHistoryLogs/
        "--enable-job-insights": false
        "--enable-glue-datacatalog": true
        "--enable-continuous-cloudwatch-log": true
        "--job-bookmark-option": job-bookmark-disable
        "--job-language": python
        "--TempDir": s3://test/temporary/
      Name: !Sub job-${Env}
      Role: !Ref Role
      WorkerType: "G.1X"
      NumberOfWorkers: 5
      GlueVersion: 4.0

Answer: The property Name: !Sub job-${Env} for Command is incorrect.
Name - The name of the job command. For an Apache Spark ETL job, this must be glueetl. For a Python shell job, it must be pythonshell. For an Apache Spark streaming ETL job, this must be gluestreaming. For a Ray job, this must be glueray.


How to set different Toggle start position in jQuery?

Question: I have a simple jQuery toggle button but I don't want to use toggleSlide. If it is loaded homepage, the div must be opened and have a button to hide.
But if it is loaded another page, div must be closed and have button to show
Here is two code, that doesn't work. I try to add them together in HTML but doesn't work
For homepage:
<code>$(document).ready(function(){
  $("#flip").click(function(){
    if(window.location.href == 'http://homepage/')
      $("#panel").hide("fast");
  });
});
</code>
for another page:
<code>$(document).ready(function(){
  $("#flip").click(function(){
    if(window.location.href != 'http://homepage/')
      $("#panel").show("fast");
  });
});
</code>
Comment: How about you just add a class to the element on the homepage and check for that in your click handler? `$("#flip").click(function(){ if(!$(this).hasClass("noToggle")){ $("#panel").slideToggle("fast"); }; }); });`
Answer: You could try something like this:
<code>$(document).ready(function(){
   var condition = (window.location.href == 'http://homepage/');
   $("#panel").toggle(condition);
});
</code>
But comparing strings is usually bad practice, so what I would do is set a bool at the top of the page, and when the homepage is loaded, set it to true. Otherwise, false.
Comment: i wrote something that doesnot work. please can u look at it?
Comment: How can be wrotten zour suggestion with hideä
Comment: What did you write that didn't work? Please update your question with the code that didn't work and I will be able to help you better.
Comment: Okay I updated my answer, please let me know if this works. This should work universally, no need to write it twice. Also try doing a Console.Log on window.location.href and see exactly what it returns.
Comment: What means condition in .toggle(condition)? must i write anything else?
Comment: It's just a boolean I've already defined one line above. It just looks cleaner than putting the condition directly in the function.
Comment: $(document).ready(function(){
       console.log(window.location.href);
     });
Comment: Try that, look at the console log whenever the page loads and make absolutely SURE that `http://homepage/` is the URL you are loading. I'm pretty sure it should be something like `http://localhost/homepage/` but you never know.
Comment: Also, if you have multiple elements with the ID of "panel", then it won't work. ID's should be unique for every element.


SMS_ReplicationLinkSummary Server WMI Class - Status values

Question: I'm trying to monitor a SCCM environment via a non-SCOM system that primarily uses WMI as a management interface.
I've found the following class:
SMS_ReplicationLinkSummary Server WMI Class
There are numerous 'status' fields in this class that seem like they could give me what I'm looking for. The problem, however, is that I get values that aren't documented on the MSDN site.
I get a value of 125 for Site1Status as well as Site2Status
This is useless to me if I cannot translate 125 to something a normal human being can read.
Anyone familiar with these?
Comment: What do you want to monitor? Replication link status or site status?
Comment: ReplicationLinkStatus
Comment: Apologies, I also  need the Site1 and Site2 status
Answer: Site status = 125 means active. You can use SQL Function to get result, like:

SELECT dbo.fnGetSiteStatusFriendlyName(125)

The property LinkStatus is overall replication link status. 2 means Active. Any value other than 2 is not good.
Comment: Just want to know if these helped?
Comment: Apologies...I never forget to mark an answer when I get one...not sure why I missed this...many thanks!
Answer: You can look at the function to see how it does it -  i found this....
<code>        WHEN 100 THEN 'SITE_INSTALLING'
        WHEN 105 THEN 'SITE_INSTALL_COMPLETE'
        WHEN 110 THEN 'INACTIVE'
        WHEN 115 THEN 'INITIALIZING'
        WHEN 120 THEN 'MAINTENANCE_MODE'
        WHEN 125 THEN 'ACTIVE'             <----
        WHEN 130 THEN 'DETACHING'
        WHEN 135 THEN 'READY_TO_DETACH'
        WHEN 199 THEN 'STATUS_UNKNOWN'
        WHEN 200 THEN 'SITE_RECOVERED'
        WHEN 205 THEN 'SITE_PREPARE_FOR_RECOVERY'
        WHEN 210 THEN 'SITE_PREPARED_FOR_RECOVERY'
        WHEN 215 THEN 'REPLCONFIG_REINITIALIZING'
        WHEN 220 THEN 'REPLCONFIG_REINITIALIZED'
        WHEN 225 THEN 'RECOVERY_IN_PROGRESS'
        WHEN 230 THEN 'RECOVERING_DELTAS'
        WHEN 250 THEN 'RECOVERY_RETRY'
        WHEN 255 THEN 'RECOVERY_FAILED'

</code>