Exactly what does "diatonic" mean?

Question: Is the meaning very context dependent, or can it be defined in general terms? Does the meaning change by author or period?
Sometimes it's used to refer to anything that stays within a specific tonal key or context, but sometimes when people talk about diatonic scales they refer to seven note scales specifically, even though other scales (like pentatonic) can be diatonic too. Sometimes it's just used as opposite of "chromatic".
According to Encyclopedia Britannica:

Diatonic, in music, any stepwise arrangement of the seven "natural" pitches (scale degrees) forming an octave without altering the established pattern of a key or mode—in particular, the major and natural minor scales. Some scales, including pentatonic and whole-tone scales, are not diatonic because they do not include the seven degrees.

But in Sound on Sound we can read that church modes are diatonic too, so it's not really about major and natural minor scales:

The definition of a diatonic scale is that there are five whole-tone and two semitone intervals in the series and that the semitones must always be separated by at least two whole-tones. Using '2' to symbolize the whole-tone steps and '1' for the semitone steps, the major diatonic scale corresponds to the interval series 2212221. No matter what note you start on, following this prescription yields a major diatonic scale — the white keys starting on C is one example. It turns out that all possible diatonic scales are constructed by starting somewhere in the major diatonic scale and continuing until you reach the same note you started on. Those are generally referred to as the church modes: Dorian for 2122212, Phrygian for 1222122, Lydian for 2221221, and so on.

Are harmonic and melodic minor not diatonic then? The i V i progression isn't diatonic?
According to Wikipedia, "diatonic" can apply to:

Musical instruments, intervals, chords, notes, musical styles, and kinds of harmony

And also puts a time context to the concept

They are very often used as a pair, especially when applied to contrasting features of the common practice music of the period 1600–1900.

Even when staying within similar contexts, the concept can take various very similar forms, but that still differ in something important. There's maybe a place where the definitions converge? Or is it just one of those concepts that vary among authors?
Exactly what does "diatonic" mean?
Comment: My answer is on the question - 'Can a diatonic scale have sharps and flats?' Sadly, there is more than one 'definition'.
Comment: I find this an interesting q and await answers from cognoscenti.  For me *diatonic* is close/synoymous to *scale* and *tonality*.
Comment: I like this question as it goes on the ground of our completely unsure knowledge and ignorance  of fundamental terms in music theory.  ;)
Comment: Very related: [this answer](https://music.stackexchange.com/a/35777/9724).
Comment: There are very few words (if any) that have an "exact" meaning.  Almost all words have shading of meaning depending on context.
Answer: As others have mentioned, the word diatonic comes from ancient Greek music theory and literally means "through [whole] tones."  Ancient Greek music tuned its scales using intervals of perfect fourths called tetrachords.  A diatonic tetrachord was one that was tuned with two whole tones on the top, and the remainder left on the bottom (roughly a semitone), like descending E-D-C-B in our modern scale.
These tunings in ancient Greece were contrasted with chromatic methods of tuning the tetrachord, which generally involved intervals smaller than whole tones and therefore often resulted in some consecutive semitone-sized intervals, like we find in our modern chromatic scale.
The reason this background is important is because it gave birth to two somewhat different ways of using the term diatonic today:
(1) The first comes directly from Greek scale construction.  By adding an additional diatonic tetrachord (A-G-F-E) to the E-D-C-B one I mentioned above, we can get a complete descending scale for an octave: E-D-C-B-A-G-F-E, with a distinctive pattern of whole steps and half steps.  (I give the scale in descending order, as that was typically how Greeks would think of tuning it.)
Those notes were also the "white notes" on our modern piano.  This pattern derived from the Greek diatonic scale thus gave birth to all the diatonic medieval modes, from our modern C major and A natural minor scales, to the Dorian, Phrygian, Lydian, and Mixolydian modes, all employing that same diatonic scale from ancient Greece.  In that original sense of diatonic, all the modes using that specific set of notes with its pattern of whole steps and half steps (like the white keys on a piano) are derived from a "diatonic scale."
(2) The second usage comes later historically, not emerging until around the 18th century when our modern major/minor key system came into place.  During the late 16th century, there was a strong revival of interest in ancient Greek music theory that began in Italy and spread more widely.  With it, the concept of things like chromatic tunings became of more interest.  Chromatic notes became associated specifically with notes outside of the standard diatonic scale (consisting, again, mostly of what we think of as the "white notes" on the piano).
Thus, when major and minor keys became standard in the 18th century, the word diatonic retained its association with the "primary notes of the scale," while chromatic referred to notes "outside the primary scale."  For major keys, the seven standard notes were thus diatonic, and any accidentals could be considered chromatic notes.  For minor keys in classical style, it was a bit more complicated, as the 6th and 7th scale degrees often were employed in both raised and lowered forms.  Traditionally, the word diatonic related most directly to the so-called natural minor, because of the rationale from point (1) above.
However, modern music theory sources are inconsistent with the way they use diatonic in relationship to minor keys.  Generally speaking, standard uses of both the raised and lowered forms of scale degrees 6 and 7 in minor are often discussed as "diatonic" in many modern music theory books.  That is, the leading tone is generally raised in dominant function chords.  The sixth scale degree can be raised to progress melodically in smooth motion to the leading tone.  The sixth scale degree is generally flattened in other contexts (especially when leading to scale degree five) and the seventh sale degree may also be flattened to progress melodically to the lowered sixth.  All of these are often thought of as standard "diatonic" patterns in minor, while more exotic uses of chromaticism with scale degrees 6 or 7, or uses of other accidentals on other scale degrees, would be considered "chromatic."

This sidesteps the question of whether melodic and harmonic minor scales are diatonic, which is really a matter of opinion and how exactly you create the formal definitions.
From my perspective, the usefulness of the term diatonic in the second sense is not about scales specifically, but rather about whether particular notes, intervals, and chords are considered "chromatic" or not.  To my mind, if the goal of the word diatonic now is to determine the standard uses of notes of the scale, then a leading tone in minor is necessary in classical style, so it's obviously "diatonic" by the second meaning.  Intervals and chords built using that leading tone are also, by extension, "diatonic."  Hence, the part in the OP's original question that asks whether i-V-i is "diatonic" is that such a progression obviously is, according to the second meaning.
But is a harmonic minor scale "diatonic" though?  I'd personally say no.  My rationale is that generally when people speak of "diatonic" in relation to scales, they are using that historical definition (1), with its specific pattern of whole steps and half steps.  Some would allow other scales to be labeled "diatonic" too, but the criteria get increasingly loose if we were to admit harmonic minor (with its augmented second) into the mix.
On the other hand, chords and harmonic progressions that use the standard minor key accidentals are thought of as "diatonic" according to definition (2).  By that definition, we might consider a use of a raised 6th scale degree fine (and "diatonic") if necessitated by melodic motion, but a purely coloristic use of the raised 6th degree (as in a simple i-IV-i) progression might be thought of as a "chromatic" variant of the iv chord.
I think the usage I outlined in the last couple paragraphs accords with how standard music theory texts often use the terms today, but there is still some variation in official definitions and use.
Answer: The definition that I've seen most often (composition, harmony, analysis, counterpoint, and form books for the most part) relates to the Common Practice Period key structure. Some extension are made to earlier forms. (I don't remember seeing the term used much for post-romantic music.)
In major keys, "diatonic" refers to melodies and harmonies using notes from that key. For minor keys, "diatonic" refers to scale steps 1,2,b3,4,5 and both b6 and b7 and 7. Both form of the mutable steps (6 and 7) are termed "diatonic." If a modulation or even a tonicization occurs, one may use diatonic to refer to either key depending on what's needed. This leads to the  next paragraph.
One cannot define "diatonic" without some reference to the term "chromatic." Music that stays in a single key for the most part with a few chromatically altered notes may be said to use "inessential chromaticism." "Inessential" means that one can analyze the piece without worrying about the chromatic notes. Perhaps Schenkeristas would say that the chromaticism disappears in deeper structures. These would things like a secondary dominant, a Neapolitan Sixth, an Augmented Sixth, perhaps an augmented or diminished chord now and then. (I would like to extend "diatonic" to these harmonic structures and to using accidentals to create a half-step in things like trills or neighbor tones, but I haven't found anyone else doing this. I just use the idea for myself in composition.)
Some music (Wagner, Chopin, Mozart, Bach, Gesualdo, Beethoven, etc.) write music where the chromatic parts are fundamental to the structure. (Schenker's deep structures contain these chromaticisms.) They are not small-scale deviations from the "diatonic" structure but essential. (Called in some of the books, "essential chromaticism.")
In pre-Baroque music, I've seen the term diatonic used to refer to pieces that do not need accidentals to switch modes. Of course, the Bb vs B (or B vs H) contrast seems to be called diatonic by some authors and chromatic by other.
The original usage for Greek tetrachords classifies them by the terms diatonic, chromatic, and enharmonic. The meanings of these terms has changed but he words linger on.
Comment: 'One cannot define "diatonic" without some reference to the term "chromatic."'  Mmm, that's my understanding — that diatonicism is about scales and note sets that mostly involve intervals of two (or more) semitones, as opposed to chromatic scales and note sets which are only single semitones apart.
Comment: In CPP harmonic, the minor mode is treated as a single object. One can derive the three scales, but all three are often used in the same piece. Only raised  6  with lowered 7 together seems to be avoided (probably because this sounds a bit like a major scale formed a second below the tonic.) Also the augmented chord on III isn't common though uses in the late 19th century. Likewise (and this is the only thing I have found universally avoided) is using the raised 6 as an upper neighbor to 5 (probably because half-step neighbors are really popular.)
Answer: According to my trusty 'bible' - aka 'Oxford Companion to Music' -
Diatonic scales are the major and minor, made up of tones and semitones, (inc. +2 in the harmonic minor) as distinct from the chromatic scales, made entirely of semitones. Thus the modes are also diatonic.
Diatonic passages, intervals, chords and harmonies, all constructed from the notes of the prevailing key are, whilst chromatic passages, intervals, chords and harmonies are not.
Some authorities won't include harmonic and melodic minor notes, and define the intervals of diatonic scales to be the well known TTSTTTS.
I have a feeling there's not one correct answer...
Comment: Indeed. Can the altered scale be diatonic? It's a mode of melodic minor... But if not, is E7 diatonic to A minor? I'm not sure what I believe anymore :)
Comment: @user45266 - if all minor scales contain diatonic notes, therefore are diatonc, thn yes, of course, any mode of melodic (or harmonic) minor will be diatonic. Just like Dorian, Phrygian et al. IF...
Answer: Diatonic is each scale you can play equal to the scales with the white keys. So any other mode that can be fitted in a same pattern of 5 whole tone steps and 2 half tone steps arranged in the same way as the white keys of a keyboard is diatonic.
This means: all scales  like wwhwwwh, whwwwhw, hwwwhww, wwwhwwh, wwhwwhw, whwwhww, hwwhwww, will always have a pattern ww and www if they have a range more than an octave.
As we see the pitch doesn't play a role and neither the root tone of the scale.
Examples:
All major scales and all natural minor scales,
all church modes without accidentals and
all Greek modes build on 5 w and 2 half steps as described above.
All  intervals derived from this scales are diatonic intervals.
So far what I know without looking consulting other sources.
N.B.
The Greeks had diatonic scales built of 2 tetrachords downstep like e,d,c,b,a,g,f,e and as we can read in wiki they also had "chromatic scales" with other half steps and "enharmonic scales" with quarter steps.
https://en.wikipedia.org/wiki/Musical_system_of_ancient_Greece
Mind that there are 2 definitions of "diatonic scale":
a) the traditional classical definition
b) the modern extended definition
I'm posting here a google translation of the German wiki site, which is more detailed than her English sister:
The root tone series c-d-e-f-g-a-h corresponds to the white keys of the keyboard. These are the notes of the C major scale.
Diatonic scales are usually seven-degrees (heptatonic) scales, dividing the octave space into five whole and two semitones. They differ from non-ionic ladders by the following necessary characteristics:
All scale steps are derived from different root tones, which is externally reflected in that their names all begin with different letters.
Between adjacent stages, there are no excessive or reduced intervals.
For example:
The "classical" diatonic scales (major, minor, and church modes) additionally fulfill the condition that they can be composed (by adding a further whole-tone step) of two diatonic tetrachords. Also, the tones of these scales can be obtained by fifth layering.
The seven pitches of any diatonic scale can also be obtained by using a chain of six perfect fifths.
Any sequence of seven successive natural notes, such as C–D–E–F–G–A–B, and any transposition thereof, is a diatonic scale.
In extension of this original strict definition, sometimes even those scales are called diatonic which merely fulfill the condition of subdividing the octave into five whole and two semitones. Examples are the acoustic and the altered scale.
In addition, according to the present understanding, also scales can be regarded as diatonic, containing less than seven tones, such as. As the anhemitonic-pentatonic ladders, which divide the octave space in three whole steps and two thirds.
The diatonic scales in the narrower sense ("classical" diatonic scales) also include the church tones and the modal scales that today draw on them.
In the broader sense  these scales are also diatonic:
the melodic minor scale upwards
the altered scale used mainly in jazz
the acoustic scale
the anhemitonic-pentatonic ladders
Not diatonic scales
These scales are not diatonic or not completely diatonic:
the harmonic minor scale, as it contains an excessive second (hiatus)
the gypsy ladders, because they contain excessive seconds (hiatus)
the whole-tone scale, since the last whole-tone step needed to reach the octave is in reality a diminished third (in the notation ais-c from c)
the chromatic scale
the modes with limited transposition possibilities of Olivier Messiaen
My conclusion:
Now  deriving chords and intervals of these scales in a broader sense (extended definition) will lead to a confusion that we better talk about diatonic chords and intervals derived from the scales defined in the classical meaning.
The following list e.g. counts all 3 kind of minor scales to the diatonic scales:
Diatonic scales (German)
Comment: Agree with most of this - but don't think an aug2 from harmonic minor is enough of an indiscretion to exclude it!
Comment: I'm not sure whether I got what you mean: You say the harmonic minor scale is diatonic too. O.k. , this will then be the extended meaning, yes?
Comment: Some believe it is, some don't. I do.
Comment: Smile ... as some questions here (especially of mine) are still disqualified as opinion based. ;)
Answer: The general way that this is used is "using only notes which can be found in one of the major scales".
I think most people would take issue with Brittanica about the pentatonic - the pentatonic scale is a subset of a major scale, and therefore is diatonic, at least in my reasoning. (Whole tone is not though.)
A diatonic instrument is only capable of making major scale notes (leaving aside things like note bending). For example, diatonic harmonicas (versus chromatic ones).
Diatonic harmony contains chords (or sequences) which again only use major scale notes. Therefor, a min 7 chord is diatonic, as it uses a subset of the major scale notes (even though it does not use all of them).
No, harmonic and melodic minor are not diatonic. Neither is a minor chord followed by its dominant seventh. For instance no major scale contains these notes:
C / D / Eb / F /G / B
which are the notes in Cmin and G7.
Answer: I agree with the Encyclopedia Britannica in restricting the definition of diatonic and chromatic to within the Western heptatonic scales.
The way the Wikipedia article opposes diatonic and chromatic in different applications also makes sense to me. This distinction evolved at the interface of when melody gave rise to harmony in the Western context, as key-consciousness became a factor, marking the start of the Common Practice period in the early Baroque era.
I would say that it is instructive to conceptualise this as a continuum, from the purely diatonic like 1st species counterpoint to heavy late Romantic chromaticism. Beyond these borders, pentatonic and modal tonality (with their absence of key-defining leading tones) past the diatonic border, and whole-tone harmony and atonality at the chromatic end.
Hence, within the boundaries of "Common Practice" in the Western canon, there are varying definitions of "diatonic", which the Wikipedia article gives a good rundown of. All agree that:

major scales
natural minor scales

... form the bedrock of what it means for an interval, a melody and a harmony to be "diatonic". Where they differ is how "diatonic" the other forms are:

harmonic and melodic minor scales;
augmented fourth chords and half- and fully diminished 7th chords, which arise from these extended minor scales;
other chords with accidentals outside the key (Neapolitan 6th, secondary dominants, chromatic mediants).

So different authors do have different definitions.
Answer: This is something that gets needlessly convoluted:
Diatonic simply means "belonging to a specific scale". My only references are the ones you've already posted, it's just that the definition gets skewed.
So B is diatonic in the key of C major, but G# is not. Eb is diatonic in the key of C Dorian, but is not diatonic in the key of C Lydian.
Whether a note is diatonic, therefore, depends on the note and the scale in question. You can't answer the question without both pieces of information.
Comment: It doesn't as there are lots of scales that aren't diatonic.
Answer: If you are willing to dare to challenge the dictionary definition you will find great value in accepting that diatonic is the same as 'di-tonic' – two tonics.
The two tonics are the first and fifth notes (I and V) as the V is harmonically closest to the I.
This is exactly why modern music theory is built on fifths – the fifth is where the scales increment – first C, then G is the next key, then D ... a fifth up, etc.
Now look at the composition of each fifth interval, such as CDEFG.
CDEFG's intervals are WWHW.
WWHW is also the interval pattern for GABCD.
Point being that major scales are build on overlapping patters of WWHW ... each V becomes the I for the major scale of the next incremental key (incrementing by the number of accidentals).
Would you like minor you say?
Ok, why not go backwards ... WHWW ... going down by fourths.
Each of these two patters is 'diatonic' because the beginning and end are the same ... a "W" ... like a puzzle piece so they fit end to end in each direction... like a puzzle piece where the left side is the inverse of the right side so they perfectly fit.
A pattern like HWWW isn't diatonic. It's the pattern of a mode.
A pattern like HHWW can't work because the two H's are together. In diatonic patterns:
1) Matching ends so they can fit like puzzle pieces.
2) Two or three W's between the H's ... as they overlap at the V note ... the I note of the next key is the V note of the previous key.
Comment: Please stop trying to push this definition. The route word is dia which is "through, across" rather than  di which is two.
Comment: Well as it's correct ... and I've explained why ... and no one has yet explained why it's wrong, why are you opposed to this insight?

Two ... across ... point to point ... two tonic system... I explained why ... the explanation is why the conventional definition falls short. If the explanation is correct then why is the conclusion unreasonable?

The only reason it's become dia-tonic is to convey that it's reversible.

What's unreasonable about this?
Comment: There's a lot of problems: 1. you are double counting. The full pattern WWHWWWH so the WWHW double pattern you mention makes no sense in terms of the construction and the fact it overlaps with the next scale pattern built on the dominant is irrelvant. 2. There's not two tonics. There's one which is the first scale degree by definition. The fifth is the dominant. 3. The circle of 5ths has nothing to do with scale construction and even if you base scale construction on it, you would end up with the lydian scale not the major scale. There's more, those are what will fit in this comment.
Comment: 1. Oops. you're right. They don't overlap. Wrong word. They concatenate to bring you to the tonic of the next key. WWHW + WWHW = WWHWWWHW ... brings you to D, two keys upward.
2. There's no two tonics. The V becomes the I for the next key.
3. Yes, the circle of fifths isn't used for scale construction.
Comment: All of your explanations are based on the circle of 5ths which has nothing to do with the definition of diatonic. So if you agree with 3, why does most of this post talk about the circle of 5ths? You are stretching the definitions you are using so much it muddies the water which is the exact opposite point of this question.
Comment: @Dom I've not made any reference to the circle of fifths in my explanation and just stated to you that I agree it has nothing to do with definition of diatonic. I stated that the interval pattern that defines major and minor scales and keys are diatonic - the two 'tonics' being the the I and V as the V is harmonically closest to the I and as such is what's use to denote the start of the next key ... for example C to G.

The term circle of fifths doesn't appear in my explanation. I see why you introduced it but I don't see what is wrong with my clarification or methodology in my answer.
Comment: @Dom  If keys are not built on WWHW and WHWW, each of length 'fifth', then why is  G the next key up from C?

I see there are websites calling these the "major pentachord" and "minor pentachord."
Comment: You are doing it again. The next key is irrelevant when just talking about a diatonic scale pattern which is why I say you keep bringing up the circle of 5ths. That's the only reason anything close to a dominant key gets mentioned as it's not part of any definition of diatonic.  I'm not going to continue to argue points against your non standard definitions when I keep bringing up points you don't want to address. No one else mentions other keys in their answer for a reason.
Comment: The diatonic scale pattern is created by overlapping the major/minor pentachord.
You can alternatively concatenate them to arrive one note further being the first note of two keys up.

Thank you for being specific so I could clarify.
Comment: You say that modes are not diatonic. Of course they are, they contain the same notes as the parent major! Please explain.
Comment: @Tim  Bad wording or just wrong on my part. They are diatonic but the two tonics aren't on the 1 and 5 which is why they're modes.
Answer: Thank you all for nice thread of discussion. There is some light on that. I shall explain here in most simple and most convincing way.
Actually, it is quite easy to understand why it is called as di-a-tonic scale. It basically means a scale with TWO (di) tonic centers.
The one tonic (root) note is, (say) 'C' in C-Maj. scale.
The second tonic (root) note is (say) 'A' as root note in A-min. scale.
Thus same set of notes creates TWO (di) centers forming major and minor scale hence called diatonic scale.
Comment: It's a nice way to think of it, but by this definition, each scale actually has seven "tonics", one for each mode. @Athanasius wrote correctly when he explained that Western music's "diatonic" scales were named for the ancient Greek "diatonic" scales. A brief explanation and etymology is given here: https://en.wikipedia.org/wiki/Diatonic_scale#History

Exactly what does "diatonic" mean?


How to install 32-bit packages on a 64-bit CentOS

Question: We have a lot of 32-bit CentOS 6 servers with custom rpms built for i386 and i686 architectures in our own RPM repos.
We now have some 64-bit CentOS 6 servers, but would like to be able to install the 32-bit packages from the 32-bit repos.
I know that Debian supports "multiarch" that allows one to install 32-bit libraries and packages. What is the CentOS equivalent?
Answer: In yum.conf you'll see a line like this:
multilib_policy=best
Change it to:
multilib_policy=all
This will allow yum to install 32-bit packages without you having to specify *.i686 specifically.
Comment: You can also specify the packages explicitly by adding .i386 or .i686 to the end of the package. Example: `yum install libstdc++.i686`
Comment: I've done that too. That doesn't work. (There is no multilib_policy line there, but I added one.)
Comment: I've found that http://h10025.www1.hp.com/ewfrf/wc/document?cc=us&lc=en&dlc=en&docname=c03585955 has useful information. `yum groupinstall "Compatibility Libraries"` seems to work.
Comment: Actually, installing "Compatability Libraries" still doesn't fix the problem. yum cannot see the 32-bit packages in the repo.
Answer: CentOS has multilib support. If your software is 32 bit and is a rpm, you can try to yum install it. Is the RPM properly built, and you've got access to the CentOS yum repositories it should hopefully be able to satisfy any 32 bit dependency (if available in repo)
If you search your 64 bit CentOS repos, you will find a lot of 32-bit packages listed. CentOS Wiki excerpt:
x86_64 installation by default will install iX86 32-bit packages on
a 64-bit installation for compatibility purposes.

Comment: with `multilib_policy=all`, or did you try `yum install packagename.i?86`, also, what package does it say is not available? your custom rpm? have you tried copying that rpm to the box locally and then running `yum install /path/to/package.rpm`?
Comment: yum installing it does not work: it does not see the packages.
Comment: I've also tried yum groupinstall "Legacy Software Support" but I get an error that the group does not exist.
Comment: what does yum say when you try to install your package?, also are you able to install on 32 bit CentOS but not 64?
Comment: I am trying to install i386 packages on it. Yum says no package by that name is available. I can install them on 32-bit CentOS machines, yes.
Comment: yum install packagename.i386 does not work. I can manually install it using rpm, but that's no help when using Puppet.
Comment: does `yum repolist` list the repository containing the packagename?
Comment: @Petter_H yes, yum repolist shows it. And I can do a `yum info` for noarch packages. But not for i386/i686 packages that I want to install.
Comment: I'm wondering if this is a problem with the repo. Do the i386 packages need to be listed separately in the x64_64 directory of the repo?
Comment: That looks like the problem. I needed to symlink the i386 packages in the x64_64 directory of the repo, and rebuild the metadata. After a yum clean metadata`, it looks like yum can see the 32-bit packages now.
Answer: The way all the major repos solve this is to actually copy the relevant 32-bit packages into the 64-bit repository. You can see this from a careful inspection of any such repo (CentOS, Fedora, etc.).
So, after you copy all the 32-bit packages to the 64-bit repo and re-run createrepo --update ... you should be able to install them. Since this can use a lot of space, I suggest hard linking them rather than copying them.


WinError 267 The directory name is invalid

Question: I tried this code in jupyter notebook, and this error occured.
Error : [WinError 267] The directory name is invalid: 'plantdisease/PlantVillage/Pepper__bell___Bacterial_spot/0022d6b7-d47c-4ee2-ae9a-392a53f48647___JR_B.Spot 8964.JPG/'

I'm using python 3.6 in anaconda environment, I tried running this code but it showed error. I can't figure out what the problem is.The file location actually exists at the given location, still it shows invalid.
image_list, label_list = [], []
try:
    print("[INFO] Loading images ...")
    root_dir = listdir(directory_root)
    for directory in root_dir :
        # remove .DS_Store from list
        if directory == ".DS_Store" :
            root_dir.remove(directory)

    for plant_folder in root_dir :
        plant_disease_folder_list = listdir(f"{directory_root}/{plant_folder}")

        for disease_folder in plant_disease_folder_list :
            # remove .DS_Store from list
            if disease_folder == ".DS_Store" :
                plant_disease_folder_list.remove(disease_folder)

        for plant_disease_folder in plant_disease_folder_list:
            print(f"[INFO] Processing {plant_disease_folder} ...")
            plant_disease_image_list = listdir(f"{directory_root}/{plant_folder}/{plant_disease_folder}/")

            for single_plant_disease_image in plant_disease_image_list :
                if single_plant_disease_image == ".DS_Store" :
                    plant_disease_image_list.remove(single_plant_disease_image)

            for image in plant_disease_image_list[:200]:
                image_directory = f"{directory_root}/{plant_folder}/{plant_disease_folder}/{image}"
                if image_directory.endswith(".jpg") == True or image_directory.endswith(".JPG") == True:
                    image_list.append(convert_image_to_array(image_directory))
                    label_list.append(plant_disease_folder)
    print("[INFO] Image loading completed")
except Exception as e:
    print(f"Error : {e}")

[SOLVED] the problem was in loading the root director make sure you're root directory is loaded, if your root directory is plantDiseases then, keep it similar, son't get deep in the directory.
Comment: BTW I've only skimmed the code, but it seems like catching Exception then printing it makes errors harder to diagnose since you lose the traceback.
Comment: I agree with @wjandrea, don't catch the exceptions just to print them.
Comment: Please don't put "Solved" in the title. Instead, post an answer (yes you can answer your own question), then click the checkmark to accept it, which basically marks the issue as solved.
Answer: Your path is invalid because it is not a directory. It is a file
Answer: I have changed the path to this
directory_root = 'D:\Coding files\Plant disease/x/'
x is the folder in which PlantVillage dataset is saved in


How do I install an app from Windows Store using Powershell

Question: I know if I have .appx package file, I can install it via powershell with the Add-AppxPackage cmdlet.
However, I simply want to download & install Microsoft Store packages by name.
I don't want to have to go to the Microsoft Store page, start fiddler, start the download, capture the .appx file URL and then manually download it so that I can use Add-AppxPackage.
(See how Windows OS Hub did that here)
That could be fun - but it will be flaky.
I need a robust scriptable method for managing Windows Store apps.
(There are a few software packages that are only accessible via Microsoft Store.
Everything else I can get via Chocolatey or direct msi download.)
One example that I can't yet script is installation of the HEIF Image Extensions (needed to view the image format from iPhones: *.HEIC format.
Once I install this from the Windows Store, it shows up with Get-AppxPackage
PS C:\Tools> Get-AppxPackage | Where-Object {$_.Name -eq "Microsoft.HEVCVideoExtension" }

Name              : Microsoft.HEVCVideoExtension
Publisher         : CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
Architecture      : X64
ResourceId        :
Version           : 1.0.31053.0
PackageFullName   : Microsoft.HEVCVideoExtension_1.0.31053.0_x64__8wekyb3d8bbwe
InstallLocation   : C:\Program Files\WindowsApps\Microsoft.HEVCVideoExtension_1.0.31053.0_x64__8wekyb3d8bbwe
IsFramework       : False
PackageFamilyName : Microsoft.HEVCVideoExtension_8wekyb3d8bbwe
PublisherId       : 8wekyb3d8bbwe
IsResourcePackage : False
IsBundle          : False
IsDevelopmentMode : False
NonRemovable      : False
Dependencies      : {Microsoft.VCLibs.140.00_14.0.27810.0_x64__8wekyb3d8bbwe}
IsPartiallyStaged : False
SignatureKind     : Store
Status            : Ok

What I want is the cmdlet: Download-AppxPackage so that I can do:
Download-AppxPackage -Name "Microsoft.HEVCVideoExtension"

Does anyone know how I can do this?
Comment: Probably more suited to https://superuser.com/
Comment: I submitted a [feature request](https://github.com/PowerShell/PowerShell/issues/17382) on their GitHub.
Comment: Have you tried [winget](https://docs.microsoft.com/en-us/windows/package-manager/winget/)? It can install soft from Microsoft Store.
Answer: You can now use winget to install msstore apps on windows 10 and 11.
Use winget search <app_name> --source=msstore to make a search, and use the id of the app to install and upgrade the app.
For example, to install Netflix:

First I made a search with winget search Netflix --source=msstore, I see that the app id is 9WZDNCRFJ3TJ.
I install app with winget install -e -i --id=9WZDNCRFJ3TJ --source=msstore.
I upgrade app with winget upgrade -e -i --id=9WZDNCRFJ3TJ.
Answer: store.rg-adguard.net is a GUI for generating direct download links to store apps. Peeking at the source of that page, we can piggyback off them to download the content directly, but using PackageFamilyName, rather than Name (in your example it would be Microsoft.HEVCVideoExtension_8wekyb3d8bbwe).
function Download-AppxPackage {
[CmdletBinding()]
param (
  [string]$PackageFamilyName,
  [string]$Path
)

  process {
    $WebResponse = Invoke-WebRequest -Method 'POST' -Uri 'https://store.rg-adguard.net/api/GetFiles' -Body "type=PackageFamilyName&url=$($PackageFamilyName)&ring=Retail&lang=en-US" -ContentType 'application/x-www-form-urlencoded' -UseBasicParsing
    $LinksMatch = $WebResponse.Links | where {$_ -like '*_x64*.appx*'} | Select-String -Pattern '(?<=a href=").+(?=" r)'
    $DownloadLinks = @($LinksMatch.matches.Value)

    for ($i = 1; $i -le $DownloadLinks.Count; $i++) {
      Invoke-WebRequest -Uri $DownloadLinks[$i-1] -OutFile "$Path\$PackageFamilyName($i).appx"
    }
  }
}

This is limited to the x64 version, and the path must point to a folder. It will download the package and its dependencies and save them all as PackagefamilyName(n).appx
Comment: Thanks - this is a good improvement. Not ideal as: a) I have to manualy install to find out the PackageFamilyName - and it may change. And: b) I don't know who "rg-adguard.net" are. I'll accept this as answer as probably best we can do until MS give me the cmdlet I want. They may want to divert users to the store to see ads etc.
Comment: as of: 06/25/2021 this is broken. Download-AppxPackage no longer works
Answer: Building further on AJ's Answer. Download any app from windows app store with powershell just supply a url from the store and a path for saving.
Usage:
Download-AppxPackage "https://www.microsoft.com/p/dynamic-theme/9nblggh1zbkw" "$ENV:USERPROFILE\Desktop"

C:\Users\user\Desktop\55888ChristopheLavalle.DynamicTheme_1.4.30233.0_neutral_~_jdggxwd41xcr0.AppxBundle
C:\Users\user\Desktop\55888ChristopheLavalle.DynamicTheme_1.4.30234.0_neutral_~_jdggxwd41xcr0.AppxBundle
C:\Users\user\Desktop\Microsoft.NET.Native.Framework.1.7_1.7.27413.0_x64__8wekyb3d8bbwe.Appx
C:\Users\user\Desktop\Microsoft.NET.Native.Runtime.1.7_1.7.27422.0_x64__8wekyb3d8bbwe.Appx
C:\Users\user\Desktop\Microsoft.Services.Store.Engagement_10.0.19011.0_x64__8wekyb3d8bbwe.Appx
C:\Users\user\Desktop\Microsoft.VCLibs.140.00_14.0.29231.0_x64__8wekyb3d8bbwe.App

Code:
function Download-AppxPackage {
[CmdletBinding()]
param (
  [string]$Uri,
  [string]$Path = "."
)

  process {
    $Path = (Resolve-Path $Path).Path
    #Get Urls to download
    $WebResponse = Invoke-WebRequest -UseBasicParsing -Method 'POST' -Uri 'https://store.rg-adguard.net/api/GetFiles' -Body "type=url&url=$Uri&ring=Retail" -ContentType 'application/x-www-form-urlencoded'
    $LinksMatch = $WebResponse.Links | where {$_ -like '*.appx*'} | where {$_ -like '*_neutral_*' -or $_ -like "*_"+$env:PROCESSOR_ARCHITECTURE.Replace("AMD","X").Replace("IA","X")+"_*"} | Select-String -Pattern '(?<=a href=").+(?=" r)'
    $DownloadLinks = $LinksMatch.matches.value

    function Resolve-NameConflict{
    #Accepts Path to a FILE and changes it so there are no name conflicts
    param(
    [string]$Path
    )
        $newPath = $Path
        if(Test-Path $Path){
            $i = 0;
            $item = (Get-Item $Path)
            while(Test-Path $newPath){
                $i += 1;
                $newPath = Join-Path $item.DirectoryName ($item.BaseName+"($i)"+$item.Extension)
            }
        }
        return $newPath
    }
    #Download Urls
    foreach($url in $DownloadLinks){
        $FileRequest = Invoke-WebRequest -Uri $url -UseBasicParsing #-Method Head
        $FileName = ($FileRequest.Headers["Content-Disposition"] | Select-String -Pattern  '(?<=filename=).+').matches.value
        $FilePath = Join-Path $Path $FileName; $FilePath = Resolve-NameConflict($FilePath)
        [System.IO.File]::WriteAllBytes($FilePath, $FileRequest.content)
        echo $FilePath
    }
  }
}

This correctly downloads neutral and x64 packages but untested for arm and 32bit systems. the path must point to a folder. It will download the package and its dependencies and save them all as their original file names while avoiding name collisions like chrome.
Comment: $env:PROCESSOR_ARCHITECTURE does not return the OS bitness, it returns the CPU (hardware) architecture. If you install a 32-bit OS on a 64-bit CPU, it will return AMD64. To test the OS bitness use: $CPU = if ([Environment]::Is64BitOperatingSystem) {'x64'} else {'x86'}
Comment: Thanks, it works. I didn't understand though why this fn downloads multiple versions of the same package. E.g. I tried with https://www.microsoft.com/pt-br/p/windbg/9pgjgd53tn86 and it downloaded both `Microsoft.WinDbg_1.2104.13002.0_neutral__8wekyb3d8bbwe.Appx` and `Microsoft.WinDbg_1.2103.1004.0_neutral__8wekyb3d8bbwe.Appx`
Comment: @André this script doesn't attempt to version check it just performs the download, you are welcome to share an adaptation that version checks~ I am sure it will be helpful for everyone
Comment: Gist: https://gist.github.com/mavaddat/26146d111abf62f6160b1bd02a392ba8
Comment: as of: 06/25/2021 this is broken. Download-AppxPackage no longer works
Comment: hey @DeerSpotter what package did you try to download? my example still runs on my system
Answer: function Download-AppxPackage {
[CmdletBinding()]
param (
  [string]$Uri,
  [string]$Path = "."
)

  process {
    echo ""
    $StopWatch = [system.diagnostics.stopwatch]::startnew()
    $Path = (Resolve-Path $Path).Path
    #Get Urls to download
    Write-Host -ForegroundColor Yellow "Processing $Uri"
    $WebResponse = Invoke-WebRequest -UseBasicParsing -Method 'POST' -Uri 'https://store.rg-adguard.net/api/GetFiles' -Body "type=url&url=$Uri&ring=Retail" -ContentType 'application/x-www-form-urlencoded'
    $LinksMatch = ($WebResponse.Links | where {$_ -like '*.appx*'} | where {$_ -like '*_neutral_*' -or $_ -like "*_"+$env:PROCESSOR_ARCHITECTURE.Replace("AMD","X").Replace("IA","X")+"_*"} | Select-String -Pattern '(?<=a href=").+(?=" r)').matches.value
    $Files = ($WebResponse.Links | where {$_ -like '*.appx*'} | where {$_ -like '*_neutral_*' -or $_ -like "*_"+$env:PROCESSOR_ARCHITECTURE.Replace("AMD","X").Replace("IA","X")+"_*"} | where {$_ } | Select-String -Pattern '(?<=noreferrer">).+(?=)').matches.value
    #Create array of links and filenames
    $DownloadLinks = @()
    for($i = 0;$i -lt $LinksMatch.Count; $i++){
        $Array += ,@($LinksMatch[$i],$Files[$i])
    }
    #Sort by filename descending
    $Array = $Array | sort-object @{Expression={$_[1]}; Descending=$True}
    $LastFile = "temp123"
    for($i = 0;$i -lt $LinksMatch.Count; $i++){
        $CurrentFile = $Array[$i][1]
        $CurrentUrl = $Array[$i][0]
        #Find first number index of current and last processed filename
        if ($CurrentFile -match "(?<number>\d)"){}
        $FileIndex = $CurrentFile.indexof($Matches.number)
        if ($LastFile -match "(?<number>\d)"){}
        $LastFileIndex = $LastFile.indexof($Matches.number)

        #If current filename product not equal to last filename product
        if (($CurrentFile.SubString(0,$FileIndex-1)) -ne ($LastFile.SubString(0,$LastFileIndex-1))) {
            #If file not already downloaded, add to the download queue
            if (-Not (Test-Path "$Path\$CurrentFile")) {
                "Downloading $Path\$CurrentFile"
                $FilePath = "$Path\$CurrentFile"
                $FileRequest = Invoke-WebRequest -Uri $CurrentUrl -UseBasicParsing #-Method Head
                [System.IO.File]::WriteAllBytes($FilePath, $FileRequest.content)
            }
        #Delete file outdated and already exist
        }elseif ((Test-Path "$Path\$CurrentFile")) {
            Remove-Item "$Path\$CurrentFile"
            "Removing $Path\$CurrentFile"
        }
        $LastFile = $CurrentFile
    }
    "Time to process: "+$StopWatch.ElapsedMilliseconds
  }
}

if (-Not (Test-Path "C:\Support\Store")) {
    Write-Host -ForegroundColor Green "Creating directory C:\Support\Store"
    New-Item -ItemType Directory -Force -Path "C:\Support\Store"
}

Download-AppxPackage "https://www.microsoft.com/p/snip-sketch/9mz95kl8mr0l" "C:\Support\Store"

Modified the script so that it delete old versions and only download latest.
Much thanks to Yorai Levi for the original script!
Comment: as of: 06/25/2021 this is broken. Download-AppxPackage no longer works
Answer: I've found some additional tools that I think are worth noting and hopefully may be of use to others who are using Windows Sandbox.
Although I tried to install Windows Store manually inside Windows Sandbox, that failed due to required components being missing, but this project fills in all of the gaps:
git clone https://github.com/kkkgo/LTSC-Add-MicrosoftStore

In that folder, simply run Add-Store.cmd and you will now have an operational Store App on the Start Menu in Windows Sandbox, but it is not complete as a few services have to be started also:
# 'config start=auto' is not required on Sandbox,
# but is useful for non-Sandbox environments.
SC config wuauserv start=auto
SC config bits start=auto
SC config cryptsvc start=auto
SC config trustedinstaller start=auto
SC start wuauserv
SC start bits
SC start cryptsvc
SC start trustedinstaller

Finally, make sure to log in to the Store with a Microsoft account (press the Profile at top right) after which, you should have a fully operational Windows Store app inside Windows Sandbox.
The project was built for Windows Enterprise LTSC (Long-Term Servicing Channel, designed for Windows 10 devices where the key requirement is that functionality and features don't change over time) that, like Windows Sandbox, uses a slimmed down set of features, but this project works perfectly on Windows Sandbox. The project installs four components to achieve this:
Microsoft Store
Store Purchase App
App Installer
Xbox Identity Provider


Find probability of $X_1 < X_2 < X_3 $ where $X_i$ is a random variable

Question: I have encountered this problem in the book Probability and Random Processes by Grimmett and Stirzaker.  The problem is:
Let $X_1, X_2, X_3$ be independent (discrete) random variables taking values in the positive integers and having mass functions given by $\mathbb{P}(X_i=x)=(1-p_i)p_i^{x-1}$ for $x=1, 2, ....$ and $i=1,2,3$.
Show that  $\mathbb{P}(X_1<X_2<X_3)=\dfrac{(1-p_1)(1-p_2)p_2p_3^3}{(1-p_2p_3)(1-p_1p_2p_3)}$
I actually find this kind of problems too vague, because I know how to calculate $\mathbb{P}(X\leq x)$ but I can't calculate the probability of (in)equality of different random variables $X, Y$ like $\mathbb{P}(X<Y)$. Is there a method for that?
What I tried so far is to write it down as $\mathbb{P}(X_1<X_2<X_3)=\mathbb{P}(X_1<X_2, X_2<X_3)=\mathbb{P}(X_1<X_2)\mathbb{P}(X_2<X_3)$. But then I don't know how to go further...
I apperciate your help and hints. Thanks!
Comment: not sure your last expression is correct. I would try $$\mathbb{P}[X_1<X_2<X_3] = \mathbb{P}\left[\left. X_1 < X_2 \right| X_2 < X_3 \right] \cdot \mathbb{P}[X_2 <X_3]...$$
Comment: I still have no clue how to continue.. :(
Answer: We use this law https://en.wikipedia.org/wiki/Law_of_total_probability, and the fact that the variables are mutually independent
$P(X_1<X_2<X_3)=\sum_{i=1}^{\infty}{\sum_{j=1}^{\infty}{P(X_1<X_2<X_3|X_2=j,X_1=i)}P(X_2=j,X_1=i)}$
$P(X_1<X_2<X_3)=\sum_{i=1}^{\infty}{\sum_{j=i+1}^{\infty}{P(j<X_3|X_2=j,X_1=i)}P(X_2=j)P(X_1=i)}$
By independence, $P(j<X_3|X_2=j,X_1=i)=P(X_3>j)$, and also by the law of total probability,
$P(X_3>j)=\sum_{k=j+1}^{\infty}{P(X_3=k)}$
So we have
$P(X_1<X_2<X_3)=\sum_{i=1}^{\infty}{\sum_{j=i+1}^{\infty}{\sum_{k=j+1}^{\infty}{P(X_3=k)}}P(X_2=j)P(X_1=i)}$
$=(1-p_1)(1-p_2)(1-p_3)\sum_{i=1}^{\infty}p_{1}^{}{\sum_{j=i+1}^{\infty}p_{2}^{j-1}{\sum_{k=j+1}^{\infty}{p_{3}^{k-1}}}}$
Using the fact that $\sum_{j=i+1}^{\infty}{u^{j-1}}=\frac{u^{i}}{1-u}$, you can conclude
Comment: This helps me a lot! Thanks!
Comment: Thanks  Byron Schmuland, I fixed it
Answer: For two random variables the answer is:
\begin{eqnarray*}
\mathbb{P}(X_2<X_3)&=&\sum_{1\leq j<k} (1-p_2)(1-p_3)p^{j-1}_2 p_3^{k-1}\\[8pt]
&=&\sum_{1\leq j}(1-p_2)(p_2p_3)^{j-1}\\[8pt]
&=&{1-p_2\over 1-p_2p_3}.
\end{eqnarray*}
I will leave the rest to you.
Comment: This is very similar to the solution given for the exercise. But I cant figure out how to go from the first equality to the second. Maybe it is because I'm not familiar with the notation in the summation.
Comment: Nvm, this question is exactly about this:
https://math.stackexchange.com/questions/536055/simplify-the-summation-over-ijk?rq=1


Java Polymorphism sequence

Question: public class A {
 int method(A a) { return 1; }
 static int method(B b) { return 2 + b.method((A)b); }
}

public class B extends A {
 final int method(A a) { return 4 + super.method(a); }
 int method(C c) { return 8 + this.method((B)c); }
}

public class C extends B {
 int method(C c) { return 16 + method((A)c); }
}

public class Test {
    public static void main(String[] args) {

    A a = new A();
    B b = new B();
    C c = new C();

    b.method(b);  //returns 7 (4 + 2 + 1)
    b.method(c);  //returns 15 (8 + 4 + 2 + 1)
}

}

Each class is in its own file.
Why did the first call return 7? For me it should return something else because B.method(A) is invoked and then A.(B) and then something in B should be called and not A.(A)
And why did the second call return 15?
Comment: you can use your debugger to go step by step through your code
Comment: I know which methods are called, but I dont know why they are called.
Comment: Look around for Java Polymorphism, lots of info on the web like: https://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading
Answer: There are two valid methods that can be called for b.method(b);:
final int method(A a) { return 4 + super.method(a); }
static int method(B b) { return 2 + b.method((A)b); } // inherited from A

The compiler chooses the more specific one - method(B). It doesn't matter that it is static. Static methods can be called on an instance too. See also: Is calling static methods via an object "bad form"? Why?
Now we need to resolve b.method((A)b);. b's compile time type is A so the compiler only searches in A. The argument expression's compile type is also A. The only applicable method is:
int method(A a) { return 1; }

At runtime, b is found to be an instance of B, so the overridden method in B is called instead:
final int method(A a) { return 4 + super.method(a); }

Now we resolve super.method(a);. The types involved here are exactly the same as those in b.method((A)b);, but we are using super, so the implementation in the superclass of B, i.e. in A, is called instead:
int method(A a) { return 1; }

For b.method(c);, the argument's compile time type is C, so we have three applicable methods:
final int method(A a) { return 4 + super.method(a); }
static int method(B b) { return 2 + b.method((A)b); } // inherited from A
int method(C c) { return 8 + this.method((B)c); }

Again, the most specific, method(C) is chosen.
Then we resolve this.method((B)c);. This is resolved in exactly the same way as b.method(b);.  The compile-time types are the same. The fact that the runtime type of the parameter is a C object doesn't really matter, because all C overrides is the method(C) method, which we never called when resolving b.method(b);.
Comment: great explanation!
Answer: For B valid functions are the following.
final int method(A a) { return 4 + super.method(a); }
static int method(B b) { return 2 + b.method((A)b); }
int method(C c) { return 8 + this.method((B)c); }

The overwritten method(A a) from class B
Also in reasons of overloading the static int method(B b)

Notice here static methods can also called on instances.
Now when method will be called because method is overloaded for multiple parameters it looks in which method the argument is applicable.
The function call stack for this b.method(b);  //returns 7 (4 + 2 + 1)
is

calls from class B method(B b) returns 2 + b.method((A)b)
calls in class B method(A a) returns 4 + super.method(a)
// because of super it calls not the overwritten method(A a) it calls the original
calls in class A static int method(A a) returns 1

1 + 4 + 2 -> 7
for b.method(c)

calls class B int method(C c) returns 8 + this.method((B)c);
calls class B method static int method(B b) returns 2 + b.method((A)b);
calls class B final int method(A a) returns 4 + super.method(a);
// Calls the not overwritten method(A a) because super keyword
calls class A int method(A a) returns 1

1 + 4 + 2 + 8 -> 15

Java Polymorphism sequence


Proving a certain symmetric matrix has positive determinant

Question: This problem comes arises from the Markowitz Portfolio optimization with $n$ risky assets.
Suppose $\mathbf{1} = (1, 1, ..., 1)\in\mathbb{R}^{n}$ and let $\mathbf{z}\in\mathbb{R}^{n}$ be the vector of expected returns and $\Sigma$ be the covariance matrix for the assets. I have the matrix
$$D = \begin{bmatrix}A & B \\ B & C\end{bmatrix}$$
where $$
\begin{align*}
A & = \mathbf{1}^{\top}\Sigma^{-1}\mathbf{1} \\
B & = \mathbf{1}^{\top}\Sigma^{-1}\mathbf{z} \\
C & = \mathbf{z}^{\top}\Sigma^{-1}\mathbf{z}.
\end{align*}
$$
Question: How can I prove that the determinant of $D$ is positive?
My attempt: I know $A,B,C$ are all positive because $\Sigma^{-1}$ is positive definite. Also, $D$ is symmetric, but I do not think I have enough to conclude $D$ is positive definite. I tried finding the eigenvalues, but arrived that the expression $$\lambda = \frac{A+C\pm\sqrt{(A+C)^{2} - 4(AC - B^{2})}}{2},$$
from which I could not get any further.
Comment: This is the Cauchy-Schwarz inequality for the inner product $\langle u,v\rangle = u^T\Sigma^{-1}v$.
Comment: If you turn this comment into an answer, I can mark the question as answered
Answer: I found the answer thanks to Michal's hint. Since $\Sigma^{-1}$ is positive definite, $\langle u, v\rangle =u^{\top}\Sigma^{-1}v$ defines an inner product on $\mathbb{R}^{n}\times\mathbb{R}^{n}$. By the Cauchy Schwarz inequality,
$$|\langle 1, z\rangle|^2 = B^{2}\leq |\langle 1, 1\rangle||\langle z, z\rangle|=AC$$
Hence,
$$\Delta = AC-B^2\geq 0$$


Open a Chrome tab , based on a value from a website

Question: I`m a newbie with programming but willing to learn ,
I need to make an extension for Chrome that searches for a value in a website , then opens another tab/link with the value from the initial page .
For example ,  if I visit a webpage and the field "Idkey00=maplesyrup' is in the source code ,  i need it to open automatically  another URL in different tab  with the Idkey00 value in it like :   http://mywebsite.com/maplesyrup/bla/bla.doc
Can you give me some help please?
I could do it manually but it would take forever..
Answer: The easiest way is to do it with TamperMonkey, and you should be able to use window.location to find out what the URL is.


Determine every number in the interval $[0,10]$ such that $F(x)=\cot(\pi x)$ is undefined

Question: Determine every number in the interval $[0,10]$ such that $F(x)=\cot(\pi x)$ is undefined. Justify your reasoning.
Please help this is on my calc homework and I have no idea how to solve this.
Answer: Hint: Recall that $\cot t=\dfrac{\cos t}{\sin t}$.
The cotangent of $\pi x$ is therefore  undefined when $\sin( \pi x)=0$. Note that $\sin t=0$ when $t=0,\pm \pi,\pm 2\pi,\pm 3\pi,\dots$.
Remark: I am assuming that by cot(pi)(x) you mean $\cot(\pi x)$. If you mean $(\cot(\pi))(x)$ then the function is everywhere undefined.


Having a verify error with solrj 5.5.0 and java 1.7

Question: I get a java.lang.VerifyError: Cannot inherit from final class exception when executing HttpSolrClient solr = new HttpSolrClient("http://localhost:8983/solr/mycore");
I use SolrJ 5.5.0 with Java 1.7. Other than that I use commons-httpclient 3.1. This is the detailed error I get:
Handler processing failed; nested exception is java.lang.VerifyError:     org/apache/http/params/SyncBasicHttpParams] with root cause
java.lang.VerifyError: org/apache/http/params/SyncBasicHttpParams
at org.apache.http.impl.client.DefaultHttpClient.createHttpParams(DefaultHttpClient.java:158)
at org.apache.http.impl.client.AbstractHttpClient.getParams(AbstractHttpClient.java:466)
at org.apache.solr.client.solrj.impl.HttpClientUtil.setFollowRedirects(HttpClientUtil.java:290)
at org.apache.solr.client.solrj.impl.HttpClientConfigurer.configure(HttpClientConfigurer.java:58)
at org.apache.solr.client.solrj.impl.HttpClientUtil.configureClient(HttpClientUtil.java:149)
at org.apache.solr.client.solrj.impl.HttpClientUtil.createClient(HttpClientUtil.java:125)
at org.apache.solr.client.solrj.impl.HttpSolrClient.<init>(HttpSolrClient.java:188)
at org.apache.solr.client.solrj.impl.HttpSolrClient.<init>(HttpSolrClient.java:161)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Answer: There were 2 httpcore libs(httpcore 4.0 from axis2 1.6.2 and httpcore 4.4.1 from solrj 5.5.0) in my .m2 folder. Removing httpcore 4.0 helped me to fix the problem. The reason is org.apache.http.params.BasicHttpParams class in httpcore 4.0 is a final class.


Find text in element that is NOT wrapped in html tags and wrap it with

Question:

Lorem Ipsum

  TEXT THAT NEEDS TO BE WRAPPED

List Item 1

I got the code above (it gets generated automatically so I can't manually wrap the text), I need to filter through the content of ".menu-content" and find the text that is not wrapped in a html tags and then wrap that text in a p tag.
I tried the following jQuery code:
$('.menu-content').find(':not(h3, ul)').wrap('

');

Answer: Use contents() and filter() to get text node

$('.menu-content')
  .contents() // get all child node including text and comment
  .filter(function() { // filter the text node which is not empty
    return this.nodeType === 3 && $.trim(this.textContent).length
  }).wrap('
'); // wrap filtered element with p

Lorem Ipsum

  TEXT THAT NEEDS TO BE WRAPPED

List Item 1

Comment: LEGEND! Thanks Mate
Comment: @AJDEV : glad to help :)


Can I get the command history in a screen while something is running in it?

Question: I've got a screen with a critical process running in it. I can't kill it, but I need to know the command that was used to start it. Can anyone offer a solution?
Answer: If your long running critical process is running in screen then Ctrlac will start a new screen.
You can then find the command line for the process with
ps -efww

which should show you the complete command line.
If it's not running in screen you can try Ctrlz followed by bg to suspend the command the put it in the background.
Comment: Or just log in again ;-)


getRange() increment by 12

Question: I am new to google script and have not coded for 15 years. Computer Science 2, Java …
So my question is: How do I increment my get.range() by 12 each time.
function clearRange() {
   var sheet = SpreadsheetApp.getActive().getSheetByName('DK LU Tracker');
   sheet.getRange('B4:B12').clearContent();
   //sheet.getRange('B16:B24').clearContent();
   //sheet.getRange('B28:B36').clearContent();
   //sheet.getRange('B40:B48').clearContent();
   //sheet.getRange('B52:B60').clearContent();
   sheet.getRange('B64:B72').clearContent();
   //sheet.getRange('B76:B84').clearContent();
   //sheet.getRange('B88:B96').clearContent();
   //sheet.getRange('B100:B108').clearContent(); }

That's what it is looking like and I know there is a more efficient way. Then I want to create a button and add it to my Google sheet. Attach this script to the button and voilà! Any help would be great!
Answer: You could replace the individual clearContent() calls with one call within a for loop.  For example:
  for (i = 0; i <= 96; i = i + 12)
      sheet.getRange(4 + i, 2, 9).clearContent();

With this version of getRange(), the parameters are row number, column number, and number of rows, in that order.
To create a button, follow the steps from this SO answer.

getRange() increment by 12


How to save input fields of accompanying checkboxes?

Question: I have a list a checkboxes with accompanying input text fields. If the user checks a box, the accompanying text field will be add to an array.
I am new to PHP and was wondering if anyone can help me in the right direction.
Should I use a for loop, foreach, while, unique "name" for each input, or something else?
Below is what I have so far.
<?php
if(isset($_POST['submit'])){
  $array = array();
  while(isset($_POST['check'])){
    if(!isset($_POST[$some_text]) || empty($_POST[$some_text])){
      echo "Please include your text for each checkbox you selected.";
      exit();
    }
   $array[] = $_POST['some_text];
 }
}
?>

<form>
<input type="checkbox" name="check"><input type="text name="some_text">
<input type="checkbox" name="check"><input type="text name="some_text">
<input type="checkbox" name="check"><input type="text name="some_text">

</form>

Comment: It will be more better if you use loop.
Comment: @raveenanigam Can you please explain more
Answer: Try this:
 $select = array();
 foreach($_POST['check'] as $key => $selected){
    $select[$key] = $selected;
 }

Comment: Doesn't seem to work. When I submit, this error pops up. Invalid argument supplied for foreach()
Answer: Please try this:
<?php

if(isset($_POST['submit'])){

for($i=0; $i<100; $i++)
{
    if($_POST['check_'.$i])
    {
        $array[] = $_POST['input_'.$i];
    }
}
}
?>

#################### HTML

<form method="post" action="">
<?php for($i=0; $i<100; $i++) { ?>
<input type="checkbox" name="check_<?php echo $i ?>"><input type="text" name="input_<?php echo $i ?>">
<?php } ?>
<input type="submit" name="submit">
</form>

Answer: You first need a way to associate your checkboxes with their corresponding text fields, and a way to tell them apart. For example:
<form>
<input type="checkbox" name="check[]" value="1"><input type="text name="text1">
<input type="checkbox" name="check[]" value="2"><input type="text name="text2">
<input type="checkbox" name="check[]" value="3"><input type="text name="text3">
</form>

Now you can loop through it as follows:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['check']) && is_array($_POST['check']) && !empty($_POST['check'])) {
        $array = array();
        foreach ($_POST['check'] as $value) {
            $text_field = 'text' . $value;
            if (!isset($_POST[$text_field]) || trim($_POST[$text_field]) == '') {
                echo "Please include your text for each checkbox you selected.";
                exit;
            }
            $array[] = $_POST[$text_field];
        }
    }
}

Comment: Wow! Exactly what I was looking for! Thank YOU


SBT sub project access root project data (dependency version)

Question: I have a multiple project, and I'm creating a class with it's git version in one of my subprojects.
def iUberdataCoreVersion(version: Option[String] = Some("Not a Git Repository"), dir: File) = {
  val file = dir / "UberdataCoreVersion.scala"
  IO.write(
    file,
    s"""package eleflow.uberdata.core\n  object UberdataCoreVersion{\n          val version = "${version.get}"\n
       val sparkVersion = ${allDependencies.value.filter(_.extraString.startsWith("spark")).head.crossVersion}
             |}\n""".stripMargin)
  Seq(file)
}

The dependencies are defined in the root project build.sbt file. I want to add spark version (one of my dependencies) into this file. Is there a way to pass an argument to a sub project build, or to iterate through the dependencies to discover which version of spark am I using?
Update as required in comments
The problem here is that in spark there is two versions, and at version 2 I can create it's context (to access the spark cluster) in a different way than it's in spark 1.
root
 build.sbt

lazy val subProject = project settings (libraryDependencies ++= Seq(
    "org.apache.spark" %% "spark-repl" % sparkVersion)

I have 3 sub projects, and the spark version is shared between them, that's why I've configured it this way, otherwise I could have inserted the dependencies into the subproject build file.
Consider that sparkVersion is provided as a build argument.
root
  sub
    build.sbt

Here in the subproject I want to create a file that contains the spark version. This can be done in a property file, or in a src code file, as I already do with git code. Can I receive it's value as a val when creating the sub project build?
I can access the spark version through it's context, it has a property for it, but in this specific case I want to do that before creating the context, and that's my problem.
Comment: Can you update your question with an example, showing what your Scala code needs to do? Usually, you have a dependency on `SomeLib_2.11-1.2.3.jar` in `build.sbt`, and that is the only place where you need to say what version it is. In your Scala class, you just `import com.someco.SomeClass` from the JAR, and you do not need to specify the version. Maybe I don't understand what you need
Comment: Are you trying to make sure that your root project and sub-project use the same version? If so, you can put the version numbers in a property file and read the property file in the build.sbt of each sub-project
Comment: @dirceusemighini It depends on what you mean by `access it from sub project`. As mentioned by @radumanolescu you need to be more specific. You need to be aware of the version in the code? That's a whole different question which has nothing to do with the fact that your project is a sub-project. If you just want to use the dependency in a sub-project, answer is yes, all `.sbt` files have access to each other. You can easily find samples on sbt docs.
Comment: Did you consider writing the version as val into Build.scala in the root project folder? Any sub project has access.
Comment: or just separate them into another file `dependencies.sbt` and then pick the ones you need for each project in the corresponding file, in other words put all deps with their versions in one place, and pick them as you wish. Note that all `.sbt` files in the root folder will be assembled together, so they have access to each other (just as if they were all in the same file).
Comment: @radumanolescu no in fact I'm trying to put the version of the lib in the code, because I need this before instantiating it's context class
Comment: @NaderHadjiGhanbari if I separate the dependencies in another sbt, can I access it from a sub project?
Comment: @NaderHadjiGhanbari By this I mean, that I have two project, and the dependency is defined at root, and I want to know how can I get this value in a subproject.
Comment: @radumanolescu Hi, I've just added a better explanation
Comment: I do write the version as a val in the root build.sbt file, but I didn't knew that I could access it from subprojects
Answer: We define properties in build.properties and use them in all subprojects. In this case, it's the Scala version - but it could be any string.
// ---------- ---------- multiproj/build.properties ---------- ---------- //
scala.version = 2.11.8
// ---------- ---------- multiproj/subproj/build.sbt ---------- ---------- //
val props = SettingKey[Map[String, String]]("props")

props := {
  import scala.collection.JavaConversions._
  val pf = new java.util.Properties()
  IO.load(pf, baseDirectory.value / ".." / "build.properties")
  pf.stringPropertyNames.map(p => p -> Option(System.getProperty(p)).getOrElse(pf.getProperty(p))).toMap
}

libraryDependencies ++= Seq(
  "org.scala-lang" % "scala-library"  % props.value("scala.version") % "compile->*"
, "org.scala-lang" % "scala-compiler" % props.value("scala.version") % "compile->*"
)


registering hostname using DHCP

Question: I am working on the development of a network device. When it boots up, I want it to register a domain name on the network so that a customer can easily browse to the webserver interface. Eg. http://device-name
I tried including the hostname in DHCP Option 12 and again in Option 81. I can see the hostname appearing in the DHCP clients table but not able to access the webserver using the hostname. Using the IP address of the device works fine. Similarly for pinging too...
There are 2 scenarios in which I want this to work.

When the device is connected to a local network which is in turn connected to the Internet.
Only the device and a Windows PC are connected using a Linksys router.

In both cases, nslookup  doesn't yield any result. :(
I get the error 'non-existent domain'.
Is there any workaround for this?
Since its a end-user device, I have to confine changes, if any, to the DHCP client as much as possible.
Please feel free to ask for any clarifications. Thank you so much.
Comment: Which DHCP server and client are you using?
Comment: The TCP/IP stack on the embedded device is provided by InterNiche....Server side it is a Windows machine running the DHCP server. Is that what you are asking?
Answer: You generally need server-side support for this; tools like dnsmasq can do it out of the box.
Alternatively, consider using multicast DNS/Rendezjour or UPnP for service discovery and hostname lookup.
Comment: multicast DNS is DNS without servers, generally restricted to your local network. It is implemented by the Avahi stack on Linux and the Apple Bonjour (previously Rendezvous, hence the portmanteau Rendezjour) software in OS X and Windows. You do need to install additional software to use it in Windows (and some Linux distributions), unfortunately, as well as running the daemon on your network device.
Comment: Hi Zanchey,

Thank you so much. I will check out dnsmasq (I was hoping to avoid 3rd party software as our main responsibility is to ship only the network device to the customer)

As for UPnP,I feel it is not feasible since UPNP stack is not standalone & requires network stack. We are looking for a simple DHCP client level solution.

Can you tell me more about multicast DNS/Rendezjour?

Thanks again.. :)
Comment: Hi Zanchey,

My network device is running threadX RTOS using on ARM instruction set. Is there anything similar to the Avahi stack available for threadX?

Thanks again for taking so much interest in this, I appreciate it.
Answer: Would enabling NetBios over TCP/IP work? DHCP option 46
Comment: Hi ITGuy24,

option 46 is NetBIOS over TCP/IP Node Type Option...
Have an idea what will be the node type for my device?

      Value         Node Type
      -----         ---------
      0x1           B-node
      0x2           P-node
      0x4           M-node
      0x8           H-node

Or should I choose DHCP option 47 - NetBIOS over TCP/IP Scope Option?
Comment: Some more questions for you :).
Would just enabling Option 46 take care of everything? Is it the only change I have to make?
.
Don't I have to send my NetBIOS name seperately in some specific format or something?
Comment: I am sorry I don't know.  My guess would be 0x1 B-mode as this is broadcast mode.  Please keep in mind that this will create a lot of traffic on the network especially if it is a large network.
Answer: Dynamic DNS would do exactly what you what. The DHCP server would need to open a rndc connection to the DNS server and on a successful lease, it would updated both the DNS and reverse DNS for that IP address. You could then configure within the DHCP client what name the device should be given.
This article about dynamic DNS using a DHCP/BIND server configuration on Debian might give you some idea on how to configure your own device.
http://www.debianadmin.com/howto-setup-dhcp-server-and-dynamic-dns-with-bind-in-debian.html

registering hostname using DHCP


Python pytest: capturing stdout always fails

Question: I'm trying to capture output from stdout / print statements in pytest (Python version 3.6).
This always fails:
message = 'The meaning of life is not actually 42\n'

def print_greeting():
    """print 42 to stdout"""

    # write to stdout
    sys.stdout.write(message)           # this fails

    # print to stdout
    print('Message again: ', message)   # this fails too

def test_printgreeting(capsys):
    """assert '42' was printed to stdout"""

    # capture stdout / stderr
    out, err = capsys.readouterr()
    print_greeting()

    # 42 should be in stdout from sys.stdout.write
    assert '42' in out

Results from pytest:
========================================================= test session starts ==========================================================

collected 1 item

test.py
The meaning of life is not actually 42
F

=============================================================== FAILURES ===============================================================
__________________________________________________________ test_printgreeting __________________________________________________________
test.py:42: in test_printgreeting
    assert '42' in out
E   AssertionError: assert '42' in ''
======================================================= 1 failed in 0.03 seconds =======================================================

Why is this not captured?
Answer: You need to call readouterr after you print:
def test_printgreeting(capsys):
    """assert '42' was printed to stdout"""

    # capture stdout / stderr
    print_greeting()
    out, err = capsys.readouterr()

    # 42 should be in stdout from sys.stdout.write
    assert '42' in out

Comment: My god. I pounded my head against this for like three hours. >,<
Comment: Thanks sooooo much.


Are CAL licenses necessary for this?

Question: I work in a company and I have been confronted with the following problem.
I have to mount a server with windows 2012 Server R2 in which Active Directory will be installed to control the logins of about 25 users. A part will also install a management program that about 10 people will use connecting from their computers with a client program.
The question I have is whether with the standard version I could do this or I would need to buy CALs for the 25 users that will use the Active Directory.
a greeting
Answer: Yes you will need CALs per user / device if you use Windows Server 2012 R2 Standard as soon as your user / device connects to your server.
However, Windows Server 2012 R2 Essentials includes 25 User CALs using up to 50 devices, so maybe this could be an option.
Some more info from a blogpost on Technet and this related serverfault question.

Are CAL licenses necessary for this?


Conflicting between Firebase messaging and Content Provider when i use them together

Question: I have an application that share locations between users on Google maps and sorting and retrieving database using content provider and also opening chat messages using firebase messaging but when i combine  Firebase messaging and Android content provider together the conflict happens and i found the error below , although when i use content provider or firebase messaging separately they work well and i have outputs from both, but once i combine both i have that message :
04-22 09:13:36.734 23186-23186/pioneers.safwat.onecommunity E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: /data/app/pioneers.safwat.onecommunity-5.apk
                                                                                at android.app.ActivityThread.installProvider(ActivityThread.java:5199)
                                                                                at android.app.ActivityThread.installContentProviders(ActivityThread.java:4802)
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4686)
                                                                                at android.app.ActivityThread.access$1400(ActivityThread.java:168)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1389)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:177)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5496)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                               Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: /data/app/pioneers.safwat.onecommunity-5.apk
                                                                                at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:64)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
                                                                                at android.app.ActivityThread.installProvider(ActivityThread.java:5184)
                                                                                at android.app.ActivityThread.installContentProviders(ActivityThread.java:4802)
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4686)
                                                                                at android.app.ActivityThread.access$1400(ActivityThread.java:168)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1389)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:177)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5496)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
                                                                                at dalvik.system.NativeStart.main(Native Method)

my Gradle file is (Module) :
  apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "pioneers.safwat.onecommunity"
        minSdkVersion 18
        targetSdkVersion 25
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
     compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    // compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.google.android.gms:play-services-location:10.2.1'
  // compile 'com.google.android.gms:play-services-plus:10.0.1'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.firebaseui:firebase-ui:0.6.1'
    compile 'com.google.android.gms:play-services:10.2.1'
    compile 'com.google.android.gms:play-services-maps:10.2.1'
   compile 'com.google.firebase:firebase-core:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

and my gradle file( Build):
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pioneers.safwat.onecommunity">
    <permission
        android:name="pioneers.safwat.onecommunity.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="pioneers.safwat.onecommunity.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Start">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Authentic"/>
        <activity android:name=".MainActivity"/>
        <activity android:name=".UserData"/>
        <activity android:name=".UpdateData"/>
        <provider
            android:name=".Myprovider"
            android:authorities="pioneers.safwat.onecommunity.Myprovider"
            android:exported="true"
            android:multiprocess="true"/>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="" />
    </application>

</manifest>

Comment: remove maps and location gradle lines. only use compile 'com.google.android.gms:play-services:10.2.1'
Answer: Try adding this in your manifest
<application
   ....
  android:name=".MyApplication">

 // ...
</application>

Then make a class.
public class MyApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}

Try this link for more details.


Comparação de string dando errado - Python

Question: Eu tenho essa função que verifica se o código que eu digitei está na lista de códigos, mas por mais que o código esteja na lista ele não entra no if e retorna false. Não consigo entender porque não funciona.
Segue o código:
def procurando(escolha, codigos, produtos, precos):
    print(codigos)
    verdade = False
    if escolha == 1:
            codigo = int(input("Código do produto: "))
            for i in codigos:
                    print("entrou no for")
                    print(codigo)
                    print(i)
                    if codigo == i:
                            print("entrou no if?")
                            verdade = True
                            print("Produto: {}                        Preço: {}".format(produtos[i], precos[i]))
                            break;

    elif escolha == 2:
            nome = input("Nome do produto: ")
            for i, v in enumerate(produtos):
                    print(produtos[i])
                    if v == nome:
                            print("Foi encontrado 1 resultado.")
                            print("Produto: {}                        Preço: {}".format(produtos[i], precos[i]))
                            verdade = True
                            break;
    print(verdade)
    return verdade

Comment: E como você executou a função? Consegue gerar um [mcve]?
Answer: Seu código está correto, a única coisa que está errada é o for para buscar pelo código.
O correto seria fazer da mesma forma como fez para buscar pelo nome do produto.
Lembrando que como está convertendo a entrada do código para um número codigo = int(input("Código do produto: ")), se os valores da lista de códigos forem strings, ex codigos = ["10", "20", "30"], a comparação sempre será false.
10 == 10 > True
"10" == 10 > False      #tipos diferentes
"10" == "10" > True

def procurando(escolha, codigos, produtos, precos):
    print(codigos)
    verdade = False
    if escolha == 1:
            codigo = int(input("Código do produto: "))
            for i, v in enumerate(codigos):
                    print("entrou no for")
                    print(codigo)
                    print(v)
                    if codigo == v:
                            print("entrou no if?")
                            verdade = True
                            print("Produto: {}                        Preço: {}".format(produtos[i], precos[i]))
                            break;

    elif escolha == 2:
            nome = input("Nome do produto: ")
            for i, v in enumerate(produtos):
                    print(produtos[i])
                    if v == nome:
                            print("Foi encontrado 1 resultado.")
                            print("Produto: {}                        Preço: {}".format(produtos[i], precos[i]))
                            verdade = True
                            break;
    print(verdade)
    return verdade

Comment: eu atualizei o código pra ficar desse jeito ai, porém ele continua não entrando no if.. a lista de códigos vem de um arquivo txt, o \n pode atrapalhar na comparação?
Comment: É possível, depende de como você está fazendo a leitura do arquivo.
Comment: Aaaah, eu converti o valor de "v" para int, ai funcionou


PHP Fatal error: Uncaught Error: Class "PhpOffice\\PhpSpreadsheet\\SpreadSheet" not found

Question: when I use the project locally, the composer spreadsheet library works.
When I upload the project to a Digital Ocean ubuntu machine, I get this error:

[Thu Oct 20 02:05:24.760534 2022] [php:error] [pid 817] [client 126.96.36.199:7921] PHP Fatal error:  Uncaught Error: Class "PhpOffice\PhpSpreadsheet\SpreadSheet" not found in /var/www/Ausen2/logic/ausen_excel.php:16\nStack trace:\n#0 {main}\n  thrown in /var/www/Ausen2/logic/ausen_excel.php on line 16

the source code:
<code><?php

require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\{SpreadSheet, IOFactory};
use PhpOffice\PhpSpreadsheet\Writer\Xlsx; //Csv, Xls

require("../db.php");

session_start();
$sqli = $_SESSION['ausen_list'];

//$nombre_admin   = $_SESSION['NOM_USUARIO'];
//$id_admin = $_SESSION['ID_USUARIO'];

//excel file
$excel =new SpreadSheet();

$excel -> getProperties()->setCreator("Andres")->setTitle("Mi excel"); //metadatos
$excel->setActiveSheetIndex(0);
$hojaActiva = $excel->getActiveSheet();
$hojaActiva->setTitle("Funcionarios");

//header information
$hojaActiva->setCellValue('A1','Cedula_Funcionario');  $hojaActiva->getColumnDimension('A')->setWidth(15);
$hojaActiva->setCellValue('B1','Fecha_Inicio');  $hojaActiva->getColumnDimension('B')->setWidth(15);
$hojaActiva->setCellValue('C1','Fecha_Fin');   $hojaActiva->getColumnDimension('C')->setWidth(15);
$hojaActiva->setCellValue('D1','Tiempo');
$hojaActiva->setCellValue('E1','Observación'); $hojaActiva->getColumnDimension('E')->setWidth(20);
$hojaActiva->setCellValue('F1','Seguridad_Trabajo');  $hojaActiva->getColumnDimension('F')->setWidth(15);
$hojaActiva->setCellValue('G1','ID_Usuario');     $hojaActiva->getColumnDimension('G')->setWidth(15);
$hojaActiva->setCellValue('H1','Tipo_Ausentismo');  $hojaActiva->getColumnDimension('H')->setWidth(15);

$ausentismos = $conectar->query($sqli);

$fila = 2;
while($ausentismo = $ausentismos->fetch_assoc()){
    $hojaActiva->setCellValue('A'.$fila, $ausentismo['Cedula_F']);
    $hojaActiva->setCellValue('B'.$fila, $ausentismo['Fecha_Inicio']);
    $hojaActiva->setCellValue('C'.$fila, $ausentismo['Fecha_Fin']);
    $hojaActiva->setCellValue('D'.$fila, $ausentismo['Tiempo']);
    $hojaActiva->setCellValue('E'.$fila, $ausentismo['Observacion']);
    $hojaActiva->setCellValue('F'.$fila, $ausentismo['Seguridad_Trabajo']);
    $hojaActiva->setCellValue('G'.$fila, $ausentismo['ID_Usuario']);

    if($ausentismo['Tipo_Ausentismo'] == 1){
            $hojaActiva->setCellValue('H'.$fila, 'INCAPACIDAD');
    }elseif ($ausentismo['Tipo_Ausentismo'] == 2){
            $hojaActiva->setCellValue('H'.$fila, 'COMPENSATORIO');
    }elseif ($ausentismo['Tipo_Ausentismo'] == 3){
            $hojaActiva->setCellValue('H'.$fila, 'PERMISO');
    }elseif ($ausentismo['Tipo_Ausentismo'] == 4){
            $hojaActiva->setCellValue('H'.$fila, 'LICENCIA');
    }

    $fila++;
}

//save excel file

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Reporte.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($excel, 'Xlsx');
$writer->save('php://output');
exit;
?>
</code>
i´ve already installed composer again, so the autoload file charge again. and i´ve used composer dump autoload.
SOLVED:
the problem was the name of the class, in my local environmet i use use PhpOffice\PhpSpreadsheet{SpreadSheet, IOFactory} and it works, but when i installed this library in the server, the class name is Spreadsheet, with the lowercase s
Comment: Did you `composer install` to make sure the live machine has all the composer loaded libraries. In other words did you provision the live server?
Comment: yeah, i did provision the live server
Comment: I guess you are developing on windows then :) No problem with that but you do have to be aware that windows is case insensitive and linus is case sensitive.
Comment: _PS_ If you solve it, then write your own answer, dont put Solved in the question
Comment: yeah, i'm working on windows.
Answer: SOLVED: the problem was the name of the class, in my local environmet i use use PhpOffice\PhpSpreadsheet{SpreadSheet, IOFactory} and it works, but when i installed this library in the server, the class name is Spreadsheet, with the lowercase s


time complexity when while not execute

Question: What is the "best case" time complexity of the following segment of program?
n=0
sum=0
input(x)
while x!=-999 do
  n=n+1
  sum=sum+x
  input(x)
end {while}
mean=sum/n

Does "best case" could be O(1) when user in the first time type "-999"
note: when user type -999 in first time, "mean" will be 0/0, result of function is undefined
Comment: To talk about O(N), you need to define N...
Comment: This isn't Java and it sounds rather like homework?
Answer: The worst case is infinity,which means this program never stops. I would not even call it an algorithm, as some definitions of "algorithm" require a finite set of inputs, while other require that it terminates before a given number of calculation steps.
Which means O() is not applicable here.
Comment: you told: "The worst case is infinity,which means this program never stops". So what about best case if user type in the first time -999?
Answer: Algorithm's complexity is usually defined in relation to some kind of data. It can be the input data, as in your case.
Imagine for a while, that the data is not inputted manually, but provided in an array in the app. What would the complexity be then?
In this case the amount of numbers processed is N, and the loop runs once for each N, so you can assume that the complexity is O(N).
Comment: *IF* complexity term can be used with this problem, then the complexity is O(N) regardless of the data! If N==0 then O(N)=O(0)=0, but it's still O(N). Worst case/best case can be applied if there are some conditions in the algorithm - in this case there are none, there's only the amount of data.

time complexity when while not execute


Comparing silhouette scores between different datasets (having different number of variables)

Question: Full Question
Experiment 1 clustered data using variables X and Y. Experiment 2 clustered data using variables X, Y and Z (i.e. a third variable was added).
Would it be valid to compare silhouette scores between cluster results in experiments 1 and 2 to say that one experiment of the two produced better results than the other - because it showed a higher silhouette score?
TL:DR
Is it valid to compare the silhouette scores of two clustering results, if the two different experiments used slightly different data? Such as different number of variables.
Answer: Be careful!
Consider the case where you compare the data set $(X,Y)$ to one where you added some noise to copies of the attribute, i.e. $(X,Y,X+\epsilon_1,Y+\epsilon_2)$.
Then evaluate the exact same clustering (i.e. computed on $(X,Y)$) on this noisier version. It will perform worse. Add more dimensions like this, and it may eventually become really bad.
Additional variables are expected to reduce silhouette, so comparison is biased towards the smaller data set. The reason is simple: there is more variation to account for.
But if your result actually improves with the additional data, then either the additional attribute helped, or it just is of higher magnitude, and the silhouette of clustering $(Z)$ alone would be even better... (Normalization is extremely important. Try different ways of normalizing/standardizing your data, and different distance functions, and you will get very different results!)
Answer: Short Answer: Yes
Long Answer: Clustering Scores are being used to compare how "well" a data-set is clustered. Usually you use such scores to tune the parameters of your clustering algorithm. For example you can run k-means for different k and based on the evaluation score choose the right one for your dataset. As you asked, you can also use the score the compare different clustering approaches, for example, clustering based on different attributes.
If you could provide some more information on your problem I might have something more specific.
Take a look at the following topic for more clustering evaluation methods and ideas that might help you.
Evaluation measure of clustering
Comment: Thanks Haris. I don't really have specific details about the data because its more of a theoretical problem. If you want an example, here's one:

dataset X: price of a car
dataset Y: country of origin of each car
Comment: hit send too early, my bad. Here's the full comment:

Thanks Haris. I don't really have specific details about the data because its more of a theoretical problem. If you want an example, here's one:

Problem: cluster different types of cars together (luxury, economy, etc.)

dataset X: price of a car
dataset Y: country of origin of each car
dataset Z: number of optional extras on each car

It is intuitive that adding more features should improve separation, but can one use silhouette score to objectively make this claim? Thanks
Answer: Silhouette clustering index has the general formula $\frac{b-a}{\max(b,a)}$, where $a$ is the distance from a point to its cluster (where it is clustered) and $b$ is the distance from the point to another cluster, "second close" to the point. The index computes for each data point and the mean index across all data points is considered the ovrall quality of the cluster partition.
Let us question the dependency of the ratio lying in the formula on the dimensionality of dataset. We'll not be doing cluster analysis nor considering any point groupings. Instead, we'll consider all triples of individual points in a random one-cloud data (i.e. data generated as having no clusters, where "clusters" could occure as a random coincidence).
Generate n points by p variables random uncorrelated data from standard normal or from standard uniform distribution. Compute n by n matrix of eucliclidean distances between the points. Consider every triplet of points and compute $\frac{b-a}{b}$ where $a$ is the smallest of the three distances in the triplet and $b$ is the next smallest of the three. (As we are not doing real clustering, let us fashion an "ideal cluster solution" scenario by assuming that a point is always closer to its cluster than to an alien cluster, and that the distance between the two clusters is futher larger because the "alien" cluster is a one which is actually enough close to our point.) Compute mean of such ratio over all the triplets. Repeat the whole task (simulation/computation) number of times. Observe the overall mean ratio and its variation.
Results for n = 30, 10 simulations in two distributions. The mean and st. deviation of the ratio for dimensionality p = 1 through 6:

The ratio clearly depends on the dimensionality. It stabilizes asymptotically in the perspective of large p. I conclude that one should mind when directly comparing Silhouette clustering index values obtained for datasets with different number of variables p1 <> p2; especially when min(p1,p2) is small one should refrain to compare.