Image Upload Not Working (Froala Editor)

Question: I have read the Froala Help Docs  over 10 times now. I still can't get it to work :(
When I click the upload icon in my editor and select an image to upload, nothing happens. The dialog box that asks you to choose an image pops up, and after selecting the image, it dismisses but nothing happens on the page afterwards.
It's definitely something wrong with my code. However, I can't figure out what it is.
My view page:
<textarea id="edit" name="message"> </textarea>

My js:
 $(function() {
      $('#edit').editable({
          height: 400,
          imageUploadURL: '/assets/upload_image.php',
          imageUploadParams: {id: "edit"},
          imageUploadParams: {id: "edit"},
          placeholder: "Write something...",
          inlineMode: false
      })
  });

My upload_image.php file:
    <?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");

// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);

// Get extension.
$extension = end($temp);

// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);

if ((($mime == "image/gif")
        || ($mime == "image/jpeg")
        || ($mime == "image/pjpeg")
        || ($mime == "image/x-png")
        || ($mime == "image/png"))
    && in_array($extension, $allowedExts)) {
    // Generate new random name.
    $name = sha1(microtime()) . "." . $extension;

    // Save file in the uploads folder.
    move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "http://localhost/assets/uploads/" . $name);

    // Generate response.
    $response = new StdClass;
    $response->link = "http://localhost/assets/uploads/" . $name;
    echo stripslashes(json_encode($response));
}

What I have tried to fix this issue:
In upload_image.php, I have replaced the upload folder path (original: http://localhost/assets/uploads/ to just uploads and created an uploads folder in that directory. Still no luck.
I have tried placing all the files together in the same folder but no luck.
Any help is highly appreciated.
Comment: Open your developer tools, go to the Network tab. Is a request sent? Do you get any errors on the client or the server?
Comment: have you ensure path url in ajax is right? and upload_image.php can be process?. try print_r(something) in your upload_image.php and die(); on the top for ensure that(debugging).
Answer: I have gone through the same issue and I am sharing working code for you.
index.php
<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="css/froala_editor.css">

    <form method="post">
      <textarea id='edit' name='edit' style="margin-top: 30px;" placeholder="Type some text">

Textarea

The editor can also be initialized on a textarea.

      </textarea>

      <input name="submit" type="submit">
    </form>

upload_image.php
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");

// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);

// Get extension.
$extension = end($temp);

// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);

/* if you want to check extension of a file, then please remove the below if condition */
/*if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {*/
    // Generate new random name.
    $name = sha1(microtime()) . "." . $extension;

    // Save file in the uploads folder.
    move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/uploads/" . $name);

    // Generate response.
    $response = new StdClass;
    $response->link = "http://localhost/test/editor-3/html/uploads/" . $name;
    echo stripslashes(json_encode($response));
//}
?>

Now Open included javascript file image.min.js and just find and change the imageUploadURL parameter to url of your upload_image.php file, in my case, it is:
imageUploadURL: "http://localhost/test/editor-3/html/upload_image.php",

Answer: I am going to add an answer here because for one Froala's documentation is terrible. I had experienced multiple issues with both image and file uploads and spent many hours going crazy till after a few weeks I finally figured out the issue and hope this can help someone else.
First
fileAllowedTypes: ['*']

documentation
The following Froala specifies that this option will allow any file type to be uploaded...wrong. The thing that Froala is not telling you is that in order to be able to upload any file type you have to specify the extension of the file as well as the MIME-type. If you don't reguardless of this option it will not work. It will only allow PDF and TXT.
What to do
When you download the Froala SDK you need to head over to
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/File.php //for File upload

and
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/Image.php //for Image upload

In those files you will see something like
'allowedExts' => array('zip', 'txt', 'pdf'),
'allowedMimeTypes' => array(
      'text/plain',
      'application/pdf',
      'application/zip'
)

This is where you need to add your extensions and MIME-types that you want to allow. You must specify both the extension and MIME-type of the file.
If you are having trouble finding the MIME-type of a particular file just use this site.
I am guessing that this might apply to other languages as well or at least be a similar solution but I can confirm this for php
Hope this helps someone out in the future.


selecting top( x ) multiple times

Question: Sorry for the rubbish title but hopefully this will explain:
Given the table
<code> name     |   data
---------------------
   1      |   1000
   1      |   2000
   1      |   3000
   2      |   1500
   2      |   2500
   2      |   3500
</code>
I want to be able to select the top( x ) for all names ordered by the data value. So if x = 2 the return will be
<code> name     |   data
---------------------
   1      |   2000
   1      |   3000
   2      |   2500
   2      |   3500
</code>
Answer: <code>;with cte AS
(
SELECT name, data, ROW_NUMBER() OVER (PARTITION BY name ORDER BY data DESC) AS RN
FROM YourTable
)
SELECT name, data
FROM cte
WHERE RN<=2
ORDER BY name, data
</code>
Comment: Thanks again for this, used it to cut a 7-8 hour process down to 10-20 minutes
Answer: A slightly universal way would be (had not seen the edited tags that specified sql server)
<code>Select
  name,
  data
From
  <table> tbl
Where
  data In
     ( Select Top 2 Distinct
          data
       From
          <table>
       Where
          name = tbl.name
       Order By
          data Desc
     )
</code>

selecting top( x ) multiple times


Remove "www" from domain with Apache2 for HTTPS?

Question: Just installed a new fresh 12.04 ubuntu server.
Always used the boilerplate redirection to remove www but it looked like it did not support https so I started looking around. Tried everything I found & somehow http "www" removal works well but https won't redirect.
Here is what I use (in a bp_rewrite.conf file in /etc/apache2/conf.d) :
# Rewrite "www.example.com -> example.com"

<IfModule mod_rewrite.c>
  RewriteCond %{HTTP_HOST} ^www\.(.+)
  RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+)
  RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301]
</IfModule>

Has anyone experienced this?
Comment: What do you mean "https won't redirect"? The webserver doesn't send a redirect, or some other error??
Comment: It will stay lazily on the `https://www.website.com` while if I enter `http://www.website.com` I correctly get redirected to `http://website.com`
Comment: There doesn't appear to be anything wrong with the rule, so it must not be running the rule at all for https. How do you have your https site configured? Is this rule in the global configuration and the https site a virtual host?
Comment: Yep global rule in conf.d & virtual host. Should I put the rule in the virtual host?
Comment: Do you have any similar rules (or rules with the [L] flag, like the one you posted) in your Virtual Host or `.htaccess` file? The virtual host by default will inherit this rule, but will run inherited rules *after* any virtual host or `.htaccess` rewrite rules; though this could also be turned off (by a `RewriteOptions` directive).
Answer: In order for the RewriteRule to trigger, both RewriteCond directives has to be true.
How about this:
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [OR]
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
</IfModule>

Now, if just one of the conditions remain true (as for https://www.example.com/, where only the first condition is true), the RewriteRule is applied
Comment: Now this would turn https on anytime it's not on already... Still not what he's asking for.
Answer: Your example code looks slightly overly complicated, but very close to what I use:
    RewriteCond %{HTTPS}s%{HTTP_HOST} ^(on(s)|offs).+\.(.+\..+)$
    RewriteRule ^(.*)$ http%2://%3$1 [R=301]

Note: This simply rips anything off the front of the domain name's last two parts. So your user could enter what.the.example.com and it would reduce it to example.com. If your domain name is example.co.uk or something with three parts the end of the first line would have to be modified to fit.
Comment: This does not work for one use case though:  if I enter [https://www.dom.com](http://example.com)(https://www.dom.com), it again returns [https://www.dom.com](http://example.com)(https://www.dom.com).   For http: it removes the www and rewrites to https though.


How do I find a function given vertical and oblique asymptope?

Question: Vertical asymptote: $x=2$
Oblique asymptote: $y=8x+5$
How do I find an example of a function given these asymptotes?
Comment: Welcome to Math Stackexchange. This is not a "solve this for me" site. Please provide some additional information on the context in which this problem appeared and/or on how you have attempted to solve it so far. Best regards
Answer: Hint: One such function can be taken as: $f(x) = 8x+5+\dfrac{1}{x-2}$.Another one would be $g(x) = f(x) + \dfrac{1}{x}$.


replace Lock screen with Switch Account screen

Question: User successfully logs in as email@example.com .
User is then mapped to email@example.com via
altSecurityIdentities: Kerberos:firstname.lastname@example.com
When the user locks the screen, the lock screen is for email@example.com, which the user does not have the (randomized) password for.
It is possible for the user return to their session by backing out to the main login screen, which where EXAMPLE.COM is the default domain/realm, and logging in there.
Is there a way to force firstname.lastname@example.com as lock screen user or, failing that, cause the lock screen to go immediately to the switch user screen.
I am primarily interested in Windows 7 and 8, but knowledge for other version would also be useful.
Comment: More details would be helpful.
Answer: To have the lock screen be the effective equivalent of the switch user screen enable group policy (Functional Level 2012*):
Computer Configuration \ Policies \ Windows Settings \ Security Settings \ Local Policies \ Security Options -> Interactive Login: Display user information when session is locked -> Do not display user Information
*This policy is not new in 2012 and shows up in much the same path in lower function levels.


Chord progressions in Harmonic Minor

Question: I'm a noob at music theory, so I want to stick to basics and stay inside the lines (for example, stay diatonic for a given scale) until my knowledge is more advanced.
I've seen a chart all over the web for chord progressions in a harmonic minor scale that looks like this

( SOURCE).
But I don't understand it.  The triad for harmonic minor's seventh scale degree is viio, i.e., a diminished chord.    But this chart has both viio and VII (a major chord).   But can you make a major (0-4-7) chord at that scale degree and stay diatonic, i.e., avoid chromatic alteration?  It's not obvious to me, so what do they mean?
Comment: I'll add this up here too. If you want to stick to basics, you do chromatic alterations. In minor, doing chromatic alterations of at least the 7th scale degree is the basic thing to do. Hit the Road, Jack: Am - G - F - E.
Comment: Have you looked up the root site of your source? https://musictheory.pugetsound.edu/mt21c/MusicTheory.html You should have and you should have showed  this site as your source. Then I would say I don't vote up your question because of lack of self researching and not telling us what your efforts have been ;)
Answer: I would summarize the other answers by calling out a faulty premise of the question: there is no such thing as a song "in harmonic minor."
The preposition "in" denotes the key of a piece.  The key designation comprises two parts.  The first is the "home" pitch, called the "tonic," such as D or A flat, and the second is a quality designation, which is usually either major or minor.  It could also be the name of a mode, such as Dorian or Mixolydian.
Harmonic minor, on the other hand, is a scale, and a rather artificial one at that.  The three qualities of minor scale appear to have arisen in the 19th century as a device to reconcile the chromatic alteration that was prevalent in minor-key harmonies with the new fashion for playing scales as a way of learning to play an instrument.  Because of this chromatic alteration, most pieces in minor keys used 8 or 9 distinct pitches (ignoring octaves), and arranging all of those pitches in a single scale did not achieve the desired result.  Instead, the idea of three different minor scales was invented.
But, like much music theory, this was not a generative rule.  Composers did not start with these scales and then work to see what they could come up with using them.  Rather, it is a descriptive or analytical tool: it is an attempt to explain how music works.  Unfortunately, this analytical tool is rather poorer than many that were developed over the centuries.  It tends to increase confusion rather than to reduce it, and it tends to complicate theoretical analysis rather than to simplify it.
If you insist on analyzing minor music in terms of the three minor scales, you find that most real tonal music mixes all three forms of the scale, using one or another at different points depending on various considerations.  Even the fact that one of the three scales has different forms depending on direction, and that one of those forms is identical to the form of one of the other scales, suggests that this whole approach to modeling music theory is problematic.
With this in mind, consider:

I've seen a chart all over the web for chord progressions in a harmonic minor scale that looks like this...

If those charts are truly said to be for "music in a harmonic minor scale" the I would advise you to find another source for music theory instruction.  The chart in fact reflects the real story with minor-key music: both the sixth and seventh degree of the scale can be raised or lowered.  That is, in A minor you will encounter F natural and F sharp as well as G natural and G sharp.
This answer is now rather longer than I wanted it to be, but it can close as it began: there is no such thing as "in harmonic minor"; it's just "in minor."
Comment: Excellent answer! +1 The same false premise is behind questions like "how can there be a non-diatonic note, doesn't this violate the rules of nature?" The more I watch theory lessons about scales and how beginners react to it, the stronger I think that melodic and harmonic minor scales shouldn't be taught to beginners at all. By the way, in A minor, you will often encounter C#, D# and Bb as well. C# when going A7 - Dm, and D# when going B7 - E7. And Bb when going Gm6 - A7 - Dm. Even harmonic and melodic minor combined are not enough to cover for-dummies level polka song harmony.
Comment: There is only one scale which truly covers notes which may be found in any piece - it's the *chromatic* scale...
Answer: IMO, the reason why people have big difficulties understanding music in minor keys comes from two mistakes:

MISTAKE #1: Instead of playing (repeating) lots of example music they want to know theory first, and
MISTAKE #2: Having got ideas from theory (caused by mistake #1), they assume that they can select one single scale in which they can operate "diatonically" i.e. without any alterations to the scale needed, for example the Harmonic Minor scale. Just like they were able to do for major tonality.

First of all, I'd suggest first playing lots of songs in minor to learn concrete examples. Spend at least a few weeks doing that. And only after you have some hands-on experience, you try to look at how the examples you know could be described in theoretical terms.
And about the "staying in one scale", it doesn't work like that. It's better to consider for example the dominant chord introducing a chromatic alteration, as you say. When you're at the tonic chord, let's say, Am, the assumed scale is A natural minor. No G# there. But then at some point comes an E major chord, and then the G note is sharpened. Songs are not "in harmonic minor" all the time.
Trying to avoid chromatic alterations is a Bad Idea and goes against the way music works, and it imposes an unnecessary obstacle to understanding even simple songs in minor keys (i.e. minor tonics). IMO, accidentals and temporary alterations should be introduced from day 1, and not try to think that music is inside a scale. Scales are there only as helper grids, so you can reason about where the sounding notes are relative to basic default positions. Songs are not "in a scale", except for some very specific modal music where chromatically altering the scale would break the modal feeling. But minor tonality is not a mode.
Harmonic and melodic minor scales can be used modally, but that's more of a modal jazz thing.
What comes to the picture, I don't know who made it or how it was presented where it was used. But to tweak the picture so that it makes some sense, I added some annotations:

During the dominant chord, the 7th scale degree has to be raised or otherwise it's not a proper dominant chord. It's a "chromatic alteration" or something. This is the basic thing to do in a minor key. Trying to use the harmonic or melodic minor scales modally is not a basic thing.

Side-note. What causes the theory-first mentality? Is it social pressure and demand of legitimacy? Seemingly scientific theoretical and informed logical thinking is highly valued. Is it perhaps a desire to retain a feeling of "being in control", and to avoid childish - and therefore socially unacceptable - babbling and tumbling where you don't know what you're doing? An opposite but related phenomenon is wanting to learn to play pieces exactly note-for-note "correctly" and precisely, for example with these Synthesia videos with note blocks falling on keyboard keys. What's wrong with repeating, babbling, toying, playing, interacting with others? That's how you learn languages, and music is a language. In my opinion, a better formula for learning music would be something like this:

45% repeating examples
45% messing around with the examples, making changes and trying variations, making discoveries
10% theory, to identify patterns and to get names for the discovered patterns, forming concepts to assist communication and reasoning.
Comment: _"What causes the theory-first mentality?"_   In my case it's probably because my background is in engineering where you have to learn a lot of physics, calculus, etc, before you can "do" real engineering.   A lot of fields are like that: medicine, physics and chemistry, etc.   The other advantage of theory is that it helps organise what you otherwise experience subjectively.   What could it mean to "know the existing literature" (as Todd Wilcox says) without being able to describe it or place it in a theoretical framework?
Comment: @user316117 Music is not a natural science, it's culture. But a part of the problem lies with teachers wanting to present logical constructs that can be put in an exam and judged in a "correct/incorrect" fashion, to get a numerical score. Scales are one of such things. But teachers should rather be more like coaches or personal trainers, guiding the student's own exploration and practicing and developing a taste. Another problem is internet "teachers" and algorithm-guided attention gathering which is engineered to produce lots of views. "_The secret formula of the pros_" etc.
Comment: One *could* stay completely within a single seven note scale, but any music composed that way would be very challenged to stay interesting. I love how this answer emphasizes composing based on knowing the existing literature over knowing the "theory". Knowing prior work in any form is the best way to move that form forward - in fact I find it makes it quite intuitive and it "feels" good.
Comment: @ToddWilcox it's not that hard to find literally diatonic music that is also interesting.
Comment: @user316117 Knowing note names and noticing even a few elementary patterns such as intervals and chords gets you a long way. Go play music on an instrument - your brain will inevitably discover patterns automatically, that's its job. And if you have to choose between identifying non-applicable patterns from playing actual music, or identifying non-applicable patterns from _theory_, it's harder to get rid of the latter. One such mythical belief is that "music is in a scale", which is simply wrong and incompatible with reality. And it hurts many people's musical progress.
Answer: For simplicity's sake, minor has been split into three different scales. That's without getting into minor modes.
There's the natural minor, the harmonic minor and the melodic minor. They're not really separate constructs but for simplicity, each contains notes of the letters ABCDEFG. That in itself makes it slightly easier for beginners. But those scales are just that - scales. Sets of notes that can be played up and down, as we do with scales.
Not a true reflection of how notes get used in minor pieces! The first five notes in each are identical, but after that, there are changes, for reasons quoted in many answers on this site.
The scale quoted is not the harmonic minor, but a bastardisation of harmonic and natural minors.
By the time all the chromatic changes for the top half of minor scales are considered, there are many different triads that can be made from those notes. The example just forgot to remind you of that.
Comment: To make things slightly "easier", an incorrect misleading fallacy, almost a complete _lie_, is taught to beginners. And then they spend lots of effort to overcome the "easy" nonsense. I say, music is taught _wrong_. It would be better if harmonic and melodic minor scales weren't mentioned at all, because all they really do is confuse people so that they cannot understand even simple basic tunes. The right way to talk about minor tonality is, "look here, during this E chord in this bar, the G note is sharpened to G#. It makes a nice melody and harmony".
Comment: The statements "scales are part of..." and "scales have always been..." do not rebut @piiperiReinstateMonica's assertion that "music is taught wrong"; they merely give some detail about what's wrong with the way music is taught.
Comment: @phoog - I know, and understand, and agree. Still a fact though...
Comment: @piiperiReinstateMonica - I hear what you say, and to a degree agree. But scales *are* part of every teacher's curriculum, and as such, rear their (ugly) heads. Major scales, and their modes, are easily understood, and stand well. Can't say the same for minors, though, as you point out. But - the problem is exacerbated by *all* the exam boards, which insist on perpetuating the 'problem'. Scales have always been (and probably will always be) a section of exams. 'They exist, so we can test them'. And, undeniably, the majority of pieces will be seen to use those scale notes. I don't think just...
Comment: @piiperiReinstateMonica -...saying 'it's there 'cos it sounds nice' is sufficient. There are technical reasons for all the chromatic changed notes in minor scales (thus minor pieces), and these need to be understood. For years I played Black Magic Woman in key Am, using E *major* as the V. Mainly because I associated E rather than Em in key Am! But yes, I agree that minor tonality is taught (not by me!) in not-particularly- helpful ways, often. Hence the propensity of questions such as this very one on this, and other sites. Aargh!
Answer: This site informs you about diatonic scales:
https://en.wikipedia.org/wiki/Diatonic_scale
It is confusing whether the harmonic minor scale belongs to the diatonic scales.
Any sequence of seven successive natural notes, such as C–D–E–F–G–A–B, and any transposition thereof, is a diatonic scale. Modern musical keyboards are designed so that the white notes form a diatonic scale, though transpositions of this diatonic scale require one or more black keys. A diatonic scale can be also described as two tetrachords separated by a whole tone.
The term diatonic originally referred to the diatonic genus, one of the three genera of the ancient Greeks. In musical set theory, Allen Forte classifies diatonic scales as set form 7–35.
This article does not concern alternative seven-note scales such as the harmonic minor or the melodic minor which, although sometimes called "diatonic", do not fulfill the condition of maximal separation of the semitones indicated above.
Western music from the Middle Ages until the late 19th century (see common practice period) is based on the diatonic scale and the unique hierarchical relationships created by this system of organizing seven notes.

If you want you can consider a melodic minor scale like a diatonic scale built by a minor tetrachord=4 tones a,b,c,d and a major tetrachord e,f#,g#,a.

Many songs contain both lines: melodic upwards e,f#,g#,a and melodic downwards a,g,f,e, some are just in the aeolian (min 6th, min 7th) or in the dorian mode (maj 6th and min 7th)

The harmonic minor scale has only an sharpened (= maj) 7th (so=> si) with a 1 1/2 half step between VI and VII (fa-si => min 6th and maj 7th).

It depends of the melody whether you have a VII  or a vii dim chord.That's why I agree with other answers: you should have more experience with songs and pieces of all 3 minor scales by playing and accompanying them with chords before asking about functions and Roman numbers and then you will understand the theory much better.
Maybe this link will help you further:
https://www.guitar-chords.org.uk/a-harmonic-minor-chords.html
But you will find much more information looking up scales here in this SE, diatonic scales, modes and harmonic scale.
Comment: No augmented 7th interval in harmonic minor. It's a *major* 7th.
Comment: oh, yes, in German we call "sharpening" = augmenting. But this is wrong: augmented would mean a double sharped 7th, yes?
Answer: In the style of harmony that chart tries to represent, called common practice, music is not in harmonic minor it is in a minor key. See the following post for some explanation of minor key harmony Understanding minor key harmony
Part of the problem with the flow chart you posted is they work best as a summary of a longer study of functional harmony. The arrows showing the progression of chords are correct on one level, but it is a mistake to then use the chart as a how to write chord progressions guide. I recently found this article - Tymoczko, Root motion, function, scale-dgree... - which does a nice job of breaking down why the flow charts are flawed. In essence Tymoczko points out the flow chart doesn't have "memory" and can easily produce un-idiomatic harmony.

...so I want to stick to basics and stay inside the lines

Use the rule of the octave for this instead of those flow charts.

...But this chart has both viio and VII (a major chord). But can you make a major (0-4-7) chord at that scale degree and stay diatonic, i.e., avoid chromatic alteration?

The thing you must understand is minor-key harmony is chromatic even at a basic level.
For example, in the key of C minor, the viio is B♮ D F and VII is Bb D F. Both chords will be common in minor key music.
In minor key music the sixth and seventh scale degree are raised and lowered depending on the harmony. The rule of the octave will provide a concise, practical example of how it all works. Combine that with some of the easier JS Bach keyboard books like the Anna Magdalena notebook or the "little prelude" books, here or here.
Answer: The harmonic minor scale is best thought of as a theoretical construct to describe how some composers deal with composing in minor keys. When approaching the tonic chord in minor, it strengthens the sense of arrival if the seventh scale degree is a half-step below the tonic pitch. In a minor key, that means raising the seventh note of the scale a half step, which, presuming no other changes, gives the harmonic minor scale. And the chord preceding the tonic chord would be a diminished chord built on that raised seventh scale degree.
However, when moving away from the tonic, the raised seventh (the "leading tone") is not needed. In that case, the chord built on the seventh scale degree is a major chord.
Example
The key of A minor has no sharps or flats. Thus, the "natural minor" scale is
a b c d e f g
But it's nice to have a leading tone to intensify movement toward the tonic. Since g to a is a whole step, we raise the g to create a leading tone. That gives the harmonic minor scale...
a b c d e f g#
... and results in a viio chord, g# b d.
When moving away from the tonic, however, we don't need the pull of the leading tone, so we use the "natural" seventh. Building a triad on that pitch gives g b d, a VII chord (often called bVII for clarity).
Comment: Are there scales that aren't theoretical constructs?
Comment: @piiperiReinstateMonica There are scales that aren't theoretical constructs to describe how some composers deal with composing in minor keys.

Chord progressions in Harmonic Minor


assign permissions to a created role?

Question: i want to assign permissions to a role in my hook_install() , but the permissions that i'm adding are part of my modules hook_permission()
 don't exist yet?
so how to grant permissions role created in hook_install after hook_permission ?
NB :

i have D7.23
     -
my module create the role and his permissions .
Thanks.
Comment: problem resolved by set permissions in hook_install() user_role_grant_permissions($pub_role_rid,array_keys(module_invoke('my_module', 'permission'))); after creation of my custom role.
Comment: you can add that as an answer also specify the links to the resources from where you find out. However I wonder whether this is a proper way to achieve it?
Comment: Possible duplicate of - http://stackoverflow.com/questions/15972588/create-a-permission-and-set-a-role-to-it-on-module-install
Comment: i'm used array_keys(module_invoke('my_module', 'permission') to get only the permissions of ma custom module thanks Mathankumar .
Answer: the solution found in http://www.dibe.gr/blog/drupal-7-create-users-and-roles-programmatically in the author comment , so i'm set only the permissions array of my custom module in hook_install() user_role_grant_permissions($role_rid,array_keys(module_invoke('my_module', 'permission')));

assign permissions to a created role?


If every proper quotient is finite, then $G\cong\mathbb Z$

Question: Here is my problem:

Let $G$ is an infinite abelian group. Prove that if every proper quotient is finite, then $G\cong\mathbb Z$.

And here is my incompleted approach:
I know that the quotient subgroup $\frac{G}{tG}$ wherein $tG$ is torsion subgroup of $G$ is always torsion-free. So, if $tG\neq\{0\}$ then here we have $\frac{G}{tG}$ torsion-free and finite simultonously which is a contradiction. Then $G$ is itself a torsion-free group.
Moreover, I assume $G$ be a divisible group, so: $$G\cong\sum\mathbb Q\oplus\sum_{p\in P}\mathbb Z(p^{\infty})$$ As any proper quotient of $G$ is infinite, so I concluded it is not divisible. I confess that I am missing the final part. If my way to this problem untill my last conclusion is valid logically, please help me about the last part of the proof. Thanks
Answer: Let $a_0\in G$ be a nonzero element.
Then $\langle a\rangle\cong \mathbb Z$ as $G$ is torsion-free (which you have shown).
Now $Q_0=G/\langle a_0\rangle$ is a finite abelian group.
If $Q_0\cong 1$, we are done.
Otherwise, select $a_1\in G\setminus\langle a_0\rangle$. Then let $Q_1=G/\langle a_0, a_1\rangle$, etc.
The orders of the finite groups $Q_0, Q_1, \ldots$ are strictly decreasing as long as they are $>1$, hence we ultimately find an $a_n$ with $G=\langle a_1, \ldots,a_n\rangle$.
Thus $G$ is a finitely generated abelian group. A quick check with the classification theorem shows that $G\cong \mathbb Z$.
Comment: Thanks Hagen!. And this quick check is related to quotient of $G$?


Why do we need to check for these two assumptions for ANCOVA but not for factorial ANOVA?

Question: ANCOVA has two additional assumptions as compared to two-way factorial ANOVA. They are (1) independence of the covariate and factor (2) homogeneity of slope. Why don't we need to check them for two-way factorial ANOVA?
Answer: The covariate (i.e., continuous factor) cannot be part of an ANOVA and these assumptions are for the covariate, thus they are only needed for the ANCOVA.
Answer: The first assumption you mentioned is not correct. Controlling for the covariate is typically done because the factor and the covariate could be dependent.
With your second assumption I guess you refer to the idea that the covariate ("age") must have the same effect for each level of the factor. Or maybe more important: the factor should have the same effect no matter what value of age you are looking at. Anyway, this means that there should be NO interaction of the factor and the covariate. In a two-way ANOVA on the other hand, the interaction of the two factors is typically analysed/studied. If it appears to be insignificant, than that is considered an important finding.
Maybe that sometimes you would only like to control for another factor i.e. a categorical independent variable, say gender. In that case, gender would serve more as a covariate, like age above, for which you would only like to control without studying the interaction of gender and your factor of interest. Then, again, you would have to assume that gender does not interact with your factor of interest, meaning that your factor has the same effect for both genders. That would be an assumption then.


Restrict administrator users from seeing blocks

Question: I am using Drupal 6. I placed a JavaScript snippet in a block required by a third-party chat service I have on site.
Now, this block is by default displayed on my administrative pages, which is annoying. Is it possible to restrict the admin role from seeing this block?
I tried this kind of snippet but it doesn't work.
global $user;
if (($user->role) == 'anonymous') {
  return TRUE;
}
else {
  return FALSE;
}

?>
Answer: If you don't want the block displayed on admin PAGES, eg, www.yourhost.com/admin/HERE, you can go into the block admin pages and restrict the block to be displayed on all pages EXCEPT admin/*.
However, if you don't want your "root" or "superuser" to see the blocks on any page, you can do what @BetaRide has suggested above in the PHP area of the admin page.
In the same vein, if you don't want anyone with an admin role to see the block, you can do something like this:
global $user;
if ($user->uid==1 || in_array('admin users', array_values($user->roles))) {
  return FALSE;
} else {
  return TRUE;
}

Of course, here you have to make sure you have a role called admin users so that might be different on your system.
If you don't want to add a role, you could use permissions and do it like this:
if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

which would display the block only to those users who could NOT access the admin pages.
Comment: thank you, the second snippet worked. I tried to use BetaRide's snippet but it was not working.
Answer: This should do the job:
 global $user
 return $user->uid!=1;

This disables the block for the admin user.


Is it possible to turn an entire webpage to grayscale using javascript

Question: I want my entire body tag to be at greyscale = 100% using javascript
like in css we can do it by using "*" selector
Comment: Possible duplicate of [Is it possible to turn an entire webpage to grayscale using CSS?](http://stackoverflow.com/questions/30192221/is-it-possible-to-turn-an-entire-webpage-to-grayscale-using-css)
Comment: Do you have a reason for not wanting to use css to do this?
Comment: yes actually in some of the cases i have to do this
Answer: To select all elements, use * as well...
Array.from(document.getElementsByTagName("*"))
    .forEach(el => el.style.filter = 'grayscale(100%)');

However, if you just want to set grayscale on your page, use
document.body.style.filter = 'grayscale(100%)';

Answer: you can select entire body:
document.getElementsByTagName("BODY")[0];


Show that if a proper function has a subgradient everywhere in its convex domain, then it's convex.

Question: Let $f:\mathbb{R}^n\rightarrow (-\infty,\infty]$ be proper. If $\operatorname{dom} f$ is convex and $\operatorname{dom} \partial f=\operatorname{dom} f$, show that $f$ is convex. I wonder what is the angle to prove such a statement?
Answer: The idea is straightforward; if we can write
$f(x) = \sup_{h \in H} h(x)$ where each $h \in H$ is convex, then $f$ is convex.
Let $H = \{ y \mapsto f(x)+g^T(y-x) | x \in \operatorname{dom}f, g \in \partial f(x) \}$.
Comment: The set of functions in $H$ is convex, only cause $\partial f$ and $ dom f$ is convex right?
Comment: @lone_wolf It is not relevant. What matters is that it is the pointwise $\sup$ of a collection of convex functions, hence convex.
Comment: Yes, I understand that the supremum of convex functions is convex. But my doubt is,if $\partial f$ is not convex,  will it then be convex only within the convex subset of $\partial f$?
Answer: Let $H$ be a family of linear functions using the following definition,
$$
H=\{x\rightarrow f(z)+g^T(x-z)|z\in \operatorname{dom} f, g\in\partial f(z)\}
$$
From the definition of subgradients, we know that $\forall h\in H$,
$$
f(x)\ge h(x)
$$
so that
$$
f(x) \ge \underset{h\in H}\sup h(x)
$$
On the other hand, we can always let $z=x$, then any $h\in H$ will satisfy
$$
h(x)=f(x)\ge f(x)
$$
so that
$$
\underset{h\in H}\sup h(x) \ge f(x)
$$
Hence $f(x)=\underset{h\in H}\sup h(x)$ is convex as the supremum of a family of linear functions.


Can a service-check be limited to hosts with a custom attribute defined?

Question: For those of our hosts, which have a public IP-address, we define a custom attribute in the host-definition: _PADDR:
define host {
        ...
        address 10....
        _paddr  53....
}

Can we then -- without creating specific groups or other entries -- limit a service check only to those of the hosts, which have the custom attribute defined?
Using Icinga-1.13.3.
Comment: Icinga 2.x support this. 1.x likely not
Comment: I'm with @uSlackr here..
Comment: @uSlackr, why don't you turn your comment into an answer so I can formally accept it and close this question?
Comment: Which version are you using?
Answer: Icinga 2.x supports this. I don't believe v1 does.  See the documentation here. Look specifically at the Apply, Assign Where, and Custom Attributes


Wave equation PDE with inhomogeneous boundary

Question: I found this question on the physics side of our network and tried in vain to solve it. It's better suited here, so I'll post it.
We have a vibrating string. One side of the string is fixed, and the other side of the string vibrates by the force $F(t) = A \sin\omega t$.
Wave equation in 1D:
$u_{tt}=k^2u_{xx}$
Boundary conditions:
$u(0, t) = 0,u(l, t) = A \sin \omega t$
$u(x, 0) = u_t(x, 0) = 0$
My attempt:
The $\sin \omega t$ term was always going to worry me but I ran into problems well before that!
If we use separation of variables with Ansatz:
$$u(x,t)=X(x)T(t)$$
and separation constant $-m^2$, we obtain two ODEs:
$$\ddot{X}+m^2F=0$$
and:
$$\ddot{T}+m^2k^2G=0$$
The second has the classic solution:
$$T(t)=A\cos(mkt)+B\sin(mkt)$$
Using the boundary condition: $u(x,0)=u_t(x,0)=0$:
$$u(x,0)=0\implies T(0)=0$$
$$0=A\cos 0+B\sin 0\implies 0=A+0\implies A=0$$
So $T(t)=B\sin(mkt)$.
And for the second one:
$$u_t(x,0)=0\implies \dot{T}(0)=0$$
$$\dot{T}(0)=Bmk\cos 0=0 \implies B=0$$
Or $mk=0$. Either way this makes:
$$T(t)=0$$
A commenter mused "You need to account for resonant frequencies where nonzero solutions are possible" but I'm far from sure how to go about that.
Comment: It does appear to pose a problem, yes.
Answer: We can search for a solution via the Laplace transform. The inverse laplace transform is what is going to be cumbersome, and I believe we might be able to extract a series solution of sorts from it.
We would have
$$s^2 U(x,s) - su(x,0)-u_t(x,0) = k^2 \partial_{xx}U(x,s)$$
Which leads to the Boundary Value Problem in $x$,
$$\begin{cases}
k^2 U''(x,s) - s^2(x,s) = 0 \\
U(0,s)=0 \\
U(L,s)=A\displaystyle\frac{\omega}{\omega^2 + s^2}
\end{cases}$$
This has the solution $$U(x,s) = A\left(\frac{\omega}{\omega^2 + s^2}\right)\text{csch}{\left(\frac{Ls}{k}\right)}\text{sinh}{\left(\frac{sx}{k}\right)}$$
and so,
$$u(x,t) = \frac{1}{2 \pi i}\int_{\gamma - i\infty}^{\gamma + i\infty}U(x,s)e^{st}\,ds$$
In order to do this, consider the integral
$$\int_{\Gamma}U(x,z)e^{zt}\,dz$$
Where $\Gamma$ is the contour taken from the vertical line $x=c$, connected to a circular contour with radius $R$ in the first quadrant going around and connecting back to $x=c$ in the fourth quadrant.
Since our integral is made up of exponentials, it's easy to bound and show that it vanishes as $R\rightarrow \infty$ (I avoided this computation, but it would be nice if someone could verify my suspicion.). Further, we have simple poles at $z = \pm i \omega$ and $z=\frac{kn\pi i}{L}$ for $n \in \mathbb{Z}$. There is no pole at $z=0$ as it is a removable singularity.
Thus,
$$u(x,t) = \text{Res}(U(x,z)e^{z t},i\omega) +\text{Res}(U(x,z)e^{z t},-i\omega) +\sum_{n\in \mathbb{Z}}\text{Res}(U(x,z)e^{z t},\frac{k n \pi i}{L})  $$
To which we have the following from the residues:
$\text{Res}(U(x,z)e^{z t},i\omega) = \frac{1}{2 \pi i}(A e^{i t \omega} \csc{\frac{L \omega}{k}}\sin{\frac{\omega x}{k}})$
$\text{Res}(U(x,z)e^{z t},-i\omega) = -\frac{1}{2 \pi i}(A e^{-i t \omega} \csc{\frac{L \omega}{k}}\sin{\frac{\omega x}{k}})$
$\sum_{n\in \mathbb{Z}}\text{Res}(U(x,z)e^{z t},\frac{k n \pi i}{L}) = \frac{AkL\omega}{i} \sum_{n \in \mathbb{Z}} \left(\frac{(-1)^n}{(kn\pi)^2-(L\omega)^2} \right)\sin{\frac{n \pi x}{L}}e^{\frac{k n t \pi i}{L}}$
So that
$u(x,t) = A\csc{\left(\frac{L\omega}{k}\right)}\sin{(t\omega)}\sin{\left(\frac{\omega x}{k}\right)} + \frac{AkL\omega}{i}\sum_{n\in \mathbb{Z}}\left(\frac{(-1)^n}{(kn\pi)^2-(L\omega)^2} \right)\sin{\left(\frac{n \pi x}{L}\right)}e^{\left(\frac{k n t \pi i}{L}\right)}$
Now, noticing the summation in the index actually simplifies..we get
$u(x,t) = A\csc{\left(\frac{L\omega}{k}\right)}\sin{(t\omega)}\sin{\left(\frac{\omega x}{k}\right)} + 2AkL\omega\sum_{n=1}^{\infty}\left(\frac{(-1)^n}{(kn\pi)^2-(L\omega)^2} \right)\sin{\left(\frac{n \pi x}{L}\right)}\sin{\left(\frac{k t n \pi}{L}\right)}$
Here's a gif of the string in action for $A=L=k=\omega=1$
Comment: @DaveNine can u verify ut(x,0)=0?
Comment: +1 for effort. Not sure I get it all. Will have to brush up on Laplace transforms...
Comment: @Gert , I have edited my post to include a full solution via Laplace Transform.
Comment: @HanSen you are right, I don't think that that condition is satisfied(I plotted a few solutions in Mathematica) I wonder what's missing? That condition is handled very early into the solution..
Comment: @DaveNine: Thank you!
Comment: I just wanted to say, after investigating what is happening at the boundary conditions for $t=0$, It appears we have some sort of Fourier Series expansion for 0, as my solution is consistent with Mathematica's numerical solution as well, and the error is very small when dealing with a finer grid. There is some sort of Gibbs Phenomenon as $x \rightarrow 0$ when forcing $t=0$ in $u_{t}(x,0)$, which is forcing the largest error on that side. I am, hence, pretty confident that the solution I derived is the exact solution for the problem.
Answer: Let $u(x,t)=v(x,t)+\dfrac{A}{l}\,x\sin(\omega\,t)$. Then $v$ satisfies the inhomogeneous wave equation
$$
v_{tt}=k^2\,v_{xx}+\frac{A\,\omega^2}{j}\,x\sin(\omega\,t),
$$
the homogeneous boundary conditions
$$
v(0,t)=v(l,t)=0
$$
and the initial conditions
$$
v(x,0)=0,\quad v_t(x,0)=-\frac{A\,\omega}{l}\,x.
$$
The solution of this equation can be found as a series of the form
$$
\sum_{m=1}^\infty \bigl(A_m(t)\cos(m\,k\,t)+B_m(t)\sin(m\,k\,t)\bigr)\sin\Bigl(\frac{m\,\pi\,x}{l}\Bigr).
$$
Comment: $v_t$ or $v_{tt}$?
Comment: Ups! I will edit.
Comment: @Hary49 $ v $ is defined to be the difference of $ u $ and the sine function
Comment: @Harry49 You are right
Comment: Rats, another stupid mistake.
Answer: A longitudinally-vibrating string is considered. The conservation of momentum gives the wave equation
$$
u_{tt} - c^2 u_{xx} = 0
$$
in the interior of the domain $x\in \left]0,L\right[$, where $c$ is the speed of sound. The string is initially at rest:
$$
u(x,0) = 0 = u_t(x,0)\, , \quad x\in \left]0,L\right[ .
$$
The side $x=0$ is fixed:
$$
u(0,t) = 0 \, .
$$
A sinusoidal force is applied on the side $x=L$:
$$
u_x(L,t) = \epsilon\sin \omega t \, .
$$
In the original problem, a sinusoidal displacement $u(L,t)$ is applied instead.
Anyway... Also with the initial problem where boundary conditions and initial conditions on $u_t$ are incompatible at $x=L$, separation of variables may not work if applied directly (see e.g. this post, where a similar problem --arbitrary displacement at $x=0$, zero force at $x=L$-- is tackled). One can write the solution as $u(x,t) = v(x,t) + x\epsilon\sin \omega t$ and apply separation of variables for $v$.
Comment: Why $u_x(L,t) = \sin \omega t$? Why the *derivative*?
Comment: Hmm... it appears to me to be a math device to get rid of the inconsistency you pointed out above. But I don't think it has a physical meaning. And my problem $u(x,0) = 0 = u_t(x,0)$ persists.


Duvidas com um contador regressivo em JS e HTML

Question: imagino que essa minha duvida seja meio bobinha, mas é sério estou metade do dia tentando resolver esse desafio que me propus e infelizmente não consegui, lembrando que sou bem iniciante.
Pois bem, resolvi criar um cronometro usando JS, onde o usuário insere o tempo num input number HTML, o JS recebe o valor, converte para number, então o if subtrai 1 do valor a cada 1000 milissegundos e exibe no HTML.
Acontece que ele funciona se eu determino o valor fixo na variável time e coloco o onload chamando a função js na tag body. Mas usando o input number com o onclick chamando a função no botão ele só exibe o primeiro valor da contagem regressiva e trava. Estou empacado aí. Mais uma coisa, tentei colocar os input dentro de um form mas nesse caso ele só piscava o numero e sumia o valor.

function contador(){
    let val = document.getElementById('valor');//essa variavel recebe o valor do form
    let time = Number(val.value);//essa variavel converte o valor recebido do form para numero

    if(time > 0){
        time = time -1;
        if(time == 0){
            time = "FIM!"
        }
    }

    tempo.innerText = time;
    setTimeout("contador()", 1000);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contador regressivo!</title>

    <link rel="stylesheet" href="style.css">

Digite abaixo um valor para o cronometro:

        <input type="number" name="valor" id="valor">
        <input type="submit" value="OK" onclick="contador()">

Preparar!

Answer: O problema é que a cada segundo você está inicializando o val novamente. Aí dá a impressão que o loop não está funcionando, mas na verdade ele "funciona sempre com o mesmo valor"
Veja a diferença inicializando apenas uma vez (não é uma boa solução, é apenas para evidenciar o problema):

var val; // Global apenas para ilustrar
var time;

function inicia(){
    // VAMOS PEGAR O VALOR SO UMA VEZ
    val = document.getElementById('valor');//essa variavel recebe o valor do form
    time = Number(val.value);//essa variavel converte o valor recebido do form para numero
    setTimeout("contador()", 1000);
}

function contador(){
    // AGORA DECREMENTA, SEM PEGAR O VALOR INICIAL
    if(time > 0){
        time = time -1;
        if(time == 0){
            time = "FIM!"
        }
    }

    tempo.innerText = time;
    setTimeout("contador()", 1000);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contador regressivo!</title>

    <link rel="stylesheet" href="style.css">

Digite abaixo um valor para o cronometro:

        <input type="number" name="valor" id="valor">
        <input type="submit" value="OK" onclick="inicia()">

Preparar!

Comment: Cara, vlw por responder, com certeza vai ajudar em meus estudos!
Answer: Bom, para fazer o cronômetro seria necessário utilizar o setInterval(), e você utilizou o setTimeout().
O setTimeout() executa uma vez depois do tempo definido, enquanto o setInterval() executa infinitamente(ou pelo menos até que você pare ele com clearInterval()).
Mais informações em NodeBR
Segue o código correto:
function iniciarContador(){
  const val = document.getElementById('valor');
  let time = Number(val.value) + 1;
  const contador = setInterval(() => {
    if (time > 0)
      time = time - 1;
    else {
      time = "FIM!"
      console.log('Finished');
      clearInterval(contador);
    }
    tempo.innerText = time;
  }, 1000);
}

Espero ter ajudado.
Comment: Cara, agradeço funcionou certinho, realmente me ajudou em meus estudos, vlw!


How to set custom Time in TimePicker

Question: TimePicker shows current time as default in TimePicker, but what if i want to set default time in time picker as per my requirement.
Like its 11:10 when i am writing this, but in TimePicker i like to show 01:00 as default (my mean 2 hours difference, and minutes should be 00 only)
static final int TIME_DIALOG_ID = 1;

    public  int year,month,day,hour,minute;
    private int mYear, mMonth, mDay,mHour,mMinute;

    public TimePickerActivity() {

            // Assign current Date and Time Values to Variables
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);
    }

    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {

        public void onTimeSet(TimePicker view, int hourOfDay, int min) {
            hour = hourOfDay;
            minute = min;

            String formattedMinutes = "" + min;
            String formattedHour = "" + hourOfDay;

            if (hourOfDay < 10) {
                formattedHour = "0" + hourOfDay;
            }

            if (min < 10) {
                formattedMinutes = "0" + min;
            }

            textTime.setText(formattedHour + ":" + formattedMinutes);
        }
    };

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {

    case TIME_DIALOG_ID:
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
        return timePickerDialog;
    }

    return null;
}

Answer: You can do this with following code:
private TimePicker timePicker;

    timePicker = (TimePicker) dialog.findViewById(R.id.timePickerDialog);

    if(DateFormat.is24HourFormat(getActivity()){
        timePicker.setIs24HourView(true);
    }else {
        timePicker.setIs24HourView(false);
    }
    // here you can define your hour and minute value.
    timePicker.setCurrentHour(hour);
    timePicker.setCurrentMinute(minute);

Comment: Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, 2);
        cal.get(Calendar.HOUR) = returns hour
        cal.get(Calendar.MINUTE) = returns minutes
Comment: this is the main question that how could i set hour as after 2 hours from current time hour
Answer: You can try below code
     SimpleDateFormat sdf = new SimpleDateFormat("hh:ss");
    Date date = null;
    try {
        date = sdf.parse("07:00");
    } catch (ParseException e) {
    }
    Calendar c = Calendar.getInstance();
    c.setTime(date);

    TimePicker picker = new TimePicker(getApplicationContext());
    picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
    picker.setCurrentMinute(c.get(Calendar.MINUTE));

How to set custom Time in TimePicker


Overriding __new__ and __init__ in Python

Question:
Possible Duplicate:
Python's use of __new__ and __init__ ?

The way I understand it, __init__ is different from a constructor in Java, because __init__ only initializes an object that has already been constructed implicitly (because __init__ is called after __new__). However, everything that I have ever needed to define has used this latter property of a 'constructor' in Java. What would be a case in which a programmer would want to override __new__?
EDIT: For the record, I ask partly because I'm wondering what would be the advantage/disadvantage to overriding new vs. using a separate classmethod in the accepted answer to this question:
Moving Beyond Factories in Python
Comment: Not quite an exact duplicate in my eyes
Answer: __new__ actually happens before an object exists. It's a static method of the type. Uses of __new__ are when you want to control the creation of new objects, e.g. a singleton. If your __new__ always returns the same instance of an object, it's a singleton. You can't do that with __init__.
Generally, in "python as Guido intended it to be" you shouldn't use __new__ more than once a month :)
Comment: That makes sense. So is this (the accepted answer below) a case where overriding __new__ would also be appropriate?

http://stackoverflow.com/questions/3571773/moving-beyond-factories-in-python
Answer: __new__ is for creating new object instance, __init__ is for initializing it.
I think if you design an immutable type, you have to initialize it in __new__, see namedtuple for example (also Python's use of __new__ and __init__?).


Upload file to S3 directly instead of using temporary storage

Question: I have one file uploading form in Drupal 8 where I am uploading 3 different assets and they might be around 2gb or more in size.
I have the s3fs module enabled and configured properly, but (due to temporary storage) it is consuming lot of time to upload to web server. First it uploads in the "/tmp" directory and then to "s3". I have also tweaked apache settings to handle large file uploads.
Is there any way to speedup this upload process?
If it's possible how to fetch the uploaded file properties for edit action on the same form?
Answer: The s3fs module page mentions the use case of uploading very large files directly to S3:

If your users need to upload very large files to your site, you might want to use the S3FS CORS Upload module. It enables CORS-based uploads, allowing files to be uploaded directly to S3, rather than being routed through your server.

The s3fs module alone only has a S3 client for PHP and will not do what you want. However it is still useful as the recommended module depends on it.
Comment: I have checked with the same already but still with CORS module file uploads in the "/tmp" directory first and then to "s3" which take same time with S3FS and via cloudfront, browser given me bad response as large file takes too much time to upload..
Comment: @VaibhavGidde did you use an existing or standard file field rather than an 'S3fs Cors File' type? There's nothing in the docs telling you to do this, but the test is to look in the source of an add/edit node page and see if s3fs_cors.js is loaded. If you upload a large file, do you see the 'Uploading: x%' progress and the buttons greyed out? (Not 100% sure it's still not making unnecessary calls to Drupal, but large files are going via Amazon when my Nginx/Apache site says they're too big.)
Answer: A simple workaround will be to upload the file directly to S3 using AWS CLI.
Just in order to create the file in your Drupal database upload a small file with the same name which will later be overwritten by the file you are going to upload using AWS CLI.


Android's RGBToHSV method doesn't work

Question: According to the document, android.graphics.Color has a method called RGBToHSV which can convert RGB values to HSV, this is what the document tells me:
public static void RGBToHSV (int red, int green, int blue, float[] hsv)

Convert RGB components to HSV.

hsv[0] is Hue [0 .. 360)
hsv[1] is Saturation [0...1]
hsv[2] is Value [0...1]

Parameters

red:  red component value [0..255]
green:    green component value [0..255]
blue: blue component value [0..255]
hsv:  3 element array which holds the resulting HSV components.

But when I write a program to test it, it doesn't work any way.
float[] hsv = new float[3];

RGBToHSV(255, 255, 0, hsv);

Log.i("HSV_H", "" + hsv[0]);   // always output 0.0

Is it a bug ?
Answer: What are your expected values? To me it seems to be working.
The code I used:
float[] hsv = new float[3];
android.graphics.Color.RGBToHSV(255, 255, 0, hsv);
Log.i("HSV_H", "Hue=" + hsv[0]);
Log.i("HSV_H", "Saturation=" + hsv[1]);
Log.i("HSV_H", "Value=" + hsv[2]);

The results:
Hue=60.0
Saturation=1.0
Value=1.0

This was run using a project targeting Android SDK 1.6 (API level 4) on a 1.6 emulator.
Answer: The result for hsv[1], hsv [2] is a decimal number, so you have to multiply by 100 to get the percentage.
Answer: There is no indication that RGBtoHSV is assigning any values to the hsv array; try something like this:
RGBtoHSV(255, 255, 0, hsv);

And then check the value of hsv[0].
Comment: public static **void** RGBToHSV()  I think this method will return nothing
Comment: Check my answer again; I failed to read the method definition when I posted my answer.

Android's RGBToHSV method doesn't work


Como usar o required e verificar se os dados já foram inseridos?

Question: Como é que eu posso fazer com que seja obrigatório ao utilizador preencher todos os campos do formulário?
 Eu tentei pôr required no código mas por algum motivo não aparece a mensagem que costuma aparecer quando ponho o mesmo código num ficheiro HTML.
Código index.php:
<!doctype html>

<meta charset="utf-8">
<title>Site</title>

<form name="calendario" id="calendario" method="post" class="form-horizontal">

<button type="button" class="close" data-dismiss="modal">×</button>

Agendamento

Primeiro Nome

                <input type="text" class="form-control" name="pnome" required="required">

Número de telemóvel

                <input type="text" class="form-control" name="numerotmv" required="required">

Local da Sessão

                <input type="text" class="form-control" name="localsessao" required="required">

<input class="form-control" name="data" type="date" required="required">
Data

<input class="form-control" name="hora" type="time" required="required">
Hora

<button type="submit" onClick="verificarAgendamento()" class="btn btn-primary btn-lg">Agendar</button>

    </form>

Código agendamento.php:
<?php

include("conecta.php");

$pnome=$_POST['pnome'];
$numerotmv=$_POST['numerotmv'];
$localsessao=$_POST['localsessao'];
$data=$_POST['data'];
$hora=$_POST['hora'];

$pesquisaUsuario = mysqli_num_rows(mysqli_query($conexao,"
SELECT nome FROM agendamento
WHERE numerotmv = '$numerotmv'
"));

if($pesquisaUsuario >0){
echo 1;
}else{
mysqli_query($conexao, "insert into agendamento (pnome, numerotmv, localsessao, data, hora) values('$pnome','$numerotmv', '$localsessao','$data','$hora')");
echo 0;
}

?>

Estrutura da minha base de dados:
Obrigado a todos que gastaram o seu tempo precioso ao ler este post para me ajudar. Sou muito grato.
Comment: Pelo que eu pude perceber você esta utilizando jQuery para fazer o envio do formulário via HTTP POST pro seu arquivo PHP. Testei exatamente o código postado e ele me retorna ReferenceError: $ is not defined. você se certificou de fazer a importação correta do jquery ?
Answer: Acredito que o problema esteja no evento que você está utilizando pra realizar a requisição. Como você utiliza o evento onClick, a função esta sendo chamada independente dos inputs estarem ou não preenchidos, sendo assim recomendo que faça as seguintes alterações no seu código:

Remova o evento onClick do seu button:

    <button type="submit" class="btn btn-primary btn-lg">Agendar</button>

Faça a importação do jQuery caso ainda não tenha feito:

Deixe seu javascript dessa forma:

document.querySelector('form').addEventListener('submit', (e) => {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "agendamento.php",
        data: $("#calendario").serialize(),
        success: function (resultado) {
          if (resultado == 0) {
            alert("Erro");
          } else {
            alert("Agendamento feito com sucesso");
          }
          return false;
        }
      });
      $('#calendario')[0].reset();
      return false
    });

Em document.querySelector('form').addEventListener('submit', (e) => { }) o formulário é selecionado e é adicionado o evento de submit. O segundo parâmetro é o callback que será executado quando o evento for chamado, basicamente é o código da sua função verificarAgendamento


When to use low discount factor in reinforcement learning?

Question: In reinforcement learning, we're trying to maximize long-term rewards weighted by a discount factor $\gamma$:
$
\sum_{t=0}^\infty \gamma^t r_t
$.
$\gamma$ is in the range $[0,1]$, where $\gamma=1$ means a reward in the future is as important as a reward on the next time step and $\gamma=0$ means that only the reward on the next time step is important. Formally, $\gamma$ is given as part of the problem, but this isn't the case in practice where choices must be made on how to build the states, actions, and rewards of the MDP out of real world information.
In my experience (which is far from comprehensive), the value of $\gamma$ used is typically high, such as 0.9 or 0.99 or 0.999. (Or simply 1.0 if we are restricted by a finite time horizon.) But this seems mostly arbitrary.
My question is: when might we use a low, but non-zero value for $\gamma$, such as 0.5 or 0.1?
I'm asking mostly out of curiosity, the question occurred to me and I thought I'd see whether any of you had seen something like this before.
The intuitive answer would be that $\gamma$ is low when the immediate rewards are much more important than long-term rewards, but that's strange. What environment could you be in where you still care about the future, but not that much? What kind of policy would you learn in an environment like that?
Answer: The discount factor doesn't really have a well founded interpretation as far as I know. It seems to have been introduced primarily so that the problem is more mathematically or computationally well-behaved. People have interpreted it as a "life-span risk" factor, (i.e $\gamma$ is your chance of dying each time-step, so you should weigh anticipated future reward accordingly). Personally I don't really buy it, because this could just be easily built in to the environment itself. Another interpretation is that it mimics human time preferences, but I don't really buy this either -- the point of reinforcement learning isn't really to mimic human behavior. You can see a bit more discussion on these points in the introduction here.
Anyway, if you're willing to accept either of these interpretations, you could say your agent is operating in a highly risky environment, where it has 50 or 90% chance of dying each time step. Or maybe you're trying to learn really impulsive and short-term decision making. Or maybe your "reward" is denominated in some rapidly hyperinflating currency which loses 90% of it's value every time step (but this goes into the interpretation of what "reward" is).
You may also be interested in these two articles: https://arxiv.org/pdf/1910.02140.pdf and https://arxiv.org/pdf/1902.02893.pdf
Comment: Another interpretation, which makes sense to me, is that actions taken now have a limited impact into the future, depending on the task being performed.  I think if an action taken at step 1 has the same impact on the reward at step N as the action at step at N-1, then the discount factor should be 1.  If every reward is an independent function of the current action, it should be zero.  Shorter time horizons will make the reward assignment problem easier and allow you to train faster.


Can I improve linear model coefficient estimates using group information without working it into model?

Question: I am fitting a linear model in order to predict future observations. The training data consists of about 1000 observations. Each observation comes from one of 10 individuals, which means I have about 100 observations per individual. The future data to which the model will be applied will come from different individuals than those in the training set. The individuals are expected to vary systematically (they could have different slopes, intercepts, etc).
I have an understanding of how one would usually account for this individual-level variation in a linear model. Dummy variables, interaction terms, partial pooling, etc. However, these options only work for prediction if I have the same individuals in the prediction data as I do in the training data. This is not the case in my situation; the individuals at prediction time are not the same individuals at training time, so the model cannot contain any terms which represent the individual.
My question: if my sole concern is in getting the best coefficient estimates possible, is there anything more I can do beyond fitting the linear model as usual with no accounting for the individuals?
I came across some info about clustered standard errors, but the entire purpose of that seems to be in correcting for underestimation of error-term variance. It doesn't seem like introducing clustered standard errors will at all impact the coefficient estimates themselves (what I really care about), though please correct me if I'm wrong.
Some relevant points:

Thankfully, there is strong reason to believe that the individuals in the training set are a representative sample of individuals that will be seen in the wild.
I have no information that could account for individual-level variation. In the training data, I only have indicators for individuals. There is no way to model the individuals' slopes/intercepts as depending on some underlying property of the individuals.

Visual explanation:
<code>library(ggplot2)

set.seed(123)
n_individuals <- 5
obs_per_individual <- 100

df_params <- data.frame(individual = factor(1:n_individuals),
                        slope = rnorm(n = n_individuals, mean = 1, sd = 0.2),
                        intercept = rnorm(n = n_individuals, mean = 0, sd = 0.2))

df_list <- list()
for (i in 1:n_individuals) {
  df_iter <- data.frame(individual = rep(df_params$individual[i], obs_per_individual),
                    x = runif(n = obs_per_individual))
  df_iter$y <- df_params$intercept[i] + df_iter$x * df_params$slope[i] + rnorm(n = obs_per_individual, mean = 0, sd = 0.1)
  df_list[[i]] <- df_iter
}
df <- bind_rows(df_list)

ggplot(df, aes(x = x, y = y)) +
  geom_point(aes(color = individual), size = 0.5) +
  geom_smooth(aes(color = individual), method = "lm", fullrange = TRUE, se = FALSE, size = 0.5) +
  geom_smooth(mapping = aes(x = x, y = y), method = "lm", fullrange = TRUE, se = FALSE, linetype = "dashed") +
  scale_color_discrete(guide = NULL)

</code>

The dashed line is the overall regression line. Colors represent individuals. Is there any way to improve upon the regression in a way that does not rely on knowing the individuals in advance at prediction time?
Comment: This is totally normal. You are asking for marginal instead of conditional estimates.
Comment: @usεr11852, please expand your comment slightly and post as an answer ...
Comment: @BenBolker: I tried to expand it. (and stopped myself from using $\gamma$) :)
Answer: When estimating a mixed effects model we have to distinguish between marginal (sometimes called "unconditional") and conditional estimates. Conditioning refers to whether these estimates are subject-specific or not. In a way, all models other than conditional GLMMs produce some variation of a marginal estimators. Please note that while I mention "subjects" here, this extends to an arbitrary level on nesting.
The practical implications of this distinction is that when we are making estimates about new "unseen" individuals, e.g. subjects $s_{n+1}$ and $s_{n+2}$, we can only predict their marginal estimates. That is because we assume that any difference between them and our training sample will be due to random variation which is by definition "0" in expectation. (For example in a single-level mixed effects model with $y_{i,j} = X_{ij}\beta + Z_{ij}u_i + \epsilon_{ij}$, our working assumption for the random effect $u_i$ is that $u_i \sim N(0,\sigma^2 D)$.) As such having conditional estimates for $s_{n+1}$ and $s_{n+2}$ is inapplicable; if we assume there are any systemic differences between these new subjects and our training sample, those differences will be realised in the fixed effects ("explanatory variables") rather than the random effects ("nuisance parameters") of our model.
Two relatively mature reference on the matter are: A Comparison of Cluster-Specific and Population-Averaged Approaches for Analyzing Correlated Binary Data (1991) by Neuhaus et al. and Marginalized multilevel models and likelihood inference (2000) by Heagerty and Zeger; CV.SE has a related thread on Difference between marginal and conditional treatment effect? Relating to regression vs. propensity score methods that will be handy to check too.  West et al.'s "Linear Mixed Models: A Practical Guide Using Statistical Software" (see Sect. 2.3.2 on the "The Marginal Model Implied by an LMM" particularly) is also a good and easy-to-follow resource on the matter.


Why does the complex phase plot look exactly like the root locus diagram?

Question: BRIEF BACKGROUND
Basically here's an interesting discovery I made (probably not an original discovery) when playing around with MATLAB the other day. I was basically just trying to make a good visualization of complex valued plots and trying to implement an HSV (hue, saturation, value) model of coloring a complex function.
But my first step was just to plot the phase and magnitude separately with standard MATLAB colorings and this is when I made the interesting discovery that the phase plot of a complex valued function looks exactly like the root locus diagram of that function. This obviously cannot be a coincidence as when I change the poles and zeros the root locus diagram looks exactly the same.
For those who are not familiar with root locus diagrams, they are useful tool in control systems to know where the poles and zeros of a system go when you change the feedback gain. If your open loop gain transfer function $L(s)$ is described by a polynomial and has certain poles and zeros when it is connected in a feedback system with a gain $K$ the poles and zeros of the total system move as $K$ is increased or decreased.
Feedback System
MATLAB CODE
<code>clearvars
clc
clf
format long

%% Complex Plotting Tools
% Setup our grid of complex values to cover the complex plane
z_real = linspace(-5, 5, 1000);
z_imag = linspace(-5, 5, 1000);
[RealZ, ImagZ] = meshgrid(z_real, z_imag);
z = RealZ + ImagZ * 1j;

% Set up the coefficients of our complex polynomial
% Define a function based off the numerator/denominator coefficients

zrs = [-1]';
pls = [-2+1j, -2-1j, -3]';
[num_poly, den_poly] = zp2tf(zrs, pls, 1);
f = @(x)(polyval(num_poly, x) ./ polyval(den_poly, x));

% Print the roots of the polynomials
disp(roots(num_poly));
disp(roots(den_poly));

% Plot the complex magnitude in these plots
figure(1)
hold on
grid on
surf(RealZ, ImagZ, log(abs(f(z))), 'EdgeColor', 'none');
colormap jet
colorbar

% Plot the complex phase in these plots
figure(2)
hold on
grid on
surf(RealZ, ImagZ, rad2deg(angle(f(z))), 'EdgeColor', 'none');
colormap jet
colorbar

%% Root Locus Plot
% Generate a pole/zero plot of the same system
% Generate a root locus plot of the same system

F = tf(num_poly, den_poly);

figure(3)
hold on
grid on
pzplot(F);

figure(4)
hold on
grid on
rlocus(F);
</code>
PLOT DIAGRAMS
Magnitude Plot of Complex Function
Phase of a Complex Function
Pole Zero Diagram
Root Locus Diagram of Complex Function
QUESTION
So my question is this: Why does the phase plot of the complex valued function look exactly like its corresponding root locus diagram? I'm going to work on this myself to see if I can figure it out but figured I'd toss this question out to the larger community.
Comment: Intriguing question...
Comment: This [article](https://dcsl.gatech.edu/papers/3DBodePlot.pdf) has some common points with your issue.
Comment: Why not ask to the author of this blog : https://gandhiviswanathan.wordpress.com/2014/10/07/domain-coloring-for-visualizing-complex-functions/ ?
Comment: About the locus of roots of parametric complex functions, see [here](https://math.stackexchange.com/q/2611435/305862) a question of mine.
Answer: Let $L: \mathbb{C}\to\mathbb{C}$ be the loop transfer function.
A necessary and sufficient condition for a point $s\in\mathbb{C}$ to be on the root locus is the angle criterion. Specifically,
$$0 = 1 + K L(s) \implies \measuredangle \frac{-1}{K} = \measuredangle L(s) \implies \pi = \measuredangle L(s).$$
That is, it is a point $s$ of the root locus is such that the phase of $L(s)$ to is $\pi.$ That phase is very special, because it is where you often run into "wrap-around" issues when you colour the phase plot. You can see this if you look carefully at your phase plot of $L(s).$ Notice points on the root locus are precisely where there is a crossing from $180^\circ$ to $-179^\circ.$
So this is just an artifact of the angle criterion.
Comment: Ah thank you very much! I was just about to get back on here and post an edit to my question to say "I know it occurs at a phase transition because when you look at the 3D view the lines are along a discontinuity". But thank you this is a very clear and concise answer to the question.
Comment: @saribeiro no problem. I was intrigued by the question actually! Great question.


What is wrong with my proof that this is an equivalence relation

Question: I need to prove that the relation $a_1b_1=a_2b_2$ is an equivalence relation for the set $\{(a, b): a, b \in \mathbb{Z}, a,b \ne0\}$
I've done the following:

Reflexivity: $a_1b_1=a_1b_1$

Symmetric: $a_1b_1=a_2b_2 \iff a_2b_2=a_1b_1$

Transitive: $a_1b_1=a_2b_2 \text{ and } a_2b_2=a_3b_3 \Longrightarrow a_1b_1=a_3b_3$
since you can substitute $a_2b_2$ with $a_1b_1$

I feel like all of the above obviously follow (I hope...)
Now the problem is that this relation according to the question isn't an equivalence relation for the set $\{(a, b): a, b \in \mathbb{Z}\}$
But I feel like my proof still holds for that second set as well? What am I doing wrong?
Comment: Are you sure you have the subscripts correct? Would expect this to be about rational numbers as an equivalence class of numerator denominator pairs.
Comment: What does the question actually say? Copy it verbatim, if you can. It would be odd for a question to imply that a statement can be proved (implied by asking you to provide proof) and at the same time not.
Answer: The simple answer to your question is that yes, the relation $R$, defined as $(a_1,b_1)R(a_2,b_2)\iff a_1b_1=a_2b_2$ is indeed an equivalence relation on $\mathbb Z^2$, not only on $\{(a,b)|a,b\neq 0\}$. However, I strongly suspect that the relation you were really meant to examine is the relation
$$(a_1,b_1)R(a_2,b_2)\iff a_1b_2=a_2b_1$$ which is not an equivalence relation if you allow $a_1, a_2$ to be zero. For example, $(1,1)R(0,0)$ is true in such a case, and so is $(0,0)R(1,2)$, however $(1,1)R(1,2)$ is not true.
In fact, $(a,b)R(0,0)$ is always true :)

But more importantly, let me share my two favorite quotes from two of my TAs from back when I was a freshman

My dear colleague, "obvious" is not a word that is allowed to be in you vocabulary until you are at least a postgrad.
Well if its obvious, it shouldn't take us more than a minute to prove, right? Surely we can spare a minute.

In other words, as a student, when proving something, do not just claim the entire statement is "obvious".
What I would expect from a beginner student when proving that a relation is an equivalence relation is basically this (with empty lines filled out, of course).

Statement: Relation $R$ on $A$ is an equivalence relation.
Proof:

$R$ is reflexive. By definition, $R$ is reflexive if, for every $a\in A$, we have that $aRa$ is true. Let $a\in A$ be an
arbitrary element. Then,
_____________________________________________________________________________________________________________________________________________________________________________________________, and therefore, $aRa$ is true. Since $a$ was arbitrary, this proves $R$
is reflexive.
$R$ is symmetrical. By definition, $R$ is symmetrical if, for every $a_1, a_2\in A$, the statement $a_1Ra_2\iff a_2Ra_1$ is true.
Let $a_1, a_2\in A$ be arbitrary. Then,
________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________...
$R$ is transitive. By definition, $R$ is transitive if, for every $a_1, a_2, a_3\in A$, we know that if $a_1Ra_2$ and $a_2Ra_3$,
then $a_1Ra_3$. Let $a_1,a_2,a_3\in A$ be arbitrary elements. Let us
also assume that $a_1Ra_2$ and $a_2Ra_3$.
Then,_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ which means that $a_1Ra_3$. Because we started with the assumption
$a_1Ra_2$ and $a_2Ra_3$, this proves the implication $(a_1Ra_2\land
> a_2Ra_3)\implies a_1Ra_3$. Because all three elements were arbitrary,
this proves the implication is true for all elements of $A$, which
proves $R$ is symmetric.

Now, admittedly, the proofs are rather wordy, and they could be shortened, but only if you know what it is that you are shortening. And just saying "oh, all three statements are obvious" is not it. For one thing, in a good proof, even if it skips over some steps, one will always know what a given symbol represents, and what quantifier the variable is bound by. For example, in my proof, in step $1$, you can see that $a$ is an arbitrary element of $A$. We know that whatever is written about $A$ must be true for every element of $A$.
In your case, when you say "Oh, it's reflexive because $a_1b_1=a_2b_2$", this is not clear.


How can I save Excel worksheets in a single workbook as workbooks with their data

Question: How can I save Excel worksheets in a single workbook as workbooks with their data?
I've been able to load the workbook into python with:
import pandas as pd
sheets = pd.read_excel('File.xlsx', sheet_name=None)
new_sheet=sheets.keys()

My issue is how to make the different sheets as data-frame using pandas with their name and save it in the same directory.
Answer: Try this:
import pandas as pd

df=pd.read_excel(File.xlsx', sheet_name=None)
sheet_names=df.keys()

for sheet_name in sheet_names:
    sheet_name=pd.DataFrame(df[sheet_name].head())
    sheet_name.to_csv(str(sheet_name)+'.csv', index=False)

Note: Ensure your 'File.xlsx' is in the same directory as your code file.


Relationships between nodes and display in a special order

Question: I have two content types: 1) Team member and 2) office
There are about 150 team member nodes that need to be associated with 50 offices. When a team member is added to the site, there should be an auto complete field, where the name of the office, the member is in, can be selected.
After saving, the team member information should show up at the office which she has just been associated with. (Name, title and photo should be displayed - which could be done with Display Suite's view modes.)
In addition, each team member is associated with a specific function (head, partner, principal, consultant). This is done with taxonomy. On the office page, however, the team members associated with that office should be ordered according to the team members' taxonomy function. Those team members with the taxonomy term "head" should be displayed first, those with taxonomy term "partner" second, "principal" third etc.
How can this best be achieved? I have taken Entity Reference and Nodereference modules into consideration. Can this be done with Display Suite only or do I need to create a Views block?
Answer: I solved this with the modules: entity reference and corresponding entity reference, setting up a relationship between the "team member" and "office" content type.
Then I created a view and added A Contextual Filter choosing the reference field from the "team member" content type as a contextual filter. Then I added: "Provide default value" "Content ID from URL" in the "When the filter value is no available" option.
After that I chose "Content: Function" field as a sort criteria so that the team members will be displayed according to the taxonomy order. Finally I added the block, which I created with the view, to the office page content type under manage display.


Find the solution for the partial differential equation

Question: Find the parametric solution of the PDE
$$xu_x -xyu_y - u=0$$
which follows the side condition $u(s^2, s)=s^3$
The solution uses another method rather than finding the general solution using parametrization of $x,y$ into $s,t$.
It says $X(s,t)=Ae^t$  and $Y(s,t)=Be^{-xt}$ and $U(s,t)=Ce^t$.
(I understand that they found $X(s,t)$ using $dx/dt$. I can't seem to solve $Y(s,t)$ and $U(s,t)$.
I also don't undestand how to find the constans A,B and C after.
Comment: What's $y_y$? I suppose it should be $u_y$.
Comment: yes thank u for the correction @kaster
Comment: $u(x=s^2,y=s)=s^3$ or $u(y=s^2,x=s)=s^3$ ?
Answer: $xu_x-xyu_y-u=0$
$xu_x-xyu_y=u$
$u_x-yu_y=\dfrac{u}{x}$
Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx}{dt}=1$ , letting $x(0)=0$ , we have $x=t$
$\dfrac{dy}{dt}=-y$ , letting $y(0)=y_0$ , we have $y=y_0e^{-t}=y_0e^{-x}$
$\dfrac{du}{dt}=\dfrac{u}{x}=\dfrac{u}{t}$ , we have $u(x,y)=tf(y_0)=xf(ye^x)$


Mapping numeric values to string

Question: Here I have a dataset:
Dataset
I want to map numeric value to CASE_STATUS values
df.CASE_STATUS.value_counts()

CERTIFIED              2615623
CERTIFIED-WITHDRAWN     202659
DENIED                   94346

Here is what I do but have a string indices must be integers, not str error:
for dataset in df:
    dataset['CASE_STATUS'] = dataset['CASE_STATUS'].map( {'CERTIFIED':1 , 'CERTIFIED-WITHDRAWN': 1, 'DENIED': 0} ).astype(int)

How should I map values to CASE_STATUS?
Answer: I don't think you need a for loop for this:
dict_map = {'CERTIFIED':1 , 'CERTIFIED-WITHDRAWN': 1, 'DENIED': 0}

df['CASE_STATUS'] = df['CASE_STATUS'].map(dict_map).astype(int)

Answer: To get a mapping you can use the pandas method to_dict.
For example :
mapping = df.reset_index().CASE_STATUS.to_dict()

Note that I use reset_index() before to be sure that index go from 0 to n (n = number of row you have).
Then you can convert your column with a simple map :
df["CASE_STATUS"] = df["CASE_STATUS"].map(mapping)

It is interesting to keep a track of your mapping transformation, that's why the dictionnary creation is an important step.

Mapping numeric values to string


Selecionar apenas primeiro lugar do primeiro semestre - Código SQL Server

Question: Fiz este código para o SQL Server para selecionar quantas vezes o piloto "AsdoVolante" ficou em primeiro lugar no primeiro semestre de 2017. Porém o mesmo não funciona. O que poderá estar mal?
SELECT P.Data, Nm.Nome, epp.PosicaoFinal
FROM Prova P, Piloto Nm, EquipaParticipaProva epp
WHERE epp.PosicaoFinal = (SELECT PosicaoFinal FROM EquipaParticipaProva where PosicaoFinal = 1)
HAVING Nm.Nome ='AsdoVolante' AND P.Data BETWEEN '2017-01-01' AND '2017-06-30';

Answer: SELECT P.Data, Nm.Nome, epp.PosicaoFinal
FROM Prova P, Piloto Nm, EquipaParticipaProva epp
WHERE epp.PosicaoFinal = (SELECT epp.PosicaoFinal FROM EquipaParticipaProva where epp.PosicaoFinal = 1)
HAVING Nm.Nome ='AsdoVolante' AND P.Data BETWEEN '2017-01-01' AND '2017-06-30';

Comment: @EliasVentura Obrigado pela sua resposta mas o código não funciona :(
Comment: @TiagoS O codigo do Elias não funcionava
Answer: Tem que primeiro verificar qual erro está exibindo.
De toda forma, tente o select abaixo:
        SELECT P.Data, Nm.Nome, epp.PosicaoFinal
        FROM Prova P, Piloto Nm, EquipaParticipaProva epp
        WHERE epp.PosicaoFinal = 1
        AND Nm.Nome ='AsdoVolante' AND P.Data BETWEEN '2017-01-01' AND '2017-06-30';
Answer: Você pode obter tais informações realizando o vínculo das informações com JOIN e restringindo no WHERE:
SELECT Nm.Nome,
       COUNT(epp.PosicaoFinal) AS quantidade
  FROM Prova P
       INNER JOIN EquipaParticipaProva epp ON epp.IdProva = P.IdProva
       INNER JOIN Piloto Nm ON epp.IdPiloto = epp.IdPiloto
 WHERE epp.PosicaoFinal = 1
   and Nm.Nome = 'AsdoVolante'
   and P.Data BETWEEN '2017-01-01' AND '2017-06-30';
 GROUP BY Nm.Nome


Coefficient in support vector regression (SVR) using grid search (GridSearchCV) and Pipeline in Scikit Learn

Question: I am having trouble to access the coefficients of a support vector regression model (SVR) in scikit learn when the model is embedded in a pipeline and a grid search.
Consider the following example:
from sklearn.datasets import load_iris
import numpy as np
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import Pipeline

iris = load_iris()
X_train = iris.data
y_train = iris.target

clf = SVR(kernel='linear')
select = SelectKBest(k=2)
steps = [('feature_selection', select), ('svr', clf)]
pipeline = Pipeline(steps)
grid = GridSearchCV(pipeline, param_grid={"svr__C":[10,10,100],"svr__gamma": np.logspace(-2, 2)})
grid.fit(X_train, y_train)

This seems to work fine but when I try to access the coefficient of the best fitting model
grid.best_estimator_.coef_

I get an error message: AttributeError: 'Pipeline' object has no attribute 'coef_'.
I also tried to access the individual steps of the pipeline:
pipeline.named_steps['svr']

but could not find the coefficients there.
Answer: Just happened to come across the same problem and this post
had the answer:
grid.best_estimator_ contains an instance of the pipeline, which consists of steps. The last step should always be the estimator, so you should always find the coefficients at:
grid.best_estimator_.steps[-1][1].coef_


Convertendo colunas em linha concatenando os resultados

Question: Tenho o seguinte select :
SELECT pedido, item FROM pedidos

Como pego o resultado dele em colunas e passo para linha concatenando com -? Exemplo:

Resultado

pedido    item
1         batata
1         arroz
1         feijão
1         tomate

Esperado:

pedido   item
1         batata - arroz - feijão - tomate

Answer: Use GROUP_CONCAT:
SELECT pedido, GROUP_CONCAT(item SEPARATOR ' - ') as item FROM pedidos

Teste no SQLFiddle
Comment: Perfeito, Obrigado.


How does one override default icons used to dislpay uploaded files from within a module instead of a theme?

Question: I'm attempting to add a custom icon for file uploads via a module. However, all I'm finding online is advice on using a theme function (How to change File field icons (without changing core)?). I want this in a module to make it work across various themes. I found file_icon_path, but am not sure how to implement it. How would this be done in a module?
Answer: I think you would want to do something along these lines:
function YOURMODULE_theme_registry_alter(&$theme_registry) {

  if (!empty($theme_registry['file_icon']['function'])) {
    $theme_registry['file_icon']['function'] = 'YOURMODULE_file_icon';
  }

}

and then create YOURMODULE_file_icon() based upon the core theme_file_icon():
/**
 * Returns HTML for an image with an appropriate icon for the given file.
 *
 * @param $variables
 *   An associative array containing:
 *   - file: A file object for which to make an icon.
 *   - icon_directory: (optional) A path to a directory of icons to be used for
 *     files. Defaults to the value of the "file_icon_directory" variable.
 *
 * @ingroup themeable
 */
function YOURMODULE_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);

  return '';
}

and change up either $icon_directory to point within your module and include all of the various file type icons there, or do a switch or if on the $mime type and grab them from wherever you want, eg, if it's the special mime type you want, grab them from your module's directory, otherwise, grab them from the core/default directory.
Comment: not sure, I'd take a look at the `file_icon_path()` function in the `file.module` and make sure your naming conventions match what it is expecting, both with respect to the path as well as the image filenames.  Most notably make sure your path is prefaced with something along the lines of `drupal_get_path('module', 'YOURMODULE')` and that the icons are in the expected name.ext format.
Comment: Being dense here.  If theme_file_icon is a normal theme function, then why the manual registry alter?  Shouldn't a theme registry rescan pick up the override?
Comment: I'm also curios why core builds up the img manually, rather than via theme('image')
Comment: I was curious about your latter comment as well @MPD, but that's what it does, I just copied it verbatim. As for your first, it's my understanding that the scans just pick up theme overrides, eg, THEMENAME_xyzzy(), not MODULENAME_xyzzy(), but I could very well be mistaken and making this far too difficult.
Comment: @Jimajamma, thanks for your help, that seems to be working to register the function, which I can apparently name whatever, but I'll keep that naming convention. Now, I have changed the $icon_directory to my module's icon directory (mymodule/images/icons), but it looks like the file_icon_url() function doesn't like it for some reason and returns no path. What could I be doing wrong now?
Comment: @Jimajamma, it was operator error :). I had my icon file named wrong. I needed to add an "-x-" to it. I hate that there are different naming conventions for these files, but I guess there's a reason. Thanks again for your help.


Como fazer essa consulta com JPA?

Question: Gostaria de duas soluções para essa pergunta, uma usando uma typedquery normal e outra usando o criteria devido a sua grande versatilidade para o código.
Eis a minha query:
      TypedQuery<Pessoa> query = em.createQuery("SELECT a FROM Pessoa a where
      a.dataNascimento <> '12/9/2000'", Pessoa.class);

como fazer para retornar essa query?
Aqui esta o erro:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.time.LocalDate

Comment: Você mesmo já deu a solução com `TypedQuery` em sua pergunta. Isso significa que você só quer a solução com `Criteria`? Ou por algum motivo você também quer algo mais com `TypedQuery` que não seja isso que você já deu na pergunta?
Comment: @VictorStafusa O problema é que quando rodo essa query ela dá um erro !!
Comment: Qual erro? Coloque o erro na pergunta.
Answer: Tente modificar seu where "a.dataNascimento <> '12/9/2000'"
como o igual "="
ficaria assim: "a.dataNascimento = '12/9/2000' "
//////////////////////////
Bom, acho que o problema gira em torno do retorno do método que contém sua query, certo?
Bom, acho que o este método deve resolver, usando o setParamenter...kkk
public Pessoa buscaDataNasc(String dataNascimento){
        Pessoa pessoa = this.manager.createQuery("select p from Pessoa p where p.dataNascimento = :pDataNascimento")
                .setParameter("pDataNascimento", dataNascimento).getResultList();

        return pessoa;
    }

ps: não tenho muita afinidade com a API de criteria.
Comment: já tentou "a.dataNascimento = '12-09-2000' "?
Comment: Tentei fazer dá o mesmo erro! Acho que temos que usar o .setParameter
Comment: Sim ! Lembrando que eu quero <> e não =
Comment: vc tem razão, temos que usar o .setParameter.
Bom, simulei um contexto semelhante a esse problema e funcionou.
Comment: Tá dando erro porque data é String e não Date. No setParameter passa um Date e não uma String. Para converter a String para Date dá uma olhada aqui: https://www.mkyong.com/java/how-to-convert-string-to-date-java/
Comment: Pois é, levando em consideração que questão não deixou claro o tipo do dado "dataNascimento" e a assinatura que ele trata a variável na query (12/9/2000), supus que tratava-se de uma String. Por isso o método recebe o parâmetro String  dataNascimento.
Answer: Pelo que parece o erro é no formato da data...
Eu tive um erro parecido, o problema esta na busca pelo formato '12/9/2000' que é formato Brasileiro, e o BD geralmente trabalha com o internacional que é '2000-09-12'
Tente fazer a busca dessa maneira...
 "a.dataNascimento = '2000-09-12' "
Comment: A questão não é formato, mas "java.lang.ClassCastException: java.lang.String cannot be cast to java.time.LocalDate"

Como fazer essa consulta com JPA?


Dynamic security constraint configuration in Java web.xml

Question: I currently have a REST API that must be authenticated via BasicAuth, but later some other method.
It's setup in Tomcat 6 with realms and I have the following in my web.xml,
<security-constraint>
    <web-resource-collection>
        <web-resource-name>document</web-resource-name>
        <url-pattern>/rest/document/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>document</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>BASIC</auth-method>
    <Realm-name>Tomcat-Advance-Authentication-Realm</Realm-name>
</login-config>

This works fine for URLs like /rest/document/*.
My question is, does anyone know if it's possible or how to define other URLs dynamically without building and re-deploying?
For example another security constraint,
<security-constraint>
    <web-resource-collection>
        <web-resource-name>secure</web-resource-name>
        <url-pattern>/rest/secure/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>secure</role-name>
    </auth-constraint>
</security-constraint>

Thanks
Answer: Whenever you make a change to web.xml, the web application needs to be restarted to pick up those changes.
If you need dynamic security constraint consider building a custom configurable filter and a related property file in wich you can define protected resources(for example).
Comment: Thanks Luca, I think we'll go that route. Eventually we want to use Spring 3 Security to handle this.


Hopital rule does it fail in this particular example?

Question: $$\lim_{n\to\infty}{\dfrac{n}{1}}$$
Using L'hopital's rule
$$\dfrac{d}{dn}n=1 , \dfrac{d}{dn} 1=0$$
So:
$$\lim_{n\to\infty}{\dfrac{n}{1}}=\lim_{n\to\infty}{\dfrac{1}{0}}=\infty$$
is this correct?
Comment: The hypotheses for the rule are not satisifed for ${n\over 1}$.
Comment: Why David Mitra?
Comment: because infinity over one is not indeterminate
Comment: But
     lim  1/x = oo
     n→0
Comment: and what does that have to do with the question?
Comment: by the way, in the future please use latex for math formatting.
Comment: OpenBSD is so slow when using latex
Comment: Okay, l'Hôpital's rule requires **first** that you check that the numerator and denominator both have the same limit, and that the limit is either zero or infinite. this is not the case for your example, so you can't use l'Hôpital's rule. The limit of 1 is 1
Comment: I don't understand
Comment: http://en.wikipedia.org/wiki/L'H%C3%B4pital's_rule
Comment: @Integralsandseries please read this http://en.wikipedia.org/wiki/L'H%C3%B4pital's_rule   and before asking your questions check if your question is a valid question in terms of the definition of what you are asking!
Comment: You can't just apply the rule willy nilly. There are conditions that have to be met in order for it to be valid. Those conditions are not met, so it is not valid to use the rule.
Comment: What are those conditions?
Comment: I have said it already. The numerator and the denominator have to have the same limit, and that limit has to be 0 or infinity. also both have to be differentiable.
Comment: LHR cannot apply into this indeterminate form
Answer: l'Hospital is not applicable here because your limit is of the form
$$\lim_{x\to\infty} \frac{f(x)}{g(x)}$$
Where $f(x) = x, g(x) = 1$ and thus
$$\lim_{x\to\infty} f(x) = \lim_{x\to\infty} x = \infty, \quad \lim_{x\to\infty} g(x) = \lim_{x\to\infty} 1 = 1$$
l'Hospital requires the two limits to be equal and to be either $0$ or $\pm\infty$.

Remark: The rule applies in a slightly more general condition:

If $\left|\lim\limits_{x\to c} g(x)\right|=\infty$, the limit of $f$ is irrelevant.

This works because if $f$ is bounded (For example $\left|\lim\limits_{x\to c} f(x)\right| <\infty$), the limit will always be $0$ and if it is not, we are in the form $\frac{\pm\infty}{\pm\infty}$ from the original rule.
Comment: @DavidMitra Included the remark and a little elaboration how to prove it starting at the stronger requirement.
Comment: The "extended rule" also applies if $\lim f$ doesn't exist (which makes the version non-trivial).
Comment: @DavidMitra couldn't you substitute $\lim\sup$ and $\lim\inf$ in that case?