Are primes (ignoring $2$) equally likely to be $1~\text{or}~3\pmod 4$?

Question: For all primes $p\neq 2$, it's easy to see that $$p\equiv 1~\text{or}~3\pmod 4$$ I was wondering if it's equally likely ($50\%-50\%$) that prime modulo $4$ is $1$ or $3$. And if so, is there a simple proof?
Comment: This may be relevant to your interests: https://en.wikipedia.org/wiki/Chebyshev%27s_bias  Note that the bias notwithstanding, the long-term proportion is $1/2$, $1/2$.
Comment: article by Granville:  https://arxiv.org/abs/math/0408319  There is a @GregMartin on this site, possibly the other author?
Comment: Thank you very much! So to summarize, they occur with equal probability, but being 3 mod 4 occurs more for the most part (but not by an overly large amount). More concretely, if $a$ and $b$ are the number of primes less than $N$ that are 1 mod 4 and 3 mod 4 respectively, then $lim_{N\to \infty} \frac{a}{b} = 1$, but it's usually the case that $\frac{a}{b}<1$. These are due to the prime number theorem for arithmetic progressions and chebyshev's bias respectively.
Comment: See [Prime Number Theorem](https://en.wikipedia.org/wiki/Prime_number_theorem#Prime_number_theorem_for_arithmetic_progressions).  The linked paragraph states that, yes, primes congruent to $1$ or $3$ are equally likely - when interpreted correctly.  (Actually, the linked paragraph claims much more).
Comment: Technically, there is no way to get a probability of this sort. But there is a way that this is basically true.
Answer: There are infinitely many primes of forms $4n + 1$ and $4n +3$.
However, it is not clear which of the two are more abundant.
In 1853, Chebyshev in a letter indicated that he had a proof that the number of primes of the form $4n+1$ is less than the number of primes of the form $4k+3$. However, in 1914, Littlewood showed that Chebychev's assertion fails infinitely often; however, he did not specify where this first reversal occurs.
Nevertheless, some forty years later in a computer search, it was discovered that the first prime for which the $4n+1$ primes become more plentiful than the $4n+3$ primes is for the prime $26861$.
That situation is not reversed until the prime $616,841$.
Although every prime is either of one of these two types infinitely often, and despite Littlewood's proof, the density of each of these two prime types as far as I know has not been established. That being the case, it remains an open question that given a prime $p$, it is more likely to be of one type than another.
Comment: The density of each is asymptotically 1/2 of all primes.  This is Dirichlet's theorem on arithmetic progressions.
Comment: According to Wiki (Pythagorean primes)---``More strongly, for each n, the numbers of Pythagorean and non-Pythagorean primes up to n are approximately equal.'' (However, they do not cite a reliable reference nor do they quantify what is meant by *approximately equal*.) Do you have a reliable reference on your assertion of *asymptotically equal*? I indeed would like to obtain it. Thank you.
Comment: This is what is known as [Dirichlet's theorem on arithmetic progressions](https://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions#Distribution); [here are some notes on it](https://people.csail.mit.edu/kuat/courses/dirichlet.pdf) and [here's another](https://kskedlaya.org/18.785/dirichlet.pdf).
Answer: Summarizing the comments: They occur with equal probability, but being 3 mod 4 occurs more for the most part (but not by an overly large amount). More concretely, if $a$ and $b$ are the number of primes less than $N$ that are 1 mod 4 and 3 mod 4 resp., then $$\lim_{N\to\infty}\frac{a}{b}=1$$, but it's usually the case that $\frac{a}{b}<1$. These are due to the prime number theorem for arithmetic progressions and Chebyshev's bias respectively.


Check if a file exists, using another user (sudo -u)

Question: I want to check if a file exists [ -f /path/to/file ] using another user.
So, I added:
USER1        ALL=(USER2)     /bin/mkdir, /usr/bin/git, /bin/echo

to the sudoers file.
The problem is, when I try to execute
USER1:~$ sudo -u USER2 [ -f /path/to/file ] && echo "1"

I get the following:
Sorry, user USER1 is not allowed to execute '/usr/bin/[ -f /path/to/file ]' as USER2 on localhost.

So, the question here is: How do I enable that on the sudoers file?

Solution
I added /usr/bin/test to the sudoers file, and instead of going with this:
USER1:~$ sudo -u USER2 [ -f /path/to/file ] && echo "1"

I actually used:
USER1:~$ sudo -u USER2 /usr/bin/test -f /path/to/file && echo "1"

Answer: You're trying to execute /usr/bin/[ but haven't given the user permission to. There are two ways you could do this.
The first is to allow the user to execute /usr/bin/[ (which is the test program). This would allow the user to perform any kind of test on any file. You can also use test instead of [, which may be more obvious as to what's happening.
USER1   ALL=(USER2) /bin/mkdir, /usr/bin/git, /bin/echo, /usr/bin/[, /usr/bin/test

And then run:
sudo -u USER2 [ -f /path/to/file ] && echo "1"

or
sudo -u USER2 test -f /path/to/file && echo "1"

The second option is to write a wrapper script and allow the user to execute that. For example, with the following in /usr/local/bin/exists:
#!/bin/sh
set -e
[ -f "$1" ]

And this in /etc/sudoers:
USER1   ALL=(USER2) /bin/mkdir, /usr/bin/git, /bin/echo, /usr/local/bin/exists

The user could run:
sudo -u USER2 /usr/local/bin/exists /path/to/file && echo "1"

Comment: I tried option 1, and still the same error: `Sorry, user USER1 is not allowed to execute '/usr/bin/[ -f /path/to/file ]' as USER2 on localhost.`. And I want to avoid the second option, as I don't want to create another file to run that. There's any bits missing on the first option? I also tried `/usr/bin/[ .*` and it didn't work.
Comment: Although your answer didn't solve the problem, it pointed me to the right direction. If someone needs the final solution, please refer to the bottom of my question.
Comment: @jlcd Strange, it works for me. I've added that method to my answer.


When does a song sound bad in its parallel major / minor key?

Question: I've recently been getting into transposing songs into their parallel major / minor keys. I've recently tried the Princess Mononoke Theme by Joe Hisaishi, but it just sounds weird when we transpose it from minor to major.

I understand that the second measure, in D major, contains a tritone in the melody line, causing it to sound bad. However, are there any music theory rules around when a song would sound bad in its parallel major / minor key?
Comment: I do it by ear and not theoretical. Do you mean the melody or the accompaniment? I think the problem will occure in the lead tone of the dominant or accompaniment of 3rds. Couldn't you post the original tune and your whole transcription?
Comment: IMO, the more complicated, the worse it *tends* to sound in parallel keys.
Answer: It's always easier to play a song in its parallel key when only the 3 main chords - I IV V or i iv V (or v) are in the song.
Thus answering - when there are more than the 3 main chords. Although, it's entirely possible to harmonise in the parallel key, but will involve judicious choice of harmonies.
Comment: The last time I changed a melody from a major key to a minor key, I had to change its chords in places such as from vi to (b)VI, from ii to Vb5/V, and from V/ii to (b)VI, and I had to change even more melody notes, but the minor-key version still sounded pretty darn good and natural. It's also easy to change the I-vi-IV-V major-key chord progression to its i-(b)VI-iv-V minor-key version, and you can argue that you may as well leave bII as-is when changing between minor and major.
Answer: I see that Tim already gave my answer:
If you have only the harmony of the classical cadence tonic, dominant subdominant a transcription to major from minor and vice versa is no problem.
But here we have somewhat a phrygian cadence. (only that there's not a major V) It's almost impossible to transcript to the parallel key if you don't keep the VII major chord unchainged (as it has been already a major in the original version.
Another possibility would be to adapt the melody (like it is use in classical sonatas aswell in the subject of a fuga:
Instead of transforming the theme la mimimire mi mi sore to do sososofa so so ti fa you could transform it this way: so mimimire mi mi sore That means instead of transcribing to the parallel key Dm -> D of  you change to the relative key.
And this here is actually the link I was looking for: min.5:11

Maybe the point with the problem you have will be explained to you
https://www.ars-nova.com/cpmanual/alteredmodes.htm
where it's said:
(2) In descending, the upper note of the mode's tritone (B when untransposed) was often flatted to avoid the tritone if the lower note (F when untransposed) was present. In ascending, the same problem was solved by raising the lower pitch.
(3) Upper auxiliary tones (upper neighbor tones) were typically flatted in practice, though generally not written that way.
(4) The sixth degree in a minor mode could be raised if moving to or from a raised seventh degree, in order to avoid a melodic augmented second. This is the basis of the modern "melodic minor." In certain cases it might be necessary to raise another degree to avoid the aug. 2nd, for example in a Phrygian final cadence where the third is raised to major and a voice passes from the second degree to the raised third degree.
(5) Internal cadences could be formed on any degree, with one tone raised to form a leading-tone. But the modes had characteristic differences in the tones on which such cadences were formed. Jeppeson identifies these patterns, with the three most common cadences as follows ...
Answer: I'm probably repeating a bit, in different words, what the previous answers say.
When changing from major to minor (or vice versa), you keep the key note but change the mode, not necessarily the chords. Changing from major to minor doesn't mean just swapping chords (such as i for I, ii0 for ii, III for iii, iv for IV, v for V, VI for vi, and VII for vii0). For example, (going from major to minor) one may wish to keep the V (or V7) at cadence points but non-cadential V chords usually become minor (passing chords and the like and perhaps some half-cadences or cadence patterns that do not end phrases).  Several chromatic chords (Neapolitan, French, Italian, and German Sixths for example) are the same in major and minor; these probably should kept the same. Some diminished chords (made of three minor thirds is an example) stay the same but a half-diminished chord often can become fully diminished. Dominant ninths occur with a lowered 6th step in either major or minor but a chord like G-B-D-F-A can take the Bb sometimes.
Augmented chords may or may not change because of voice leading; it depends on the chords around them. The ii6 in major sounds good as a ii06 in minor; it's sometimes used this way even in major keys at cadences.
Rather often, classical era (Haydn, Mozart, Beethoven, Schubert, etc.) pieces do repeat passages in "the other mode" somewhere (exposition, development, recap) so these may give one an idea what has been used in the past.
Still, it's fun to do on the fly. I've done it with country-western pieces that were simple enough (especially waltzes) and the audience didn't notice.
Answer: Melodies that work well in both modes tend to emphasize musical features common to the modes, such as stepwise motion, the stability of scale degrees 1, 3, and 5, chord progressions using primary triads, sequences by descending fifth or third, etc. Examples can be found in any of Bach's fugue subjects.
Melodies that work badly in the opposite mode tend to emphasize musical features that differ in both modes, such as

Modulation to III, which is easy in minor but in major requires fitting in two accidentals
Leaps by perfect fourths/fifths that become tritones: 2-6 (major to minor) and 4-7 (natural minor to major)
Pentatonic melodic patterns. This seems to be the main obstruction in your example. In major the usual pentatonic scale is 1-2-3-5-6-1, while in minor it is 1-3-4-5-7-1. When a pentatonic scale is shifted to the other mode, the gentle, nearly equal scale steps (major 2nds and minor 3rds) get replaced with uneven, harsh minor 2nds and major 3rds, and the tritone also appears prominently.

So, for instance, the hymn tune "Be Thou My Vision," which, like most Irish folk music, is mostly pentatonic, does not work well in minor, while "A Mighty Fortress is Our God," which stresses scale degrees 1 and 5, works fine in minor (but don't get caught playing it that way in church...)
Answer: Maybe the rule is: it sounds bad if you try to fit the changed melody into an unsuitable harmony?
What comes to the example you gave, I don't see a big problem.
With an ascending bass on the first line:

With a descending bass on the first line:

I'm not entirely happy with the last two bars of the first line, but someone else can suggest something better. The point is, listen to the melody and harmonize it according to its nature.


Postfix - Relay incoming email only to certain domains

Question: We have an old zimbra server as the company mailserver, which does TLS1 only. Let's call zimbra for MailServerA.
To fix this (and sort out some security issues), I'd like to setup a postfix server to receive incoming email from the internet. Let's call this server for MailServerB
Then it should only forward email to MailServerA if the recipient's domain is in my list of domains.
How do I configure MailServerB to accept email from anyone, but only relay to MailserverA if the email is for one of my domains?
Answer: by using the selective relay feature:

add a line in /etc/postfix/transport:
mydomain.net        smtp:insecuremx.mydomain.net
run postmap /etc/postfix/transport
add

smtpd_relay_restrictions = permit_mynetworks, reject_unauth_destination
transport_maps = hash:/etc/postfix/transport
relay_recipient_maps = hash:/etc/postfix/relay_recipients

to /etc/postfix/main.cf it it
   is missing and run postfix reload.
Postfix to relay mails to other SMTP for particular domain
http://www.postfix.org/SMTPD_ACCESS_README.html#lists
https://xdeb.org/post/2017/12/20/mail-relay-mx-backup-and-spam-filtering-with-postfix/
Comment: Thanks! I managed to fix it. The transport was a part of the solution, but I also needed relay_recipients_map (only domains, no usernames). Ref: https://xdeb.org/post/2017/12/20/mail-relay-mx-backup-and-spam-filtering-with-postfix/


Setting up networking on a virtual server with virtual PC 2007

Question: I've created a virtual PC and installed Server 2003 R2 on it. I have added the application server role. I can get to the default site using http://localhost on the VPC.
The VPC can access the internet.
I can't however ping the VPC from my physical desktop (host machine).
I've tried adding a second network adaptor in the VPC console and giving this a static IP but to no avail.
Answer: It depends on how you have networking setup.  I you have it setup with NAT, then Virtual PC is assigning a private IP to the VPC (likely on a different subnet than your host PC).  If you have it setup to use the same network adapter as your host OS is using, then (if I recall correctly) it should get another IP from your router, and you can try pinging it via that IP, although (if I recall) that is tricky in that it has two IP addresses using the same MAC address, and your NIC would not know where to route packets.  If you have a second network card in the host, you could assign it to the Virtual machine and try connecting to it that way.
Could you perhaps post information on what the TCP/IP settings are for the host and guest, as well as information on the type of networking you have setup in Virtual PC?
Answer: It looks like you've set it up NAT'd behind the host.  So nothing can access it.  You need to bridge it to the network adapter.  Then you'll be able to access it from any machine on the network.


Cohen's Kappa for more than two categories

Question: I have data set of teacher's evaluation rated by 4 different raters. The teacher's are evaluated for 13 different categories for example (Interaction with students, lesson delivery etc). All of the 4 raters are rating teachers in 13 categories from 1 to 5.
I want to find the agreement level between observers using cohen's kappa. I know how to compute kappa for one category only but I am confused how can we do that for different categories? Do I have to compute it for each category separately? or is there any other method?
For computing kappa I am using STATA. Here's an example of how my data looks like. Can't share the original data.
Answer: From kappa - Stata  "kap (second syntax) and kappa calculate the kappa-statistic measure when there are two or more (nonunique) raters and two outcomes, more than two outcomes when the number of raters is fixed, and more than two outcomes when the number of raters varies. kap (second syntax) and kappa produce the same results; they merely differ in how they expect the data to be organized."
So, yes you can. Also, this other answer may help  you with interpretation.
Comment: No. See for example https://www.statisticssolutions.com/KappaCalculator.html
Comment: So I have to calculate it separately for each category?
Comment: Maybe read through the SPSS documentation on it beginning [here](https://statistics.laerd.com/spss-tutorials/cohens-kappa-in-spss-statistics.php), and look at what they do as  well by following the links to using SPSS. It isn't STATA, but SPSS documentation is generally good.


How to use text-overflow ellipsis in an html input field?

Question: My web page has input fields to which I have applied the following css :
.ellip {
    white-space: nowrap;
    width: 200px;
    overflow: hidden;
    -o-text-overflow: ellipsis;
    -ms-text-overflow: ellipsis;
    text-overflow: ellipsis;
}

But this doesn't seem to have any effect.
Am I missing something obvious here or is it not possible to have an ellipsis in an input field using CSS only?
Comment: Just checked and `text-overflow:ellipsis` works great on `input` elements (at least in Chrome)
Comment: The accepted answer doesn't seem to actually answer this question.
Answer: Setting text-overflow:ellipsis on the input itself did the trick for me. It truncates and places the ellipsis when the input is out of focus.
Comment: Also needed the `white-space:nowrap` and `overflow:hidden` to make it work https://www.codeply.com/go/xyUMETlNgs
Answer: I know this is an old question, but I was having the same problem and came across this blog post from Front End Tricks And Magic that worked for me, so I figured I'd share in case people are still curious. The gist of the blog is that you CAN do an ellipsis in an input in IE as well, but only if the input has a readonly attribute.
Obviously in many scenarios we don't want our input to have a readonly attribute. In which case you can use JavaScript to toggle it. This code is take directly from the blog, so if you find this answer helpful you might consider checking out the blog and leaving a comment of appreciation to the author.

// making the input editable
$('.long-value-input').on('click', function() {
  $(this).prop('readonly', '');
  $(this).focus();
})

// making the input readonly
$('.long-value-input').on('blur', function() {
  $(this).prop('readonly', 'readonly');
});
.long-value-input {
  width: 200px;
  height: 30px;
  padding: 0 10px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

  <input type="text" class="long-value-input" value="sdghkjsdghhjdfgjhdjghjdfhghjhgkdfgjnfkdgnjkndfgjknk" readonly />

Comment: .click() doesn't work when you're tabbing through controls, and if you move the prop removal to .focus(), that comes with it's own set of issues (doesn't actually remove the readonly property since it's still got focus)
Comment: I have used a similar code but it's not working on IE. If you know about solution on ie, please comment.
Answer: From my testing Chrome, Safari and Firefox now support it.
However they do have slightly different effects.
On blur Firefox appends ... to the right of the text but only if there is any text hidden by the right hand side of the text box.
Whereas on blur Chrome seems to jump to the beginning of the text and appends the ... at the end, regardless of where you left the scroll position of the text.
Comment: Firefox can render text-overflow characters on both sides of the input field when defining two values, like `text-overflow: ellipsis ellipsis;`. Chrome seems to have problems with that.
Comment: This seems to stop working when the width is almost the width of the input's parent.
Answer: A  field is an element with its own rules. The input field is implemented in the way that if the text gets longer than the field, the text gets just unseen.
The reason for this is, if you use the field in a form and it would be possible to use text-overflow ellipsis, then it would only transmit the truncated content, what is not the wanted effect.
Comment: **a)** firefox 16 renders an ellipsis (at wrong position), when input field hasn't focus **b)** the reason is totally wrong, whats displayed has nothing to do with whats in the dom (and thus transmitted) **c)** having an ellipsis marker when not focused is (arguably) best from a usability pov
Comment: Chrome renders ellipsis too when the textbox isn't focused. If you want to change your "lack of facts" answer I'd love to remove the downvote i've given you!


Installing Gearman with PHP Extension on Debian 6.0.5 leads to error

Question: What I have tried ...
<code># apt-get install php5-dev
# apt-get install gearman-job-server libgearman-dev
# pecl install gearman
</code>
Result ...
<code>...
configure: error: Please install libgearman
ERROR: `/tmp/pear/temp/gearman/configure' failed
</code>
Than I tried ...
<code># export GEARMAN_LIB_DIR=/usr/include/libgearman
# export GEARMAN_INC_DIR=/usr/include/libgearman
# pecl install gearman
</code>
Result ...
<code>...
configure: error: libgearman version 0.21 or later required
</code>
Then I tried ...
<code># wget pecl.php.net/get/gearman-1.1.1.tgz
# tar -zxf gearman-1.1.1.tgz
# cd gearman-1.1.1
# phpize
</code>
Result ... same error as in attempt 2
Whats wrong?
Answer: Debian 6 only has version 0.13 of Gearman. You either need to upgrade that, or find an older version of the PHP extension. You could try installing the packages from testing.
Comment: @mgorven How is it possible to ugrade the version of libgearman on Debian 6? I'm facing the same problem :(


How to send a message notification based on a flagged node being linked via entity reference?

Question: I'm trying to figure out how to make the following work: Sending notification based on flagged node being linked via entity reference.
I have a 'News' content type and a 'Band' content type, that has a flag called 'fan'. When somebody becomes a fan, I want them to receive a notification via the Message module whenever I link the band to the content type 'News' with the News article I just created.
The content-type setup is as follows:

Node type 'News' has field:
Entity reference to content type 'Band'
The Band content type has a flag called 'fan'
The Message type is called "user notification center" and has a field named field_mnc_recipients, which is an reference to a user(unlimited values)

How I want it to work:

when a user flags the 'band' and a new article is referenced to the band, I want to notify them with the Message module,
to make it work, I need to get the user from the flag for that band and insert it into the message field  field_mnc_recipients.

I created a Rules Component as follows:
<code>{ "rules_message_tes3" : {
"LABEL" : "message tes3",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "referencing_node" : { "label" : "referencing_node", "type" : "node" },
  "referenced_node" : { "label" : "referenced_node", "type" : "message" }
},
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "referencing-node" ],
      "type" : { "value" : { "bands" : "bands" } }
    }
  },
  { "entity_is_of_type" : { "entity" : [ "referenced-node" ], "type" : "message" } },
  { "entity_has_field" : { "entity" : [ "referenced-node" ], "field" : "field_mnc_recipients" } }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "referencing-node:flag-fan-user" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "data_set" : {
            "data" : [ "referenced-node:field-mnc-recipients" ],
            "value" : [ "referencing-node:flag-fan-user" ]
          }
        },
        { "entity_create" : {
            "USING" : {
              "type" : "message",
              "param_type" : "user_notification_center",
              "param_user" : [ "site:current-user" ]
            },
            "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
          }
        }
      ]
    }
  }
]
</code>
}
}
And now I got stuck, I based the component on "Sending a message to users of a flagged node when it is referenced" which is close to what I want.
Comment: great question, too bad I don't have time to tackle this one, but seems doable.
Comment: @NoSssweat still no time? I'm curious about what you were thinking "back then" ...
Answer: It works, after days and days it finaly works! I used this as a base line for my research: Sending a message to users of a flagged node when it is referenced
Instead of sending an e-mail within the loop, i create a new entity(action), in this case the message notification. After that i fill(set data) in the entity-created:field-mnc-recipients field with the flagging users. This is how it works :)
Comment: Please add an export of your rule in this answer to elaborate on how exactly you did this. And consider marking your own answer as "accepted" also (so that the question no longer appears as "unanswered" ...).


How to efficiently organize authentication & authorization using JWT in a microservice Spring Boot app?

Question: I am still a beginner in creating Spring applications, so I need to further grasp a deeper understanding of how microservice architecture works. So far I have read some conflicting opinions, and I want to adhere to best practice.
Following a tutorial on JWT HttpOnly cookie authorization in Spring boot, I have built a simple app that registers, logs in and logs out a user. It maps only post requests to /login /signup and /logout as a result. The Spring Security configuration in the app filters all incoming requests and populate the SecurityContext with authenticated object if the token is of a valid authenticated user.
Now the problem is that I want to build a separate Spring Boot app that handles other logic so that I can follow the microservice architecture paradigm. As the already built app's security config already handles the authorization in the HTTP request itself, I want to utilize this service to automatically authorize each request before it is forwarded to the next service.
I read about API Gateaways and the solution makes sense but seems too abstract to me to start building an implementation. Also I have a couple of questions: should the request first go to the intended service then to the auth service and then back to the intended one OR go to the auth service and then to the intended service? Which way is best practice? How to effectively connect the two services?
Any help will be much appreciated!
I have not yet tried a solution as I do not know how to proceed.
Answer: consider the following ;
for your order of request flow - it is generally recommended to first authenticate and authorize the request in the API Gateway before forwarding it to the intended microservice. it will ensures that only authenticated and authorized requests are processed by the microservices. and to effectively connect the two services, you can use service discovery mechanisms like Netflix Eureka or HashiCorp Consul. these tools allow services to register themselves and discover other services dynamically. You can also use load balancers to distribute the incoming requests across multiple instances of the microservices.
and by implementing an API Gateway, you can centralize the authentication and authorization logic and ensure consistent security across your microservices. It also provides a single entry point for clients to interact with your microservices, simplifying the overall architecture.so the follow up list will contain ;
1.Design the API Gateway: Determine the responsibilities of the API Gateway, such as authentication, authorization, rate limiting, and request routing. In your case, the API Gateway will handle authentication and authorization.
2.Create a new Spring Boot app: Start by creating a new Spring Boot app that will serve as your API Gateway. This app will be responsible for receiving all incoming requests and forwarding them to the appropriate microservice.
3.Configure the API Gateway: In the API Gateway app, configure the routes for each microservice. For example, you can define routes like /users that will be forwarded to the user service. You can also configure the authentication and authorization filters to validate the incoming requests using the existing security configuration from your already built app.
4.Implement request forwarding: Once the request is authenticated and authorized, forward it to the intended microservice. You can use Spring's RestTemplate or WebClient to make HTTP requests to the microservices.
5.Handle responses: Receive the response from the microservice and return it to the client. You can also handle any error scenarios and provide appropriate error messages.


Evaluate: $\int \frac{{\sin(x)}}{{\sin(x) - \cos(x)}}\,dx$

Question: I'm trying to evaluate the following integral:$$\int \frac{{\sin(x)}}{{\sin(x) - \cos(x)}}\,dx$$ Here's my approach so far:
$$$$I've multiplied the numerator and denominator by  $-csc^3(x)$, resulting in $$\int -\frac{{\csc^2(x)}}{{\cot(x)\csc^2(x) - \csc^2(x)}}\,dx$$
Next I substituted $u = cotx $, giving me $$\frac{{du}}{{dx}} = -csc^2(x), du =  -csc^2(x)dx$$ therefore in $\int -\frac{{\csc^2(x)}}{{\cot(x)\csc^2(x) - \csc^2(x)}}\,dx$ by replacing $cotx$ with $u$,  I obtained,  $$\int \frac{-1}{{u\left(u^2+1\right) - \left(u^2+1\right)}}\,du$$ $$\int (\frac{1}{{4\left(u+1\right)}} - \frac{1}{{4\left(u-1\right)}} - \frac{1}{{2\left(u-1\right)^2}})\,du$$
I would greatly appreciate any insights or techniques that could help me make progress with this integral. Are there specific strategies or mathematical tools that I should consider? Are there any useful properties or identities related to this type of expression?
Thank you for your attention and assistance.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: If I can ask a question: you have multiplied by $-\csc^3(x)$, but what's wrong with a simple $\sec(x)$? :-)
Comment: @AnneBauval I thought it wasn't gonna work out in the end and so didn't do the integration. How stupid of me!
Comment: why is my question still closed? can anyone tell me the reason
Comment: You improved it only 40min ago. You had to wait for 4 votes for its reopening. Done.
Comment: It's only one vote away from being reopened.
Comment: Your question is not clear. I didn't check your computations but it seems you reached the goal. What "progress with this integral" do you need? Can't you integrate $\int (\frac{1}{{4\left(u+1\right)}} - \frac{1}{{4\left(u-1\right)}} - \frac{1}{{2\left(u-1\right)^2}})\,du?$
Comment: @JoséCarlosSantos Done. Thanks to you,  I learnt it only requires 4 votes.
Comment: Jayadrata: Again, what was your question? The "solution-verification" tag was added by @ÁtilaCorreia. Be *that* your question or be it not, please edit your post to clarify it.
Answer: Alternatively, you can proceed as follows:
\begin{align*}
\int\frac{\sin(x)}{\sin(x) - \cos(x)}\mathrm{d}x & = \frac{1}{2}\int\frac{2\sin(x)}{\sin(x) - \cos(x)}\mathrm{d}x\\\\
& = \frac{1}{2}\int\frac{(\sin(x) - \cos(x)) + (\sin(x) + \cos(x))}{\sin(x) - \cos(x)}\mathrm{d}x\\\\
& = \frac{x}{2} + \frac{1}{2}\int\frac{(\sin(x) - \cos(x))'}{\sin(x) - \cos(x)}\mathrm{d}x\\\\
& = \frac{x}{2} + \frac{1}{2}\ln\left(\sin(x) - \cos(x)\right) + C
\end{align*}
Comment: thank you very much your process was so much simpler
Comment: that should be sin(x) + cos(x) instead of (sin(x)−cos(x)), anyway thanks again.
Comment: @JayadrataBanerjee you are welcome ! I am glad to help.
Comment: quite beautiful!
Answer: It is not clear what you are asking for (see comments) but if it is a verification of your solution, here is one. You did very well with your substitution choice, and were quite near to the solution. I only have three remarks.

You did a small sign mistake when you  "obtained, $\int \frac{\color{red}-1}{{u\left(u^2+1\right) - \left(u^2+1\right)}}\,du$": it should be
$$\int \frac{\color{green}+1}{{u\left(u^2+1\right) - \left(u^2+1\right)}}\,du.$$
Next, your partial fraction decomposition was wrong. The correct one is:
$$\frac1{\left(u-1\right)\left(u^2+1\right)}=\frac12\left(\frac1{u-1}-\frac{u+1}{u^2+1}\right).$$
Incomprehensibly, you did not dare integrating it.
$$\begin{align}\frac12\int\left(\frac1{u-1}-\frac{u+1}{u^2+1}\right)du&=\frac12\left(\ln|u-1|-\frac12\ln\left(u^2+1\right)- \arctan u+C\right)\\&=\frac12\left(\ln\frac{|u-1|}{\sqrt{u^2+1}}+ \operatorname{arccot}u+D\right)\qquad(D=C-\frac\pi2)\\&=\frac12\Big(\ln|\cos x-\sin x|+x+D\Big).\end{align}$$
Comment: thank you very much for pointing out my errors and the solution
Answer: Let
$$ A=\int \frac{{\sin(x)}}{{\sin(x) - \cos(x)}}\,dx, B=\int \frac{{\cos(x)}}{{\sin(x) - \cos(x)}}\,dx. $$
Clearly
$$ A-B=\int \;dx=x+C_1. \tag1$$
Note
$$ A=-\int \frac{1}{{\sin(x) - \cos(x)}}\,d\cos(x), B=\int \frac{1}{{\sin(x) - \cos(x)}}\,d\sin(x) $$
and hence
$$ B+A=\int \frac{1}{{\sin(x) - \cos(x)}}\,d(\sin(x)-\cos(x))=\ln|\sin(x)-\cos(x)|+C_2. \tag2$$
From (1) and (2), it is easy to obtain $A$. In fact,
$$ A=\frac12 x+\frac12\ln|\sin(x)-\cos(x)|+C. $$
Answer: Use the substitution $x=\frac{\pi}{4}+v \Rightarrow dx=dv$
Now use the following facts:
$$\begin{aligned}
&\sin\left(x+\frac{\pi}{4}\right)=\frac{\sin x+\cos x}{\sqrt{2}} \\
& \cos \left(x+\frac{\pi}{4}\right)=\frac{\cos x-\sin x}{\sqrt{2}}
\end{aligned}$$
So we get $$\begin{aligned}
I= & \int \frac{\sin x d x}{\sin x-\cos x}=\int \frac{\left(\frac{\sin v+\cos v}{\sqrt{2}}\right) d v}{\left(\frac{2 \sin v}{\sqrt{2}}\right)} \\
& \Rightarrow I=\frac{1}{2} \int \frac{\sin v}{\sin v} d v+\frac{1}{2} \int \cot v d v \\
& \Rightarrow I=\frac{v}{2}+\frac{1}{2} \ln |\sin v|+C
\end{aligned}$$
Where $v=x-\frac{\pi}{4}$.
Method $2:$
Use the identities
$$\begin{aligned}
\cos ^2 x-\sin ^2 x & =\cos 2 x=1-2 \sin ^2 x \\
\sin 2 x & =2 \sin x \cos x
\end{aligned}$$
$$\begin{aligned}
f(x) & =\frac{\sin x}{\sin x-\cos x}=\frac{-\sin x(\cos x+\sin x)}{\cos ^2 x-\sin ^2 x} \\
& \Rightarrow f(x)=\frac{-1}{2}\left(\frac{2 \sin x \cos x+2 \sin ^2 x}{\cos 2x}\right) \\
& \Rightarrow f(x)=\frac{-1}{2}\left(\frac{\sin 2x+1-\cos 2 x}{\cos 2 x}\right) \\
& \Rightarrow f(x)=\frac{-1}{2}(\tan (2 x)+\sec (2 x)-1)
\end{aligned}$$
Hope you can proceed from here.
Comment: You gave two methods. Damn!
Answer: Multiplying the numerator and the denominator of the integrand by $\sin x+\cos x$ we get the integral of $\frac12-\frac12\sec2x-\frac12\tan2x$ which is
$$\frac x2-\frac14\ln|\sec2x+\tan2x|-\frac14\ln|\cos2x|+c$$
and
$$\frac x2-\frac14\ln|1+\sin2x|+c.$$
Answer: $1/2(\ln |\sin(x)-\cos(x)|)+x/2+c$
$\sin(x)$ can be written as $1/2(2\sin(x))$ and then $2\sin(x)$ should be written as $\sin(x)+\cos(x)+\sin(x)-\cos(x)$. Then integrating we get the above result.
Comment: How does your solution differ from Atia Correia?


how to manipulate SREC file

Question: I have an S19 file looking something like below:
S0030000FC
S30D0003C0000F0000000000000020
S3FD00000000782EFF1FB58E00003D2B00003D2B00003D2B00003D2B00003D2B00003D
S3ED000000F83D2B00003D2B00003D2B00003D2B00003D2B00003D2B00003D2B00003D
S31500000400FFFFFFFFFFFFFFFFFFFFFFFF7EF9FFFF7D
S3FD0000041010B5DFF828000468012147F22C10C4F20300016047F22010C4F2030000
S70500008EB4B8

I want to separate the first two characters and also the next two characters, and so on... I want it to look like below (last two characters are also to be separated for each line):
S0, 03, 0000, FC
S3, 0D, 0003C000, 0F00000000000000, 20
S3, FD, 00000000, 782EFF1FB58E00003D2B00003D2B00003D2B00003D2B00003D2B0000, 3D
S3, ED, 000000F8, 3D2B00003D2B00003D2B00003D2B00003D2B00003D2B00003D2B0000, 3D
S3, 15, 00000400, FFFFFFFFFFFFFFFFFFFFFFFF7EF9FFFF, 7D
S3, FD, 00000410, 10B5DFF828000468012147F22C10C4F20300016047F22010C4F20300, 00
S7, 05, 00008EB4, B8

How can I do this in Python?
I have something like this:
 #!/usr/bin/python
 import string,os,sys,re,fileinput
 print "hi"
 inputfile = "k60.S19"
 outputfile = "k60_out.S19"

 # open the source file and read it
 fh = file(inputfile, 'r')
 subject = fh.read()
 fh.close()

 # create the pattern object. Note the "r". In case you're unfamiliar with Python
 # this is to set the string as raw so we don't have to escape our escape characters

 pattern2 = re.compile(r'S3')
 pattern3 = re.compile(r'S7')
 pattern1 = re.compile(r'S0')
 # do the replace
 result1 = pattern1.sub("S0, ", subject)
 result2 = pattern2.sub("S3, ", subject)
 result3 = pattern3.sub("S7, ", subject)

 # write the file
 f_out = file(outputfile, 'w')

 f_out.write(result1)
 f_out.write(result2)
 f_out.write(result3)
 f_out.close()

 #EoF

but it is not working as I like!! Can someone help me with how to come up with proper regular expression use for this?
Comment: And what about the first line: `S0030000FC`
Comment: Looks like it might take nearly a whole line of `awk`...
Comment: I don't think you want regular expressions, you need slicing... http://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string-in-python
Comment: @CasimiretHippolyte, yes sorry I missed that, I added that.
Comment: @MarkSetchell, I have to try slicing that you are suggesting...
Answer: try package bincopy, maybe you need it.

bincopy - Interpret strings as packed binary data
Mangling of various file formats that conveys binary information (Motorola S-Record, Intel HEX and binary files).

import bincopy
f = bincopy.BinFile()
f.add_srec_file("path/to/your/s19/flie.s19")
f.as_binary() # print s19 as binary

or you can easily use open() for a file:
with open("path/to/your/s19/flie.s19") as s19:
    for line in s19:
        type = line[0:2]
        count = line[2:4]
        adress = line[4:12]
        data = line[12:-2]
        crc = line[-2:]
        print type + ", "+ count + ", " + adress + ", " + data + ", " + crc + "\n"

hope it helps.
Motorola S-record file format
Answer: You can do it using a callback function as replacement with re.sub:
#!/usr/bin/python
import re

data = r'''S0030000FC
S30D0003C0000F0000000000000020
S3FD00000000782EFF1FB58E00003D2B00003D2B00003D2B00003D2B00003D2B00003D
S3ED000000F83D2B00003D2B00003D2B00003D2B00003D2B00003D2B00003D2B00003D
S31500000400FFFFFFFFFFFFFFFFFFFFFFFF7EF9FFFF7D
S3FD0000041010B5DFF828000468012147F22C10C4F20300016047F22010C4F2030000
S70500008EB4B8'''

pattern = re.compile(r'^(..)(..)((?:.{4}){1,2})(.*)(?=..)', re.M)

def repl(m):
    repstr = ''
    for g in m.groups():
        if (g):
            repstr += g + ', '
    return repstr

print re.sub(pattern, repl, data)

However, as Mark Setchell notices it, there is probably a nice way to do it with slicing.
Answer: I know you are thinking Python and regexes, but this was made for awk and the following will maybe help you work out the way to do it using slicing:
awk '{r=length($0);print substr($0,1,2),substr($0,3,2),substr($0,5,8),substr($0,13,r-14),substr($0,r-1)}' OFS=, k60.s19

That says "get the length of the line in variable r, then print the first two characters, the next two characters, the next 8 characters and so on... and use a comma as the field separator".
EDITED
Here are a few more hints to get you started...
if you want to avoid printing line 1, you can do
awk 'FNR==1{next}  ...rest of awk script above ... '

If you want to only process lines longer than 40 characters, you can do
awk 'length($0)>40 {print}' yourfile

If you only want to process lines where the second field is "xx", you can do
awk '$2 ~ "xx" {print}' yourfile

Comment: thanks @Mark, what is that substr($0,13,r-14) for?  I think that substr($0,r-1) means take the end of line+2 characters?
Comment: That's correct. The 13 means the 13th character from the start of the line and r-14 means to take r-14 characters to allow for the first 2, the gap, the next 2 and the block of 8 characters.
Comment: awk is a powerful command! what if you want to do replacement or expression-matching deletion, does awk work with sed? I thinK I have to pipe the two?  for example if I want to get rid of the first line and last line, and also the middle string matches 'FD'?
Comment: I have added some extra hints and tips to my answer for you. Hope it helps!

how to manipulate SREC file


What is the object assigned to a Functional Interface in Java?

Question: I am new to Lambda Expressions in Java so please don't react too harsh if this question appears silly:  What is the actual object that gets implemented if I assign it to a FunctionalInterface?  I.e., if I do List<String> lst = new ArrayList<>() I implement an ArrayList object.  What is the object that gets created if I do Function<String,String> fct = s -> s?  And is that object immutable, i.e. does it make sense to have a public static final Function<String,String> REUSE_OFTEN = s -> String.valueOf(s)?
Comment: You could print out `REUSE_OFTEN.getClass()` and see what its class type is.  My guess is it's something synthesized by the compiler and not part of the API.
Comment: Also, as a general rule of thumb, it's important to note that the keyword `final` doesn't really achieve immutability for reference types. all it does is stop the field it qualifies from being updated;
Answer: When you write a lambda expression -
Function<String,String> fct = s -> s;

It simply creates an anonymous class that implements Function<String, String> interface and overrides its only method apply() with the implementation you have provided by s -> s. And assign this object to Function<String, String> reference.
Function<String,String> fct = new Function<>() {
    @Override
    public String apply(String s) {
        return s;
    }
};

And it is an immutable object and it does make sense to have a public static final Function<String,String> REUSE_OFTEN = s -> String.valueOf(s) as you can reuse same object to apply this operation with the different input.
Comment: Thank you very much for your explanation.
Comment: Initially, the lambda's body will be desugaed into a static method. After that, at run-time, the wrapper class will be generated for this method. In terms of JVM it's not an anonymous class...
Answer:
I.e., if I do List lst = new ArrayList<>() I implement an
  ArrayList object.

You instantiate a ArrayList rather.

What is the object that gets created if I do Function
  fct = s -> s? And is that object immutable, i.e. does it make sense to
  have a public static final Function REUSE_OFTEN = s ->
  String.valueOf(s)?

Lambdas are not the same thing than anonymous classes in terms of byte codeand also in terms of behavior/functioning. This last one is close enough but not exactly the same.
Here are two methods that do the same thing, one with lambda the other with anonymous class :
public class CompareBoth {

    public void lambda() {
        Function<String,String> fct = s -> s;
        fct.apply("a");
    }

    public void anonymousClass() {
        Function<String,String> fct = new Function<String, String>() {

            @Override
            public String apply(String t) {
                return t;
            }

        };
        fct.apply("a");
    }
}

Here the disassembled code :
public class cli.CompareBoth {
  public cli.CompareBoth();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public void lambda();
    Code:
       0: invokedynamic #2,  0              // InvokeDynamic #0:apply:()Ljava/util/function/Function;
       5: astore_1
       6: aload_1
       7: ldc           #3                  // String a
       9: invokeinterface #4,  2            // InterfaceMethod java/util/function/Function.apply:(Ljava/lang/Object;)Ljava/lang/Object;
      14: pop
      15: return

  public void anonymousClass();
    Code:
       0: new           #5                  // class cli/CompareBoth$1
       3: dup
       4: aload_0
       5: invokespecial #6                  // Method cli/CompareBoth$1."<init>":(Lcli/CompareBoth;)V
       8: astore_1
       9: aload_1
      10: ldc           #3                  // String a
      12: invokeinterface #4,  2            // InterfaceMethod java/util/function/Function.apply:(Ljava/lang/Object;)Ljava/lang/Object;
      17: pop
      18: return
}

We can see that the JVM treat them differently.

What is the actual object that gets implemented ?

As a lambda is created this JVM instruction is performed :

0: invokedynamic #2,  0              // InvokeDynamic
        #0:apply:()Ljava/util/function/Function;

InvokeDynamic that was introduced in Java 7 is specified as a bytecode instruction that facilitates the implementation of dynamic languages (for the JVM) through dynamic method invocation.
You can read this javaworld page to have more information.

Now, does it really matter as you develop ?
In most of cases, it doesn't.
Functional interfaces are functionnaly close to anonymous interfaces with multiple slight differences.
Conceptually, I think that it is acceptable to consider them in this way.
About functional interface immutability :
Functional interfaces may have a state but are designed to be immutable.
So you can reuse them if it makes sense.
But InvokeDynamic may be optimized by JVM.
So you should not reuse them in your code just to spare some objects.
Instead of, extract the functional interface in a constant or a variable because it makes things more clear or it avoids duplication.
Comment: Should we say that lambdas capturing local variables are also stateless?
Comment: @tsolakp Very good remark. Thanks :)
Comment: Thank you very much for this extensive explanation.
Comment: You are welcome. Thanks for the quick accept :)


Is there a big difference between coding for Mobile apps vs Web apps

Question: I am on the cusp of recieving a new project that involves creating a mobile app for android tablets. Is there a large difference in coding for web apps vs mobile apps. And is there any good links I can go to read up on it more? This will be in .Net by the way
Comment: Are you talking about *web applications* targeted for mobile devices or actual native applications for mobile devices?
Comment: I am presumming native applications installed on the device itself?
Comment: are you using [Mono for Android](http://android.xamarin.com/) then? Because I know of no other working solution for using .NET on Android.
Comment: That is the thing I am not sure what I should use.
Answer: Well, obviously both involve coding, so they are quite similar at this level.
But the restrictions that apply to you are quite different.

on a sever application, the size of the libraries you use don't usually make a difference, while the installation size of a mobile app is a definite issue
memory and processing power are usually are less of an issue on the server, as compared to a mobile device
each mobile platform usually has it's own UI framework with quite unique concepts (at least each interesting platform does it its own way)
the APIs are quite different (it's rare to have the same API for server applications and mobile applications)

So yes, there is quite a difference between writing a web-application and writing a native smartphone application.
Comment: ok thank you. This application will be an installed app on the android tablet itself, so I guess this is what is called a native mobile device application correct. I am a quick learner so i want to be able to do this without much downtime. I downloaded MonoDevelop, will this work for creating these native device applications? I know that it will be one specific model that the company uses that these applications will e deployed on.
Comment: @mattgcon: Note that Mono for Android (which I *think* is the new name for MonoDroid) is a commercial application and I don't know of any free way to write .NET code to run on Android. I'd suggest you try to write a "normal" Java android application: You'll have to learn a lot of new APIs anyway and Java really isn't that different from C#.
Answer: Fundamentally coding is coding, but as with anything you are going to be using a different language with android and a different architecture for setting things up. I would suggest reading through the developer documents at developer.android.com and depending on how well you know java maybe do some studying on the basics of java development. www.thenewboston.com helped me a ton when I was first starting to program.


Lilypond finger placement brackets

Question: In music sheets intended for beginner harpists it's very common that the fingering includes not only the numbers but also brackets that indicate which fingers are positioned at the same time, replacements, etc. Here is one example:

I'd like to know what would be the best way to achieve a similar effect in Lilypond.
Ref. for image: http://elizabethlouiseharpist.com/harp-fingerings-brackets-marking-harp-music/
Answer: <code>\version "2.19.52"
variable = {
 \once \override TextSpanner.style = #'line
 \once \override TextSpanner.to-barline = ##f
 \once \override TextSpanner.bound-details =
  #`(
   (left
    (text . ,#{ \markup { \draw-line #'( 0 . -.5) } #})
    (Y . 0)
    (padding . 0.25)
    (attach-dir . -3)
   )
   (right
    (text . ,#{ \markup { \draw-line #'( 0 . -.5) } #})
    (Y . 0)
    (padding . 0.25)
    (attach-dir . 3)
    )
   )
}

\relative c' {
 \key c \major
 \time 3/4
 \partial 4
 \override Fingering.staff-padding = #'()
 \variable
 \once \override TextSpanner.rotation = #'(4 1.9 0)
 a'8_3\startTextSpan b_2 \variable \once \override TextSpanner.rotation = #'(-4.5 -4.5 0)
 c4-1\stopTextSpan\startTextSpan b-2 a_3 \variable \once \override TextSpanner.rotation = #'(3 -0.2 0)
 g_4\stopTextSpan\startTextSpan a_3 b-2 \variable \once \override TextSpanner.rotation = #'(-7 -2.5 0)
 c-1\stopTextSpan\startTextSpan g_2 f_3
 e2_4\stopTextSpan
}
</code>

It's a bit hacky, but it gets the job done.
As always, manual fiddling required to get it the way you want to look. ;)
Answer: One possibility is to include LilyPond's fingering capabilities (<code>-4</code>, for instance, after a pitch) and the analysis bracket capability found at the LilyPond Snippet Repository.
<code>\version "2.19.47"

\layout {
  \context {
    \Voice
    \consists "Horizontal_bracket_engraver"
  }
}
\relative c'' {
  c4-1\startGroup b4-2 a4-3 g4-4\stopGroup |
}
</code>
Comment: Unfortunately this example didn't work for me. First, it's a piano staff and with your example even though I added the code to the first staff the group appeared below the bass clef. Second, for the replacements there is an intersection between different groups and if I start a group and then start another group, stop the first, and then stop the second, the way it was interpreted was a small group inside a larger group.

Lilypond finger placement brackets


Como fazer uma mensagem de carregamento enquanto uma Promisse carrega?

Question: Criei um arquivo js com o seguinte código:

function buscarRepos(){
    lista.innerHTML = '';
    var nomeUser = document.querySelector('div#app input').value;

   var resultado = minhaPromise(nomeUser)
   .then(function(response) {
        for (let url = 0; url < response.length; url++){
            resultado = response[url].html_url;

            var itemList = document.createElement('li');
            itemList.append(resultado);

            lista.append(itemList);
        }
   })
   .catch(function(error) {
     console.warn(error);
   });

   console.log(resultado);
}

var minhaPromise = function(username){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', `https://api.github.com/users/${username}/repos`);
        xhr.send(null);

        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4){
                if (xhr.status == 200){
                    resolve(JSON.parse(xhr.responseText));
                } else {
                    reject("Erro na requisição");
                }
            }
        }
    });
}

Agora preciso que enquanto o resultado dessa Promise carregue, apareça uma mensagem assim no html:

Carregando...

Como faço?
Answer: Você pode por quando a função for chamada:
 lista.innerHTML = '
Carregando...
';

Comment: Muito obrigado pela ajuda!
Comment: Que bom que você gostou das respostas! Mas a melhor forma de agradecer a quem te ajudou é assinalando "aceite" na melhor resposta e votando em todas que te ajudaram. Assim você garante que quem escreveu a resposta receba algo em troca, além de tornar o site mais limpo e útil para todo mundo. Adicionar uma nova resposta assim (que não é uma resposta pra pergunta e deve ser removida) deixa o site mais confuso e pode atrapalhar.
Comment: Certo, sou novo no site, não sabia desse recurso. Passarei a usá-lo de hoje em diante.


How to use Active Report with AngularJs

Question: How to use Active Report with AngularJs
I'm newbie and i can't find tutorial of ActiveReport with AngularJS
how to create active report service and generate report from AngularJS
thanks.
Answer: Please take a look at the following blog post which explains how to use ActiveReports with AngularJS - http://arhelp.grapecity.com/2014/05/28/activereports-8-html5-viewer-and-angularjs/
Comment: Thank, can i export pdf directly not by viewer.
Comment: You can export through javascript. Check the 'export' method at the following documentation link: http://arhelp.grapecity.com/webhelp/AR11/index.html#HTML5WorkingwithViewerUsingJavascript.html

How to use Active Report with AngularJs


Renaming bunch of files with xargs

Question: I've been trying to rename a bunch of files in a proper order using xargs but to no avail. While digging around on piles of similar question, I found answers with the use of sed alongside xargs. Novice me wants to avoid the use of sed. I presume there must be some easier way around.
To be more specific, I've got some files as follows:
Abc.jpg
Def.jpg
Ghi.jpg
Jkl.jpg

and I want these to be renamed in an ordered way, like:
Something1.jpg
Something2.jpg
Something3.jpg
Something4.jpg

Could xargs command along with seq achieve this? If so, how do I implement it?
Answer: I don't know why anyone would try to engage sed for this.  Probably not xargs or seq, either.  Here's a pure-Bash one-liner:
(x=1; for f in *.jpg; do mv "$f" "Something$((x++)).jpg"; done)

At its core, that's a for loop over the files you want to rename, performing a mv command on each one.  The files to operate on are expressed via a single glob expression, but you could also name them individually, use multiple globs, or use one of a variety of other techniques.  Variable x is used as a simple counter, initialized to 1 before entering the loop.  $((x++)) expands to the current value of x, with the side effect of incrementing x by 1.  The whole thing is wrapped in parentheses to run it in a subshell, so that nothing in it affects the host shell environment.  (In this case, that means it does not create or modify any variable x in the invoking shell.)
If you were putting that in a script instead of typing it on the command line then it would be more readable to split it over several lines:
(
  x=1
  for f in *.jpg; do
    mv "$f" "Something$((x++)).jpg"
  done
)

You can type it that way, too, if you wish.
Answer: This is an example of how to find, number and rename jpgs.
Regardless of how you use the find (what options you need. recursive, mindepth, maxdepth, regex, ...).
You can add numbers to find ouput with nl and use number and file as 2 arguments for xargs $1, $2
$ find . -type f -name "*.jpg" |nl| xargs -n 2 bash -c 'echo mv "$2" Something"$1".jpg' argv0

the echo echo mv ...  will show this
mv ./Jkl.jpg Something1.jpg
mv ./Abc.jpg Something2.jpg
mv ./Def.jpg Something3.jpg

Using sort and testing the number of arguments
$ find . -type f -name "*.jpg" |sort|nl| xargs -n 2 bash -c '[ "$#" -eq 2 ] && echo mv "$2" Something"$1".jpg' argv0
mv ./Abc.jpg Something1.jpg
mv ./Def.jpg Something2.jpg
mv ./Jkl.jpg Something3.jpg

Renaming bunch of files with xargs


Ember calling delete action for object in each loop behaves strangely

Question: In ember calling an action to delete from model in a #each always deletes the last object.
{{#each itm in content}}

      {{itm.firstName}} {{itm.lastName}}
      <button {{action delete itm}}>delete</button>

{{/each}}

App.IndexController = Ember.Controller.extend({
actions:{
    delete: function(itm){
        alert("deleting " + itm.firstName + " " + itm.lastName)
        this.content.popObject(itm);
    }
}
});

it seems like when I delete the object ember gets lost in his action references and always deletes the last item!
but the alert box gives me the right data.
here is a fiddle cause I find this hard to explain: http://jsfiddle.net/jmorvan/ap4qD/
Am I doing something terribly wrong?
Answer: You can use this.content.removeObject(itm); Worked in the jsfiddle you provided.
Comment: thanks @claptimes! do you happen to know why its acting weird with `popObject`? they both achieve the same goal in the end! must be some more wiring done in `removeObject` then?
Comment: They are different. Take a look at the [docs](https://github.com/emberjs/ember.js/blob/v1.3.0/packages/ember-runtime/lib/mixins/mutable_array.js#L188) `popObject` removes the last element of the array.
Comment: Here's the [docs](https://github.com/emberjs/ember.js/blob/v1.3.0/packages/ember-runtime/lib/mixins/mutable_array.js#L188) for removeObject. Hope this helps!
Comment: thanks! I should have checked this! this was so stupid/lazy of me! thanks again!


Intuition behind the expectation of a conditional expectation

Question: Let $(\Omega, \cal F, P)$ be a probability space and $X,Y$ two random variables defined on $(\Omega, \cal F, P)$. I stumbled upon the equality $$E[E(X \vert Y)]=E(X)$$
Observing that
$$\begin{align}
E[E(X \vert Y)] & =\sum_iP(Y=Y_i)E(X\vert Y_i) \\
& = P(Y=Y_1)E(X \vert Y_1)+...+ P(Y=Y_n)E(X\vert Y_n) \\
&=E(X)
\end{align}$$
it "mathematically" makes sense to me, but still not intuitively. How does one intuitively recognise that the expectation of a random variable equal the expectation of an expectation of that random variable given some information?
Answer: $E(X)$ is the expectation of $X$, whatever $Y$. You can also express it as a weighted average of the expectations of $X$ for given $Y$, where the weights are the probabilities of the respective values of $Y$.
E.g. we have the drawings
$$(1,1),(1,2),(2,1),(2,2)$$ with respective probabilities $0.1,0.2,0.3,0.4$.
The expectation of $X$ is
$$1\cdot0.1+1\cdot0.2+2\cdot0.3+2\cdot0.4=1.7$$
The marginal probabilities of $Y$ are $0.4, 0.6$.
The conditional probabilities of $X$ are
$$Y=1\to 0.25,0.75,\\Y=2\to 0.33,0.67.$$
The conditional expectations of $X$ are
$$Y=1\to 1\cdot0.25+2\cdot0.75=1.75,\\Y=2\to 1\cdot0.33+2\cdot0.67=1.67.$$
and indeed,
$$1.75\cdot0.4+1.67\cdot0.6=1.7.$$
Answer: There are many ways of explaining this intuivitely, I will use the equalities you provided, stick to the discrete case and won't go much into the machinery of probability theory.
I claim that the sum
$$\sum_i P(Y=Y_i)E(X|Y_i)$$
is essentially just the expected value of $X$ - a weighted average of all values of $X$ - in disguise. It is only matter of how the space $\Omega$ is partitioned.

$E(X)$
To see that, let's see what $E(X)$ does:
$$E(X) = \sum_i  P(X = X_i)  X_i$$
Think of the event $[X=X_i]$ as a set of all cases (all the $\omega$s) where $X(\omega) = X_i$. These events form a partitioning of $\Omega$ in that they are disjoint sets that add up to $\Omega$.
In $E(X)$ we are therefore looking at the value of $X$ on the set $[X=X_i]$ and weighting it with the size of the set, $P(X=X_i)$.

$E(E(X|Y))$
Now in your case:
$$\sum_i P(Y=Y_i)E(X|Y_i)$$
Here, we are looking at the value of $X$ on the set $[Y=Y_i]$. But we can't just write $X_i$, since $X$ does not have to have the same value on all $\omega \in [Y=Y_i]$. Thus we have to average over all the cases in $[Y=Y_i]$, which is precisely what $E(X|Y_i)$ is. Then we just multiply this with the size of the set, which is $P(Y=Y_i)$.
In both cases, we are just aggregating the $\omega$s in different ways. In $E(X)$, it's over the sets $[X=X_i]$, in $E(E(X|Y))$, it's over the sets $[Y=Y_i]$.


Keras data augmentation layers in model or out of model

Question: How exactly do the preprocessing layers in keras work, especially in the context of as a part of the model itself? This being compared to preprocessing being applied outside the model then inputting the results for training.
I'm trying to understand running data augmentation in keras models. Lets say I have 1000 images for training. Out of model I can apply augmentation 10x and get 10000 resultant images for training.
But I don't understand what's happening when you use a preprocess layer for augmentation. Does this (or these if you use many) layers take each image and apply the transformations before training? Does this mean the total number of images used for training (and validation I assume) to be the number of epochs*the original number of images?
Is one option better than the other? Does that depend on the number of images one originally has before augmentation?
Answer: The benefit of preprocessing layers is that the model is truly end-to-end, i.e. raw data comes in and a prediction comes out. It makes your model portable since the preprocessing procedure is included in the SavedModel.
However, it will run everything on the GPU. Usually it makes sense to load the data using CPU worker(s) in the background while the GPU optimizes the model.
Alternatively, you could use a preprocessing layer outside of the model and inside a Dataset. The benefit of that is that you can easily create an inference-only model including the layers, which then gives you the portability at inference time but still the speedup during training.
For more information, see the Keras guide.
Comment: Okay I understand. What I still can't figure out is what's happening with the data augmentation if I put it as a preprocessing layer inside the model. Does it take my original images and generate a new batch every epoch? Does it augment the images once (or multiple times) then train?
Comment: No batching happens before - for example, `keras.Model.fit` allows passing a batch size. The data flow is still per batch, but with preprocessing layers your raw data comes in instead of preprocessed. Also, the preprocessing layers can generate multiple channels though, depending on how you set it up.
Answer: I had the same question. Essentially there are two recommended ways of applying augmentation:

To the model pipeline. Here, the initial layers will be the augmentation and the latter layers the neural network.

    model = tf.keras.Sequential([
        tf.keras.layers.Input(shape=(512,512,3)),
        tf.keras.layers.Rescaling(scale=1/255.0),
        tf.keras.layers.RandomFlip(),
        tf.keras.layers.RandomRotation(factor=0.5),
        tf.keras.layers.Conv2D(256, kernel_size=(5, 5), padding='valid', activation='relu'),
        tf.keras.layers.MaxPool2D(pool_size=(2, 2)),
        tf.keras.layers.Dropout(rate=0.2),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dense(1, activation='sigmoid')
    ])

In this method, the number of images remains the same as before. Augmenting changes the image style, but each layer only runs once per image. I couldn't find any concrete documentation for it, but creating a model only consisting of augmentation proved the same.
augmentation_layer = tf.keras.models.Sequential([tf.keras.layers.RandomRotation(factor=0.5)])

nrows = 4
ncols = 4

fig = plt.gcf()
for images, labels in training_set.as_numpy_iterator():
    augmented_images = augmentation_layer(images)
    break

for i, image in enumerate(augmented_images):
    sp = plt.subplot(nrows, ncols, i+1)
    plt.imshow(image/255.0)
    plt.suptitle('Augmented Images')

for i, image in enumerate(images):
    sp = plt.subplot(nrows, ncols, i+1)
    plt.imshow(image/255.0)
    plt.suptitle('Actual Images')

PS: The training_set is a _PrefetchDataset created from tf.keras.utils.image_dataset_from_directory. You may have to edit the code to get it to work with your dataset.
The results show that for each actual image, only one transformation is applied.
This method is great if you have lots of data and so do not need to increase the dataset size. If however, you wish to create additional data, then option 2 is better:

Applying augmentation before and then adding it into the model. In this case, you will need to run the augmentation multiple times on the same image, using a loop. You can keep adding the augmented images back to the source dataset.


Apache not showing a test page when I browse to the server running it

Question: I have set up a CentOS 5.5 server with Apache on it. The httpd service starts just fine (no warnings at all), and I was under the impression that I should see an Apache test page if I was to browse to the server via Firefox or the like (not localley, from a different machine), when no virtual hosts exist?
I have set the HOSTNAME entry in /etc/sysconfig/network, added the FQDN to /etc/hosts, and set the ServerName in etc/httpd/conf/httpd.conf (DocumentRoot is set to /var/www/html).
Is there anything I have missed, or am I barking up the wrong tree completly? Thanks.
Comment: What happens when you try to open test page? Any chance that iptables is blocking requests on server with httpd?
Comment: Did you open port 80 in your firewall?
Comment: Sorry Andrei, not sure what you mean? Server is called monitor, with IP 192.168.1.16, and have tried both `http://monitor` and `http://192.168.1.16`, both of which show the standard 'Unable to display your webpage' error. Is that what you meaning? Thanks.
Comment: Can you get to any other services on the machine? SSH for instance.
Comment: What does `netstat -plnt |grep httpd` output?
Comment: look in the apache log /var/log/apache2/ I imagine
Comment: check /var/log/httpd/error.log and /var/log/httpd/access.log
Answer: You say you're getting "webpage cannot be displayed", not "server cannot be reached", so I think that Apache is responding on port 80, but check to see if something like wget http://localhost/ (or links http://localhost) gives you something different. If so, you have a firewall issue. Do you have iptables enabled, and are you blocking port 80? If so, edit /etc/sysconfig/iptables to allow port 80 access, and then service iptables restart.
Assuming Apache IS responding on port 80 to other computers...
CentOS shows the welcome page for an empty vhost directory by default when you:

Have the Include conf.d/*.conf line in httpd.conf.
Have an /etc/httpd/conf.d/welcome.conf that contains:

    Options -Indexes
    ErrorDocument 403 /error/noindex.html

And /var/www/error/noindex.html exists and is readable by the webserver.

So, I would check all three of those things, once you're sure Apache is responding on port 80.


How to make reply of an email becomes a HttpRequestServlet to a web application?

Question: I got a requirement which I don't know how to get started.
Requirement:
The application will send emails to clients (using org.springframework.mail.javamail.JavaMailSender) with same "from email address" as email@example.com. Also the email content will have some hidden information such as client_id. If the client reply back to that email, I need to get that as an HttpServletRequest to a Servlet so that I can process it.
EDIT:
This web application does not have google app engine setup, but my requirement is matching similar to this link.
Answer: When someone replies to the mail you sent him that mail will go to the POP3 server configured for your domain. From this SMTP server you can read this mail using the Java Mail API. You can have a Spring timer task to keep polling this mailbox after every few seconds.
I would look at the below resources to see how to read mail from the POP3 server -
Using JavaMail API -
http://metoojava.wordpress.com/2010/03/21/java-code-to-receive-mail-using-javamailapi
Using Spring -
http://blog.solidcraft.eu/2011/04/read-emails-from-imap-with-spring.html
Comment: POP3 does not have to have anything to do with it in general.
Answer: Better and popular solution is to have a link in your email and asking user to click it and asking specifically not to reply to this email (from address can be firstname.lastname@example.com)
For getting a servlet call in an email reply, you need to use
http://javamail.kenai.com/nonav/javadocs/com/sun/mail/pop3/package-summary.html
Keep polling for new emails in your reply address(for  eg firstname.lastname@example.com) using POP, and when new email comes trigger a httprequest(HttpClient? ).
On a related note you can add user_id and similar stuff using a + in reply email address
For eg email@example.com and firstname.lastname@example.com will deliver to same address. Everything after + is ignored. But you will get this info in reply email event as to address and decide on who is the user.This could be a security concern for sure if not properly implemented.


"protected by reCAPTCHA" message in browser at PC startup

Question: Starting yesterday, right after starting my Windows 10 PC I see that some process has opened two tabs in Google Chrome with the following URL and message:
https://www.recaptcha.net/recaptcha/api2/anchor?ar=1&k=6LcXnG8cAAAAAMdaeQXuMG01hTwMaFO5V3VlS354&co=aHR0cHM6Ly9sb2dpbi5nb2cuY29tOjQ0Mw..&hl=en&v=-TriQeni1Ls-Mdq_ssN2cUL5&size=invisible&cb=h2s63l1gv2zl

Is anyone else experiencing this? Any suggestions for how to detect the service that is causing this would be hugely appreciated. So far, my anti-virus go-to tools (Microsoft built-in threat detection, and Hitman Pro) have not been able to remove whatever causes these.
I'm running Windows 10 21H1 (OS Build 19043.1266)
Thanks so much!
Comment: I can only add that this has happened to a few of us, on different browsers. Seems to have started a few days ago. https://www.reddit.com/r/chrome/comments/pxercn/weird_recaptcha_link_on_startup/
Comment: Thank you for your reply, Roberto. The cause on my PC turned out to be the GOG.com Galaxy application. Once I stopped that one service from starting automatically, the behavior I described stopped.
Answer: I had the same issue, apparently caused by MinerGate uninstall registry leftovers... In the task manager in startup I had an app called "Program" but it was not possible to open the location.
If you select in the header of startup manager the "Startup type" and "command line" view you will see what cause this, and in my case it was this old app I installed once to see what it was about ages ago.
I don't understand why it behaved this way suddenly (I hope it wasn't a malware afterall). After deleting all the related keys in the registry it solved my problem, and this "Program" doesn't appear anymore in my startup list.
Comment: Thank you for suggesting to check the Startup tab of the Task Manager. The GOG.com Galaxy app caused the two calls that fired up Chrome on each machine boot. After disabling that app from starting on Startup, I do not see the two Chrome tabs pop up any longer.
Comment: Thank you again for your answer and your help! Much appreciated.
Answer: updating GOG.com Galaxy application to v2.0 solved the issue in my case.


Track key press and key release on WPF applications

Question: Is there a way to track key press and release actions on WPF?
This is what I've tried so far, but what I'm finding is that the <code>_upDownKeyIsPressed</code> is only set to false if I press another key - not when the up or down key is released
<code>    private void KeyUpPress(KeyEventArgs e)
    {
        if (e.Key == Key.Up || e.Key == Key.Down)
        {
            _upDownKeyIsPressed = true;
            Console.WriteLine(_upDownKeyIsPressed.ToString());
        }
    }

    private void KeyDownPress(KeyEventArgs e)
    {
        if (e.Key == Key.Up || e.Key == Key.Down)
        {
            _upDownKeyIsPressed = false;
            Console.WriteLine(_upDownKeyIsPressed.ToString());
        }
    }

    private void PlotListView_KeyUp(object sender, KeyEventArgs e)
    {
        KeyUpPress(e);
    }

    private void PlotListView_KeyDown(object sender, KeyEventArgs e)
    {
        KeyDownPress(e);
    }
</code>
Comment: Maybe you should put it to `true` on KeyDown and to `false` on KeyUp.
Comment: I added a real answer to the problem. Did it help ?
Answer: If you want to try what I said in comment. I think about something like this :
<code>    private void PlotListView_KeyUp(object sender, KeyEventArgs e)
    {
        TrackUpDownKeyPress(e, false);
    }

    private void PlotListView_KeyDown(object sender, KeyEventArgs e)
    {
        TrackUpDownKeyPress(e, true);
    }

    private void TrackUpDownKeyPress(KeyEventArgs e, bool isPressed)
    {
        if (e.Key == Key.Up || e.Key == Key.Down)
            _upDownKeyIsPressed = isPressed;
    }
</code>
If you want more info about the difference between keyUp and keyDown, check this question.


How to force dynamically loaded MVC controllers to take particular MasterName

Question: Consider we have some compiled class libraries which contain some Controllers and relevant Views, that called Plugins.
in other side we have an web MVC application which loads plugins at run-time and renders existing embedded views and controllers by WindsorControllerFactory.
 [Transient]
///
/// Controller Factory class for instantiating controllers using the Windsor IoC container.
///
public class WindsorControllerFactory : DefaultControllerFactory
{
    private IWindsorContainer _container;

    ///
    /// Creates a new instance of the <see cref="WindsorControllerFactory"/> class.
    ///
    /// <param name="container">The Windsor container instance to use when creating controllers.</param>
    public WindsorControllerFactory(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        _container = container;
    }

    protected override IController GetControllerInstance(RequestContext context, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.", context.HttpContext.Request.Path));
        }

        return (IController)_container.Resolve(controllerType);
    }

    public override void ReleaseController(IController controller)
    {
        var disposable = controller as IDisposable;

        if (disposable != null)
        {
            disposable.Dispose();
        }

        _container.Release(controller);
    }
}

my problem is that when I call an action from a plugin it renders page without setting Layout and it's empty!
i want to set Layout some constant value for every views of actions in my plugins. for example Layout = "~/Views/Shared/_Layout.cshtml".
Notice1 that the _ViewStart.cshtml fire up by every action call views in main MVC application, but it does not from calls in plugins.
Notice2 that i don't want to set layout on the plugin side,
neither specify MasterName on calling plugins controller's view (return View(model,"SomeMasterName")), nor specifying Layout in plugin's Views such as :
@{
    Layout = "~/Views/Shared/MyPluginLayout.cshtml";
}

Answer: This should be set inside your VirtualPathProvider which serves embedded Views. Your VirtualPathProvider offers a VirtualFile through GetFile(string virtualPath) method.
public VirtualFile GetFile(string virtualPath)
{
    return this.IsEmbeddedFile(virtualPath) // this one you should handle by yourself
            ? new EmbeddedVirtualFile(new FileInfo(virtualPath), virtualPath)
            : null;
}

A possible implementation for  your VirtualFile can be as follows:
public class EmbeddedVirtualFile : VirtualFile
{
    private string LayoutPath = "~/...yourpath to the Layout"
    private readonly string _virtualPath;

    public EmbeddedVirtualFile(string virtualPath) : base(virtualPath)
    {
        this._virtualPath = virtualPath;
    }

    public override Stream Open()
    {
        var stream = File.Open(this.fileInfo.FullName, FileMode.Open);
        if (_virtualPath.EndsWith(".cshtml"))
        {
            var streamFixed = CorrectView(_virtualPath, stream);
            return streamFixed;
        }
        return stream;
    }

    private Stream CorrectView(string virtualPath, Stream stream)
    {
        var reader = new StreamReader(stream, Encoding.UTF8);
        var view = reader.ReadToEnd();
        stream.Close();
        var ourStream = new MemoryStream();
        var writer = new StreamWriter(ourStream, Encoding.UTF8);
        // Here you may add some @usings like writer.WriteLine("@using System.Web.Mvc");
        // partial views should not have a layout & viewStart/_Layout either
        if (!string.IsNullOrEmpty(LayoutPath) && !virtualPath.Contains("/_") && !virtualPath.Contains("_viewstart") && !virtualPath.Contains("_Layout"))
        {
            writer.WriteLine(string.Format("@{{ Layout = \"{0}\"; }}", LayoutPath));
        }
        writer.Write(view);
        writer.Flush();
        ourStream.Position = 0;
        return ourStream;
    }
}

Of course you can take care of LayoutPath variable and pass it from your VirtualPathProvider depending on your plugin _Layout.


Hermitian metric on $L=\mathcal{O}_{\mathbb{P^n}}(1)$ over the projective space

Question: Consider the line bundle $L=\mathcal{O}_{\mathbb{P^n}}(1)$ over the projective space. Locally is descriebd by $\{U_a,g_{ab}\}$ where $U_a=\{z_a\neq0\}$ is the standard covering of the projective space.
A Hermitian metric on $L$ can be given locally as a smooth function $h_a:U_a\rightarrow\mathbb{R_{>0}}$, satisfying $h_a =|g_{ba}|^2 h_b.$
My question is: how can we define $h_a$ locally? For example if we choose  $h_a=\frac{1}{|z_a|^2}$ ,which satisfies $h_a =|g_{ba}|^2 h_b$, then $h_a$ is not well-defined on the homogeneous coordinates.
I would appreciate any help on this.
Answer: The line bundle $L$ is given by the data $\{U_{\alpha\beta}, g_{\alpha\beta}\}$, where $\alpha, \beta = 0, 1, \cdots, n$,
$$U_\alpha = \{ z_\alpha \neq 0\}\ \ \text{ and }\ \ g_{\alpha\beta} = \frac{z_\beta}{z_\alpha}.$$
If we set $h_\alpha : U_\alpha \to \mathbb R_{>0}$, where
$$h_\alpha = \frac{|z_\alpha|^2}{|z_0|^2 + \cdots + |z_n|^2},$$
then $h_\alpha$ is well defined and $h_\alpha |g_{\alpha\beta}|^2=  h_\beta$. Thus it's a Hermitian metric on $L$.
Note that this metric is the most natural one on $L$: First we consider $L^*$, which can be described as the tautological line bundle
$$L^* = \{ (\ell, v) \in \mathbb P^n \times \mathbb C^{n+1} : v\in \ell\}.$$
Notice that $L^*$ has a natural Hermitian metric $\tilde h$: on each fiber $\ell \subset \mathbb C^{n+1}$, we restrict the Hermitian metric of $\mathbb C^{n+1}$ to $\ell$. So if on each $U_\alpha$,
$$e_\alpha = \left( \frac{z_0}{z_\alpha}, \frac{z_1}{z_\alpha}, \cdots, 1, \cdots \frac{z_n}{z_\alpha}\right)$$
is a basis for $L^*$ and
$$\tilde h_\alpha = \tilde h(e_\alpha, e_\alpha) = \frac{|z_0|^2 + \cdots + |z_n|^2}{|z_\alpha|^2}.$$
Thus $h_\alpha = \tilde h_\alpha^{-1}$ is a Hermitian metric on $L$.
Comment: thank you for your answer. I have a quick question: If $h_\alpha$ is defined as above then it does not satisfy $h_\alpha=|g_{\alpha\beta}|^2 h_\beta$ with $g_{\alpha\beta}=z_\beta / z_\alpha.$ How can we fix that?
Comment: Ok, I think the relation should be $h_\alpha |g_{\alpha\beta}|^2=h_\beta$ where $g_{\alpha\beta}=z_\beta / z_\alpha.$ This is because you must have that $|s_a|^2 h_a=|s_b|^2 h_b$ and since $s_b=g_{ba}s_a$ you get this relation.  Now everything make sense. Thanks for the help


How to return the result of a promise in a function

Question: I'm really confused about why I can not return the JSON result from amazonMws.products.search() and could use some help understanding what is going on. When I write it this way gives me undefined:
function listMatchingProducts(query) {
    const options = {
        Version: VERSION,
        Action: 'ListMatchingProducts',
        MarketplaceId: MARKET_PLACE_ID,
        SellerId: SELLER_ID,
        Query: query
    }

    amazonMws.products.search(options, (err, res) => {
        if(err){
            throw(err)
            return
        }

        return res
    })
}

I also get undefined when using amazonMws.products.search().then().catch() as well.
If I return amazonMws.products.search() I get a promise back instead of the result.
Inside of the callbacks if I console.log(res) I get back the JSON result I'm expecting. So this led me to believe I need to use async await I think, but this results in Promise { <pending> }:
async function listMatchingProducts(query) {
    const options = {
        Version: VERSION,
        Action: 'ListMatchingProducts',
        MarketplaceId: MARKET_PLACE_ID,
        SellerId: SELLER_ID,
        Query: query
    }

    return await amazonMws.products.search(options)
    .then(res => {
        return res
    })
    .catch(e => errorHandler(e))
}

I am totally lost, so if someone could explain to me what is going on, that would be greatly appreciated.
Comment: It's asynchronous. You cannot get a value from the future. A promise for it is the best you will get. At the place where you're calling this, wait for it.
Comment: Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)
Answer: The amazonMws.products.search function is asynchronous, meaning that it will give you a value later, and because of this, you can't get the value now. Instead, you'll have to say what you want to do later when you receive the value.
This is what returning the promise does. The promise itself is the representation of this value that you'll receive later.
function listMatchingProducts(query) {
    const options = {
        Version: VERSION,
        Action: 'ListMatchingProducts',
        MarketplaceId: MARKET_PLACE_ID,
        SellerId: SELLER_ID,
        Query: query
    }

    return amazonMws.products.search(options)
}

Then, when calling the function, attach a handler to the promise.
listMatchingProducts(someQuery)
  .then(result => {/* do something with result */})
  .catch(error => {/* handle the error */})

And, though you don't need to use async await here, it can make the code look a little nicer in some situations, as though it were synchronous. Here's what calling the above function would look like with async await:
async function getProducts() {
  try {
    const result = await listMatchingProducts(someQuery)
    // do something with result
  } catch (error) {
    // handle the error
  }
}

And, as usual, always consult the docs for any detail you're confused about:

Using promises
await keyword
Comment: You can't return the value like you would normally from another function, because the returned value doesn't exist until later. You have to return the promise and use that.
Comment: In the API it says I can use promises, or callbacks. But when I use `amazonMws.products.search(options, (err, res) => { return res; })` I still get a promise returned. How do I simply return the JSON?
Answer: function listMatchingProducts(query) {
    const options = {
        Version: VERSION,
        Action: 'ListMatchingProducts',
        MarketplaceId: MARKET_PLACE_ID,
        SellerId: SELLER_ID,
        Query: query
    }

    return amazonMws.products.search(options); //returns a promise
}

Answer: As others have pointed out, Promises just don't work the way you think they do.
See my answer to function returning too early before filter and reduce finish for a (hopefully) clear explanation  of the problem you face.


Auto rotation of UIImageView subviews

Question: Root view is a UIImage View, it has subviews, those have subviews. My root view will open in landscape i have set both project properties in the project's .plist and have integrated application.statusBarOreintation in applicationDidFinishLaunching and verified that it works.
But all of my subviews are appearing in portrait. How do I change this on my subviews?
Thanks
// :)
Answer: Do you have a viewcontroller?  What is your shouldAutorotateToInterfaceOrientation returning?
<code>// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
            (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
</code>
Without a viewcontroller, you will have to apply a transform to rotate each view you load.

Auto rotation of UIImageView subviews


Como escrever códigos como exemplo, sem executar?

Question: Eu to fazendo a tradução de um livro para uma página HTML, ai no livro tem os códigos, mas como eu faço para o meu HTML exibir o meu código, HTML, PHP e JavaScript, sem executa-los?
Comment: Onde você está fazendo esse texto? HTML puro? Algum framework para blogs como wordpress, por exemplo?
Comment: Aqui tem um site para ajudar a modificar o html para texto: http://blogcrowds.com/resources/parse_html.php
Comment: Caso use jQuery pode fazer isso `$('pre').text( $('pre').html() );`.
Answer: Você precisa escapar os caracteres que fazem suas tags serem interpretadas como HTML, o < e o >.
Por exemplo, em vez de:

Teste

use:
<div>Teste</div>

Se está usando PHP, existe uma função que faz isso, a htmlentities:
echo htmlentities('
Teste
');

http://ideone.com/DEZduB
No caso de código PHP, basta dar saída dele sem o <?php inicial, e ele não será interpretado. Caso queira incluir o <?php no exemplo, use <?php.
Comment: Eu pensei em indicar algum plugin que mostre códigos, tipo esse: http://alexgorbatchev.com/SyntaxHighlighter/manual/demo/
Comment: Sim @EstácioDiFabio, o jQuery irá pegar o html `$('pre').html()` e transformar em texto `$('pre').text()`. A tag `pre`, respeita "tudo" que estiver dentro dela, no caso os espaços em branco (não precisa usar ` `) e quebras de linhas (não precisa usar ``).
Comment: Isso mesmo dessa forma funciona super bem. Eu utilizo o plugin Highligth.js para exibir os códigos porém ele executa com as tags < >  . Alterar o primeiro "<" que o navegador não irá renderizar, fica bem mais rápido (:.
Comment: KaduAmaral - isso irá escrever o que tá dentro da tag  como código html, sem executar?
Answer: Voce pode usar
<xmp>

Blah teste

</xmp>

A tag xmp não precisa usar caracteres de escape.
 O resultado será:

Blah teste

Comment: Interessante isso, eu não conhecia. Porém encontrei documentação dizendo que [é um recurso obsoleto que pode ser removido dos browsers](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/xmp).
Comment: essa é uma ótima técnica, mas dentro das tags     olar mundo    . O navegador renderiza todo o código por trás dos  e . Mas se for somente para HTML puro funciona super bem. Uma pena mesmo ser obsoleto.
Comment: @RenaroSantos saquei, mas mesmo obsoleto é uma ótima dica, também não conhecia (+1)
Comment: Sim, pode ser descontinuada no futuro, mas por enquanto é a solução mais simples. Um pena ser obsoleto. =)
Comment: Não é a solução mais simples o próprio site fala pra usar  ou
Comment: eu dava +1 mas com esses comentários não dá. Também não conhecia.
Comment:  ou  não funcionam neste caso @AdirKuhn
Answer: Podes usar a tag pre e jQuery:

jQuery(document).ready(function($) {
   $('pre').each(function(index, el){
     $(this).text( $(this).html() );
   });
});
pre{
  background-color: rgba(0,0,0,0.08);
  border-left: 3px solid rgba(0,0,0,0.4);
  margin: 0;
  padding: 4px 6px;
}

pre.php::before{
  content: '<?php';
  display:block;
  margin:0 0 2px -3px;
}
pre.php::after{
  content: '?>';
  display:block;
  margin:2px 0 0 -3px;
}

hr{margin 7px 0; border-color: #999;}

      Teste da tag
      pre

   $var = 'Hello World!';

   if (1 == 1)
     echo $var;

Porém no caso do PHP, caso também esteja utilizando-o no lado do servidor, terá omitir a tag de abertura <?php (pode fazer a emissão dela por CSS).
Answer: Eu cai aqui primeiramente por que tinha a mesma duvida "como exibir php na página sem executar".
Acabou que eu não gostei das soluções propostas aqui e fui fazendo testes por conta própria e a solução não poderia ser mais simples.
Basta apenas dar um 'ECHO' no conteúdo PHP que quer exibir, exemplo:

<?php
  echo "
    <?php
      function teste(valor) {
        alert(valor);
      }
      //Chamando a função
      teste('Deu certo');
    ?>
  ";
?>

Espero que seja útil, abraços


Como funciona chave estrangeira em c#?

Question: Tenho duas tabelas Contato(Homem) e Mulher.
O homem pode ter várias mulheres e uma mulher é para um homem.
<code> public class Contato {
    public int id { get; set; }
    public String usuario { get; set; }
    public String nome { get; set; }
    public String senha { get; set; }
    public List<Mulher> listaMulher { get; set; }
}

  public class Mulher
  {
    public int idM { get; set; }
    public Contato id { get; set; }
    public String nome { get; set; }
    public String formacao { get; set; }

  }
</code>
Seria dessa forma?
Mas e a mulher como posso adicionar uma chave para a mulher? Como ficaria isso na classe main?
Comment: Se você está fazendo um *framework* de acesso a BD *inhouse* cabe a você definir a API. Caso contrário você vai ter que escolher um *framework* existente. Aí depende de você para decidir o que melhor atente, existem várias opções, EF, NHibernate, Dapper, etc. Pesquise e  depois adicione detalhes a pergunta.
Comment: Só para confirmar, você está usando EF, certo?
Comment: O que é EF??????????
Comment: [Entity Framework](https://www.asp.net/entity-framework). Se não está usando, tem que nos dizer qual tecnologia pretende usar.
Comment: Não estou usando e não pretendo usar. Aqui no momento só estou fazendo tudo na mão mesmo...
Answer: Em um Relacionamento um para muitos
Data Annotations
<code> public class Student
    {
        public Student() { }

        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public int StdandardRefId { get; set; }
        [ForeignKey("StandardRefId")]
        public virtual Standard Standard { get; set; }
    }

    public class Standard
    {
        public Standard()
        {
            StudentsList = new List<Student>();
        }
        public int StandardId { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }
</code>
em  Fluent API
<code> protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            //configure one-to-many
            modelBuilder.Entity<Standard>()
                        .HasMany<Student>(s => s.Students) Standard has many Students
                        .WithRequired(s => s.Standard)  Student require one Standard
                        .HasForeignKey(s => s.StdId);Student includes specified foreignkey property name for Standard
    }
</code>
fonte:http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
Comment: Isso aí é o que? Vc está usando entity framework?
Comment: sim entity framework, mas segunda opção serve também para mapeamento do Fluent Hibernate
Comment: Mas considere a pergunta sem a utilização de Entity framework pq aqui na empresa eles não utilizam.
Comment: pensando como orientação objeto é mesma coisa so ultima parte que não existe

Como funciona chave estrangeira em c#?


Using jQuery to include/require a different php file if window height > 1000?

Question: How can you use jQuery to include/require a different php file if window height > 1000?
if window height > 1000

    <?php require('a.php'); ?>

else

    <?php require('b.php'); ?>

Answer: you can't require like php in JavaScript/jQuery. Instead of that you can use .load(). It will load an script using AJAX.
For example:
if( $(window).height() > 1000 ) {
  $('#result').load('a.php', function() {
      alert('a.php load was performed.');
  });
} else {
  $('#result').load('b.php', function() {
      alert('b.php load was performed.');
  });
}

But If you want to reload page then you need window.location ie.
window.location = "some_url";

Answer: You can detect the width and height in javascript and then redirect the page to your actual page.
location.href="myRealPage.php?height="+clientheight;

Then you can use these variables on the server to decide which page to load.
if($_GET["height"]>1000)
{
   require("a.php")?
}
else
{
   require("b.php")?
}


C++ Why use an implicit conversion from (std::string) to (void) type?

Question: I'm looking at CPP-NETLIB's source code and came across this syntax where it describes the concepts.
<code>template <class R> struct ClientRequest : network::Message<R> {
  BOOST_CONCEPT_USAGE(ClientRequest) {
    std::string tmp;
    R request_(tmp);
    swap(request, request_);  // swappable via ADL

    std::string host_ = host(request);
    boost::uint16_t port_ = port(request);
    std::string path_ = path(request);
    std::string query_ = query(request);
    std::string anchor_ = anchor(request);
    std::string protocol_ = protocol(request);

    request << uri(std::string());

    network::http::uri(request, std::string());

    (void) host_;
    (void) port_;
    (void) path_;
    (void) query_;
    (void) anchor_;
    (void) protocol_;
  }

 private:
  R request;
};
</code>
I can't seem to find any explanations that describe how the (void) conversion of in-scope types could be necessary or what it would do. Why would you need to clear the stack before ending the BOOST_CONCEPT_USAGE member function? What else would it do if not clearing the stack?
Comment: It's *explicit*, not implicit...
Comment: and it will not clear the stack.
Comment: Define an macro to do it and name it as "UNUSED_VARIABLE", will fully resolve this confuse.
Answer: It's just for suppressing the compiler's warnings about unused variable, nothing special.
It does NOT clear the stack in any way, if that's what you mean.
Comment: @etcimon - nothing is about saving here. `(void)host_;` does not change save anything into `host_`, too. The warning is for `unused parameter/variable` - making `(void)host_;` you actually _use_ it - so this suppresses the warning.
Comment: @NemanjaBoric `BOOST_CONCEPT_USAGE` I think the name says enough :)
Comment: I'm a bit confused about it. For host_, the equivalent to (void)host_ is static_cast(host_) here but correct my reasoning: the reason it doesn't suppress anything is because the value isn't saved back into host_?
Comment: I went to get some groceries, and I couldn't stop thinking about this... What could be the possible usage of this? I mean, why programmer just didn't comment out the lines?
Comment: @NemanjaBoric - If these lines are removed, then there will be warnings and some projects are compiled with the `-Werror`flag, which means - each warning is considered an error and then the compiling process will fail. There are other ways to avoid this, but it depends on the situation (for example, you may have `void f( int ) { ... }` (note the missing name of the parameter)
Comment: @KirilKirov Yes, I understand that, but I don't understand `std::string protocol_ = ...`. Will  this actually generate fields?
Comment: @NemanjaBoric - what fields? This looks like an example for me. I have no idea what is this function, but maybe it demonstrates something and it's expected, that `protocol_` and the others will be used later for something. The useless may be removed, things like this. I don't know what's the idea, could be just demonstrating the API or something.
Comment: @KirilKirov I think you're right. I just thought `BOOST_CONCEPT_USAGE` is doing some code-generation magic, as I can't find lot of docs on that.


Propositional formula, consisting of $p, q, r$ is true iff only one of them is true

Question: I have some difficulties in building a formula $\phi(p, q, r)$, which is true iff only one of the variables is true.
I suppose that it's reasonably to start trying, using the truth table, but building a formula from it actually seems to be a tough job.
In some point of view, the exact formula should contain the $\oplus$ function - for example, $a_{1} \oplus a_{2} \oplus \ldots \oplus a_{n} $ is true iff formula consists only of an odd number of true variables.
Could somebody give me a clue, how to cope with it?
Comment: 'Exactly one' or just 'one'?
Comment: Exactly one variable.
Answer: The simplest formula is obviously, $$ ( p \land \lnot q\land \lnot r) \lor ( \lnot p \land \lnot q\land  r) \lor ( \lnot p \land q\land \lnot r) $$
Maybe there is a more succinct and elegant formula but I can't seem to unearth it.
Comment: My answer [here](http://math.stackexchange.com/questions/938364/how-would-i-go-from-dnf-to-a-simplified-formula-with-less-symbols/938388#938388) provides ways to simplify the statement.
Answer: As you observe, $p\oplus q\oplus r$ is true when only one of the variables is true, or when all three are true. Therefore, $(p\oplus q\oplus r) \wedge \neg(p\wedge q\wedge r)$ would fit your needs.