Same shards across different MongoDB collections

Question: I have a collection A containing one type of documents, and a second collection B containing another kind of documents.
There are multiple documents in collection B that have the same value for the field "b" which references field "a" in the collection A.
If we shard the two collections A and B on "a" and "b" respectively, can we be assured that documents in collection A having "a=foobar" will be co-located with documents in collection B having "b=foobar"?
Comment: Yes, I know this is called a relationship, and I could use a RDBMS, and Postgres is great, yada yada yada. Changing DBMS is not the question.
Answer:
If we shard the two collections A and B on "a" and "b" respectively, can we be assured that documents in collection A having "a=  " will be co-located with documents in collection B having "b=foobar"?

Shard key indexes are defined per collection, and (as at MongoDB 4.0) collections are balanced independently. Even if two collections have identical shard keys, there is definitely no guarantee that the chunk ranges or shard assignments will align.
If you plan to use server-side queries to combine data from these collections using $lookup or  $graphLookup, note that additional collections you are looking up from cannot currently be sharded. For this use case you would only shard one of the collections. For sharded lookup support there are some relevant improvements to watch/upvote in the MongoDB issue tracker: SERVER-29159 (sharded $lookup) and SERVER-27533 (sharded $graphLookup).
There are a few possible approaches to co-locating data, but all have caveats:

Denormalize: duplicate the most commonly used fields from A into B. This can speed up data retrieval by avoiding the need for joins, but adds some overhead for updates and data storage.
Embed the related data so you have a single sharded collection. This will not be ideal if your collections have very different growth or access patterns, or a large one-to-many relationship.
Manage the data distribution manually: disable balancing for these collections, manually split (or pre-split) chunks so the chunk ranges are identical, and use zone sharding for shard affinity.

For more information on relationship patterns, the Six Rules of Thumb for MongoDB Schema Design blog series is a helpful read. It doesn't cover sharding but the general data model considerations still apply.
Comment: Thanks for the useful links and for the alternatives.


Setup pop3 mailboxes in on Windows Server 2012 datacenter

Question: a complete beginner question but I cannot find an answer with Google:
Where do I setup email accounts / POP3 mailboxes on Windows Server 2012? I setup smtp service and can send emails from the server but I want to create private email mailboxes for several users? Thanks for any help
Comment: If you are a novice user [this tutorial](http://blog.evomailserver.com/how-to-setup-mail-server-in-windows/) might help. It tells you how to configure an IMAP/POP3 email server on Windows Server from scratch, including DNS settings and Firewll rules.
Answer: There is no built-in mail server in Windows. Use Microsoft Exchange, or some other third party mail server that supports Windows.
Comment: I didn't know that. Could you recommend a good free mail server? I don't need any advanced features. It just has to be a stable one. Sorry, I am not a sys admin, just have to setup a server for a small client and need some guidance
Comment: @lesko products recommendations are off topic here, but luckily for you, [google](http://www.google.com) is in good working order.
Comment: I did google search before asking. Thank you for the first reply as well as letting me know this forum's rules


Show Name Property on a foreignkey relationship

Question: I have a selectList of foreignkey (like a parent). Currently, the ID are binded for the value and item name. I want to change that for my Name property:
Here's my models:
public class Genus
    {
        public int GenusID { get; set; }
        public EnumCategory Category { get; set; }
        public string Name { get; set; }

        public List<Species> Species { get; set; }
    }
public class Species
    {
        public int SpeciesID { get; set; }

        public int GenusID { get; set; }
        public virtual Genus Genus { get; set; }

        public string Name { get; set; }
    }

On my Create and Edit Species page I have this code:
<select asp-for="Species.GenusID" class ="form-control" asp-items="ViewBag.GenusID"></select>

This code are generated by default when We Add Razor Page Scaffold. Well, the result are on the line 1, and what I want of result on the line 2:
<option selected="selected" value="1">1</option>
<option selected="selected" value="1">NameProperty</option>

Do you have an idea to make that right ?
Thanks per advance
Answer: Looking at the code for the NavigationMetadata class in the scaffolding repo (https://github.com/aspnet/Scaffolding) I have found the following commented code which describe the behaviour.
// The default for the display property is the primary key of the navigation.
DisplayPropertyName = PrimaryKeyNames[0];

// If there is a non nullable string property in the navigation's target type, we use that instead.
var displayPropertyCandidate = navigation
    .GetTargetType()
    .GetProperties()
    .FirstOrDefault(p => !p.IsNullable && p.ClrType == typeof(string));

if (displayPropertyCandidate != null)
{
    DisplayPropertyName = displayPropertyCandidate.Name;
}

So if you want the Name property to show by default instead of the ID, then ensure it is the first string property in the model (yours already is), and then make sure it's not nullable.
protected override void OnModelCreating(ModelBuilder builder)
{
    // ...
    builder.Entity<Genus>().Property(l => l.Name).IsRequired();
    // ...
}


Range queries using B trees and B+-trees

Question: I am writing a program to retrieve the number of objects within a given range and I am using the B-tree data structure to implement my solution as the number of objects cannot fit in RAM. I came across several articles saying that B+ trees are far superior than B trees for range queries and are used by all major database implementations. I was unable to understand why B+ trees are superior than B trees as all the data are stored on the leaf and it will take h (height of tree) disk accesses to retrieve the node and perform the range query while in the B tree the interval may be located on parent nodes and the disk accesses would be thus minimized. Furthermore, if I have a query such as return # of objects of a particular key then I may be able to locate the key before descending all the way down to the leaves as in B+ trees. Why then do they say that B+-trees are efficient than B-trees for range queries? If I have to write a program to perform range queries shouldn't B trees be the right data structure? Thanks in advance for your replies!
Answer: Practical B tree and B+ tree implementations tend to have nodes of a fixed byte size that is chosen to match the page size of the architecture or another fixture like the cluster size on disk. A typical value would be 4096 bytes.
A B+ tree can fit lots more keys into an internal node because there is no space needed for the record data. That gives higher fanout (lower tree height) and better cache utilisation, since a given set of index pages (internal nodes) 'covers' more queries than would be the case for a B tree.
A second advantage of B+ trees is that the keys in internal nodes are only needed for routing searches to the right leaf. They only need to separate the things on their left from the things on their right but they do not have to correspond to any actual record keys. This means that they can often be shortened, and it also means that deletions do not have to be propagated from the leaf layer into the index layer (i.e., once you have a deleted a key from a leaf, you're done - no need to delete anything from internal nodes except for what happens naturally during rebalancings).
Also, in a typical B+ tree the leaf nodes have pointers to their left and right siblings. This means that you can iterate over a range of records by walking a linked list of pages, instead of having to use the tricky iteration logic typical for B trees.

in the B tree the interval may be located on parent nodes and the disk accesses would be thus minimized

To lay that theory to rest, estimate how many keys total are located in internal nodes of a B tree and how many keys total are located in leaf nodes. That ratio tells you how often a search can stop early, before descending all the way to the leaf level. Note: the early-out scenario is only applicable to queries where the exact key happens to be present in the tree; otherwise a descent to the leaf level is inevitable.


Tell taxonomy links to use route in custom module

Question: I have a module where I created a route /page/tag/{term} that uses a controller for modifications to how the term page is handled.
The problem is that when any page displays these term links, they don't use the custom route, but the default /taxonomy/term/{id}.
How can I tell the taxonomy term links to use my custom route?
Adding the path as the term alias skips over the custom route entirely.
OR, how would I get rid of the custom route and create a pathauto pattern using the same path, but tell those pages to use my custom controller?
I have tried both methods without success...

Here is what I've tried with modifying the existing route:
modulename.services.yml
services:
  modulename.route_subscriber:
    class: Drupal\modulename\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber, priority: 100 }

modulename/src/Routing/RouteSubscriber.php
namespace Drupal\modulename\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
    * {@inheritdoc}
    */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            // i've tried both of these
            $route->addDefaults(['_controller' => '\Drupal\modulename\Controller\ListController::list_by_tag' ']);
            $route->addDefaults(['_title' => 'test']);
        }
    }

}

Edit: after seeing this, I thought about keeping my custom route and using the alterRoutes to change the links...
$route->setPath('/page/tag');
That worked, but it adds on ?taxonomy_term=123
How can I get the term name into the url? /page/tag/term

Update:
Still can't figure out how to get the term name from the route (without loading the taxonomy entity - I'd imagine that is too much load)
Also, I will need to make sure I'm in a specific vocabulary before changing the route.
Any ideas?
Comment: you do not get rid of the original route, get rid of your route and alter the existing route instead. routes are hardcoded like links were in <=d7 so altering them makes no sense.
Comment: How would I go about doing this and having the existing route use my custom controller?
Comment: Create event subscriber service from \Symfony\Component\EventDispatcher\EventSubscriberInterface and listen to \Drupal\Core\Routing\RoutingEvents::ALTER event.
Comment: ´RouteSubscriberBase` already contains this even listener. See https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
Answer: In my case, I'm also using a RouteSubscriber to change the default controller responsible for handling taxonomy term entities. I also wanted to use a custom template only for a specific taxonomy (called my_taxonomy in the example below).
Here is the code for the RouteSubscriber:
<?php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RoutingEvents;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.taxonomy_term.canonical')) {
            $route->setDefaults([
                '_controller' => '\Drupal\my_module\Controller\DefaultController::listAll',
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -200];
        return $events;
    }

}

And here is the code for the controller. Note that a custom render array can be returned only for terms of the specific taxonomy my_taxonomy. All other terms fall back to the default controller used by the views module in the original route:
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\Routing\ViewPageController;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends ControllerBase {

    public function listAll(Request $request) {
        $render = [];

        $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
        $term = Term::load($tid);
        $bundle = $term->bundle();
        if ($bundle == 'my_taxonomy') {
            // render array for your custom template
        } else {
            // falls back to the default ViewPageController to handle all other taxonomies
            $viewPageController = new ViewPageController();
            $render = $viewPageController->handle('taxonomy_term', 'page_1', \Drupal::routeMatch());
        }

        // Return render array
        return $render;
    }

}

Comment: This is almost functional. In order for term-pages from other vocabularies to work RouteSubscriber needs one small addition:

`$route->setDefaults([
  '_controller' => '\Drupal\my_module\Controller\DefaultController::listAll',
  'view_id' => 'taxonomy_term'
]);`

The view_id default needs to be added so other vocabularies can load the proper view.


Prove optimality for hats riddle

Question: Riddle: There are White and Black hats. There are 3 people, who randomly get assigned white and black hats. Each person can't see his/her own hat color, but can see the others. At least one of the 3 people needs to guess their hat color right, and no one can get it wrong (they can choose to stay silent if they want). What strategy can they use to have max probability of winning?
Optimal solution: Whoever sees 2 of the same color hats on the other 2 people, will say the opposite of that color for their own hat color. This ensures 3/4 probability of winning. Here is the state space:
WWW BBB WBB BWB WBW BBW WWB BWW  (the bolded person will speak out)
How can I rigorously prove that this is the optimal solution, and that getting 7/8 or 8/8 is not possible?
Answer: In any strategy, any given person's probability of guessing correctly equals their probability of guessing incorrectly.  Summing over people, it follows that the expected number of correct guesses equals the expected number of incorrect guesses.  Since at most three people can guess incorrectly in any given state, and you need at least one person to guess correctly in order to win, it follows that
$$ P(\text{win}) \leq E[\#(\text{correct guesses})] = E[\#(\text{incorrect guesses})] \leq 3 \cdot P(\text{loss}), $$
which implies
$$
1 = P(\text{win}) + P(\text{loss}) \leq 4 \cdot P(\text{loss}),
$$
so $P(\text{loss}) \geq 1/4$ and thus $P(\text{win}) \leq 3/4$.  This generalizes readily to the $n$-player version for any $n$.
Comment: Where does the 3/4 come from? Is it 3 * P(loss), where P(loss) = 1/4? Why does it equal 1/4?
Comment: @JamesFlanagin I have edited my answer to clarify the last step.
Answer: To win in $7$ or $8$ of the $8$ scenario's (at least) one of the people (person $X$) must guess white, if they see two white hats, or one of the people must guess black if they see two black hats.  Without loss of generality assume the former.
Then if person $X$ has a black hat and the other two have white hats, they will lose, which means that they must win in every other scenario.
But then there must also be a person, person $Y$ ($Y$ may or may not equal $X$) who guesses black, if they see two black hats.  If $Y$ has a white hat and the other two have black hats, then they will lose.
Thus there will always be at least two distinct scenarios where they lose.
Comment: @JamesFlanagin The above shows that given any strategy, there exist at least two states where they do not win, so probability of success is always less than or equal to $6/8$.
Comment: Hmm, I'm looking for a more state space-sort of proof, where we can prove that there exists no other strategy such that this would work. Thank you though!

Prove optimality for hats riddle


XLRf - 1/4"m adapter with or without transformer

Question: Greetings forumers from newbie!
Advice pls for selection of an adapter to plug a dynamic mic (ending in XLRm) into an active speaker ("karaoke) box with a "1/4f" input". Since the speaker box comes with a cheap mic with a cord ending in 1/4"m, should one presume that the box's single 1/4"f input is mic level? If so, should one presume that a XLRf - 1/4"m adapter without an inline transformer should work best since there seems to be no need to change a mic level signal throughout. FMI do I understand correctly that an XLRf - 1/4"m adapter with inline transformer is intended for cases where a mic signal needs to be stepped up for a line level input? For fuller context the application is for maximum portability of a saxophone busking using backing tracks from phone. Many thanks in advance.
https://en-us.sennheiser.com/instrument-microphone-saxophones-trumpets-drums-wind-instruments-congas-percussion-e-608 https://www.tronios.com/sps75-karaoke-machine-with-lightshow/
Answer: Try the simple adapter.  When I started gigging, PA amps had Lo-Z and Hi-Z mic jacks.  But inputs on today's gear are very forgiving, a high input impedance with plenty of gain is typical and accepts most sources. The only Hi-Z input you're likely to see will be for a VERY high impedance source like a guitar pickup.   For the price of a simple adapter...
Love the 'light show'!
Answer: More often than not, a mic equipped with a 1/4" jack is hiZ, and one equipped with an XLR is lowZ, the extra pin on the XLR used to produce a 'balanced line'.
Usually, when plugging a mic into an input, the resulting volume is more into the lowZ input. Often, either will work with either, but there can be volume and sometimes tonal issues.
Matching transformers are available either way, so your best bet is to take your stuff along to a sound/music shop, and they will supply you with the adapter which works best - or even another lead.


Concept of "auto" keyword in C

Question: What is the exact concept of the keyword auto in a C program?
When I went through the book Deep C secrets, I saw this quote:

The auto keyword is apparently
useless. It is only meaningful to a
compiler-writer  making an entry in a
symbol table. It says this storage is
automatically allocated on entering
the block (as opposed to global static
allocation, or dynamic allocation on
the heap). Auto is irrelevant to
other programmers, since you get it by
default.
Comment: That's why it's a comment Cody, not an answer.
Comment: @ssg: C++ is not the same language as C. That has nothing to do with the question.
Comment: In C++0x auto has a completely different meaning though. http://en.wikipedia.org/wiki/C%2B%2B0x#Type_inference
Comment: Possible duplicate of [Where is the C auto keyword used?](http://stackoverflow.com/questions/2192547/where-is-the-c-auto-keyword-used)
Answer: auto isn't a datatype. It's a storage class specifier, like static. It's basically the opposite of static when used on local variables and indicates that the variable's lifetime is equal to its scope. When it goes out of scope it is "auto"-matically destroyed.
Note that auto in C is currently (ie: in C17 and earlier) not like auto in modern C++ -- it does not perform any type inference. However, it is possible that C23 will change auto to do a weaker form of type inference. The auto keyword is pretty useless today: you never need to specify it as the only places you're even allowed to are exactly the places where automatic storage is already the default behavior.
Comment: @jcsalomon The C90 spec, in §126.96.36.199, says this about automatic storage duration: "storage is guaranteed to be reserved for a new instance of such an object on each normal entry into the block with which it is associated ... Storage for the object is no longer guaranteed to be reserved when execution of the block ends in any way." I don't have a copy of the C99 spec, but it seems unlikely that they would have change this.
Comment: Apparently the "auto" keyword is a holdover from the B language.  In B, everything was a machine word, no other types.  Variables were simply declared static, extern, or auto.  auto then became the default for C.

https://www.princeton.edu/~hos/mike/transcripts/thompson.htm
Comment: Are you sure "the variable's lifetime is equal to its scope"?  I'd thought the lifetime was equal to the function call.  *E.g.*, is `int foo() {int *p; {int i = 42; p = &i} return *p;}` non-conforming?
Answer: It might be useful in C89 where you have an implicit int rule.
void f() {
  a = 0; // syntax error
  auto b = 0; // valid: parsed as declaration of b as an int
}

But then, you can just write straight int instead of auto. C99 doesn't have an implicit int rule anymore. So I don't think auto has any real purpose anymore. It's "just the default" storage specifier.
Comment: I don't understand how this would be useful, even in C89. It doesn't add anything. Whereever `auto` can be used, it is also the default, implied `int` type or not.
Answer: You get the auto behaviour by default whenever you declare a variable for example - int i = 0; However you do the same by explicitly specifying auto int i = 0 which is not needed.
Answer: As said auto is the default for variables in block scope in C. The only usage that I have had for the keyword is in macros. For a macro that does a variable declaration you might sometimes want to ensure that the variable is not declared static or in file scope. Here the auto keyword comes handy.
This was particularly useful for C++ where you could abuse the constructor/destructor mechanism to do scope bound resource management. Since the auto keyword is currently changing its meaning to something completely different in C++, this use is not possible any more.
Comment: Re: "auto is the default for variables in function scope in C": C11: "A _label name_ is the only kind of identifier that has _function scope_."
Comment: @pmor, thanks for finding this bug in a 12 year old answer ;-) Now corrected to the correct terminology, namely block scope.
Answer: I find that quote quite questionable. The logical level of a compiler has nothing to do with the logical level of the compiled language, even when the two languages are the same. May be I'm poor on fantasy but I really can't imagine how having or not a certain keyword can be useful for a compiler but not for a general program, especially in "C" where you cannot directly manipulate keywords or any form of code anyway and you've to reflect everything on data because, in "C", code and data are two completely distinct concepts.
My wild guess is that auto was there originally because it wasn't optional but mandatory, later when the language evolved and it wasn't necessary any more it still remained because of backward compatibility reasons with existing C code.
Answer: I am sure you are familiar with storage class specifiers in C which are "extern", "static", "register" and "auto". I am not sure, but I think it is compiler dependent. You see, with respect to storage class specifiers, there is a rule. We cannot use multiple storage class specifiers for a variable. That is why static global variables cannot be externed. Therefore, they are known only to their file. When you go to your compiler setting, you can enable optimization flag for speed. one of the ways that compiler optimizes is, it looks for variables without storage class specifiers and then makes an assessment based on availability of cache memory and some other factors to see whether it should treat that variable using register specifier or not. Now, what if we want to optimize our code for speed while knowing that a specific variable in our program is not very important and we dont want compiler to even consider it as register. I though by putting auto, compiler will be unable to add register specifier to a variable since typing "register auto int a;" OR "auto register int a;" raises the error of using multiple storage class specifiers. To sum it up, I thought auto can prohibit compiler from treating a variable as register through optimization.
This theory did not work for GCC compiler however I have not tried other compilers.
Another possible answer is that C was developed in 1970 but it did not have any standards until 1989 when C89 came out. The non-standard C, may have used auto often but when C89 came out as the standard C, perhaps they needed to maintain compatibility with the non-standard C.

Concept of "auto" keyword in C


How can I explain/understand a flattened 2nd in a minor melody

Question: My 10yo daughter (~grade 4 piano level) likes composing her own tunes, and then we'll discuss them and expand on them.  Recently she composed a melody that appears to be in c# minor, except that every so often she uses d-natural instead of d#.  I have played around an I have to admit it sounds "right" where she has used it, so I don't think it can be unusual.  What sort of musical theory explanation is there for this note sounding correct?  Should we think of this as momentarily modulating to F# minor for a phrase and then back again - and is there any justification for why that sounds "good"?
Edit: Here's an example
In this case the same phrase is dropping down one place in the scale of c#-minor, which means the first note drops a tone each time (c#, b, a), and the quaver on beat 3 seems to mirror this (f#, e, d)?  But doing so takes it out of scale - and plenty of other notes do not drop down a tone (so the melody is exactly transposed on each repetition), e.g the last note (a, g#, f#)
Comment: ...compositions that are outside its conventions. This can be its own strength, as "outsider music" can be fresh and interesting. Note, also: It's a common misconception that a given piece can only use the notes of a given key, or that any non-key notes indicate modulation. These could simply be accidentals, chromatic alterations. It being the season: If I sing "It's Beginning to Look a Lot Like Christmas" in C major, I'll also sing an F#, A#, G#, and Ab, and that's just in the chorus, which certainly doesn't modulate (even if the verse maybe visits Am and G).
Comment: Welcome! You're essentially asking for a theoretical analysis of the piece; it would be helpful if you posted it (if she and you are comfortable with that). You might also want to check out [the topics covered here](https://music.stackexchange.com/help/on-topic) and [how to avoid subjective answers](https://music.stackexchange.com/help/dont-ask). In fairness, you're actually asking to get *beyond* "it sounds good" and reach an objective analysis. It might just come down, though, to the fact that new composers and musicians, who don't yet know the ins and outs of music theory, often create...
Comment: That excerpt looks more like it's in F#-minor
Comment: @PiedPiper ok... and then the d#/d-natural are to do with melodic minor stuff?  How do you deduce f# - just because of the d-natural or anything else?  (It starts and ends on c# and f# doesn't seem to have any special significance in the melody)
Comment: @Corvus That last measure really seems to want to resolve to F#
Comment: She might well have just picked it up from Beethoven.  Same key as Moonlight Sonata, which also has a N6
Comment: @nuggethead She has recently listened to moonlight sonata so who knows what kids pick up on!
Comment: To OP: do you feel that you now gained some kind of an understanding on this? Do you now have an idea as to why it sounds good, and what kinds of mechanisms the chromatic alteration triggers? Or was the main thing just to hear that "it's normal and commonly done". I'm interested in this, because very often people ask to "understand" something, and even if they accept an answer, it remains largely a mystery to me, what kind of understanding was gained, and what was the actual obstacle that this answer removed. Was it about knowledge or skill, or maybe something psychological or social.
Comment: @piiperiReinstateMonica to some extent this is probably about a child beginning to exceed a parent's knowledge and the insecurity that brings! :-)   Being serious though yes the answers have been very helpful, at this early stage she is just learning about the "rules" for music, and obviously all rules can be broken, but it seemed like a good teaching moment to learn more rules and deeper insights - rather than just shrug and say that sounds good.  Whether or not this actually is a Neapolitan is less relevant than it being a jumping off point for discussion.
Comment: @Corvus Everyone has their own path to learning music. Myself, I learned by playing songs by ear: bass, chords, melody. I built my own abstrations and concepts and didn't need anyone to teach. In hindsight, I didn't miss anything, because all this talk about Neapolitan or Kentucky Fried Chords seems like making trivial things look unnecessarily complicated. It's just a chromatic alteration, it is done all the time. I suggest spending 90% of time playing and exploring, particularly by ear. Different styles of music. You learn by examples. If someone says "this is difficult", don't believe it.
Answer: Those flattened 2nd scale degrees could point to tonicization of or temporary modulation to the subdominant (e.g. if ^1-^♭2-^1-^4 is harmonized as i-VI/iv-V/iv-iv).
But those flattened 2nd scale degrees could also be signs of - and harmonized as - the ♭II a.k.a. Neapolitan chord!
In classical music, the ♭II chord is treated as a subdominant-function chord, and it is indeed sometimes substituted for iv (so, for example, ^1-^4-^5-^1 can be harmonized as i-♭II6-V-i). Occasionally, minor-key music even modulates to the Neapolitan chord's key (e.g. near the end of Franz Schubert's Moment Musical in F Minor, D. 780 (Op. 94), No. 5, there is a striking modulation from F minor to G flat major (the key of ♭II of F minor) and back):

While already occasionally to more than occasionally appearing in classical music if you know where to look (e.g. Ludwig van Beethoven's "Moonlight", "Appassionata", and "Tempest" piano sonatas), the ♭II chord may as well be a first-class citizen in heavy metal and (shockingly often therefore) edgy enough video game music. In those types of music, dominant chords are often omitted entirely, so you often hear chord progressions like i-♭II-i and i-♭II-VII-i.
Comment: @Aaron - I'd treat that use of bII in the example in the question as the Neapolitan chord. In fact, "The Azure Arbitrator", the final boss theme of *The Legend of Heroes: Trails to Azure*, uses almost the exact same chord progression (that theme's version is more like i - iv - V7/III - III - VI - bII - isus2 - V, and it's also in C Sharp minor to boot).
Comment: I definitely see a Neapolitan progression in the excerpt given. You easily can have N6 V i with that ending.
Comment: Hope you'll update your answer now that the excerpt is present. You've  more-or-less identified the chord progression even without it. The post just needs an update to specify the actual progression used: i - iv - VII - III - VI - bII - v - i (modified circle of fifths).
Comment: I'm not saying your answer is wrong. It's correct — the chord is the Neapolitan. I'm just saying there's a larger context you can now add to your correct answer.
Comment: Just looked at moonlight sonata again, and it's right there, the same A->D change that she's used, and creating the same sort of feeling/momentum.  This is clearly exactly what she's stumbled across, so I've marked this as the correct answer.
Answer: EDIT: My original answer starts in the second paragraph. This was based on not having a musical example. Based on the musical example that was added after I posted my answer I would say the use of D natural is not Phrygian but rather part of a circle of 5ths sequence that ends on the implication of a Neopolitan bII chord. The melody seems to imply C#m, F#m, B, E, A, D, G#m, C#m. She came up with a very interesting line.
Without hearing or seeing the music for the piece your daughter wrote I would just say: Welcome to the Phrygian mode!
The Phrygian mode is identical to the natural minor scale except for the 2nd degree, which is M2 in minor but m2 in Phrygian. This gives the Phrygian mode a darker and some might say a slightly Spanish or Middle Eastern flavor.
It's possible she doesn't use it exclusively in the piece. That's ok, the great thing about composing is that there are no rules that say a piece must only contain certain notes, unless you are writing something as part of some kind of assignment with rules to follow.
In case you're not familiar with where it comes from, it is one of the 7 modes built from the 7 degrees of the major scale. Information on modes is universally available so I won't go into a detailed explanation but here is a link to get you started : https://en.wikipedia.org/wiki/Mode_(music)
The Phrygian mode is built on the 3rd degree of the major scale so in essence if she is in C# minor that is the 3rd degree of A. The key of A is the relative major of F# minor which is the key you mentioned in your question so you weren't far off with what you heard. However in this case if the piece sounds like the tonal center is C# then it is better to think of it as either C# minor with some borrowing from the Phrygian mode or if there are no D#'s or a lot of other chromaticism you can think of it as being in C# Phrygian.
Comment: @ToddWilcox Of course there are but I answered based on the original  unedited question which contained no musical example.
Comment: There are uses for the lowered second degree outside of Phrygian.
Answer: ♭2 is a common chromatic alteration in minor keys. It might imply the 'Neapolitan' ♭II chord. It might be just a melodic decoration.  If it's used consistently in place of the major 2nd, we might be in Phrygian mode!
Answer: Scale degrees are regularly altered (modified), and it sounds like what it sounds like. Now you've heard what this particular modification sounds like, and you'll be able to use that sound in the future, when you want that sound.
An essential element in sheet music notation is accidentals which are used to show alterations to scale degrees. By notational convention, the alterations are temporary and are automatically cancelled at the next barline. This convention is because that's how pieces are usually built. Alterations are temporary, and when they are returned back to normal, that's a kind of a tension/release element.
I wrote a chord accompaniment harmonization for this melody.

To add further scale degree alterations, I made a change in the last bar, making a proper dominant-seventh (G#7 instead of G#m) accompaniment chord fit better with the melody.

Try making further modifications and listen to the new sounds. How about this one, do you like the sound?

Many of the scales and/or chords obtained via alterations have specific names, but I'm not sure if learning a lot of fancy names does more harm than good. The names don't matter, only the sound matters and that you know how the sound was made.
What "understanding" means for different people varies. For me, it is enough if I can relate the change to something I consider familiar or conventional. Another thing that helps to gain a feeling of understanding is if I have encountered example pieces where this particular thing is used. What comes to the flattened 2nd in minor, unfortunately I can't name any specific tune from the top of my head, but it is very commonly used.
You can also do the same trick in the backing chords, without the alteration being reflected by the melody at all. How about this:

Now there are many more chromatic alterations of scale degrees. During the D7 chord, even the tonal center C# is altered! I don't claim to particularly like this chord progression, it feels slightly weird at places, but you can do that and it sounds like what it sounds like.
Answer: All the Neapolitan comments seem off the mark, because it isn't really functioning like a subdominant N6 that would normally move to a dominant chord of some kind. In other words, it isn't followed by a G#7, so it isn't a convincing subdominant to dominant in a minor key movement.
But, there is a very obvious melodic sequence happening, and the pattern of that sequence is a decoration of a third, an implied root position triad, that leaps up a perfect fourth. Not just any old fourth, but specifically a perfect fourth.
Two important points should now be mentioned:

melodic/harmonic sequences are frequently used to modulate to new keys
the perfect fourth above a tonic is an important tonal degree and chromatic alterations that form that tone are important in modulation

The second point I think is less in effect for this passage, but at the very least when we get to the third measure, the D4♮ really stands out as a perfect fourth above the outlined A C#, and it has a strong A major feel. The D4♮ rather than sounding like solfege RE lowered in C# minor, sounds like FA in A major, even if that event is just a temporary shift. The sequence continues, so at this point we wouldn't want to settle on A major as a new tonality.
The first point is probably the more important one. When you see sequential passages with accidentals, it should signal you to look for a modulation or temporary shift of tonality. When such changes aren't modulations, then it's most likely about altered chords, and altered chord usually stand out for their particular "sounds" and they often have conventional resolutions. If we want to consider the possibility of an altered chord - such as the Neapolitan N6 chord - we really want to see conventional handling to make the case.
One way or the other, harmonic analysis is usually clearest when it reveals the most conventional harmonic identities.
Let's continue with the premise it is modulating and see if it fits a common convention.
The passage stops on C#4.
The natural on D4 has the temporary effect of a key signature of three sharps, which would be F# minor.
C#4 is the dominant of F# minor.
The decorated third of G#3 B3 in the fourth measure outlines a iio chord in F# minor.
iio V makes a nice half cadence in F# minor. From a common practice tonal perspective that conventional harmonic progression makes much more sense than a supposed N6 chord moving to an implied minor dominant to tonic move, which would not be conventional common practice harmony.

EDIT
The D4♮ sounds like a Neapolitan, lowered ^2 is being introduced, but the fourth bar doesn't continue along those lines and play a proper dominant, like this...

To leave the line as written, I tried a modulation to F#m that made functional sense...

I'm not really satisfied with that ending in F# minor, but that does leave the line unaltered.
If I wanted to go the way of a Neapolitan chord, and wanted it to sound like common practice, I would change the last bar accordingly.
The basic cadential formula for a Neapolitan chord is...

...the tonic enclosed by the lowered ^2 degree and the raised ^7 degree in a minor key.
The Schubert example in the accepted answer is an example of modulating to the key of the lowered ^2, but it doesn't demonstrate the cadential use of N6. It's interesting, but doesn't provide the same kind of continuation/ending that is presented in the original question.
Comment: If I understand what you are saying correctly, your suggestion is that this is most usefully interpreted as a temporary modulation to F# minor, and then the D-G#-C# finish is VI-II-V?
Comment: Yes, but probably the more important point is about what happens in the fourth bar. I edited my answer to put into notation what I mean.
Answer: I see that an answer has already been accepted, but I think this is worth pointing out.  I don't know why I didn't see/hear it the first time.  The composer has written a brief sequence.  Since beat 3 is metrically strong, I wonder if at some level she felt D# was a "wrong note" and corrected it down to D natural.  All the other iterations of the sequence outline a perfect fourth between beats 1 and 3.  D# would form an augmented fourth, and interval that takes some getting used to - and one that often sounds "wrong."
I wouldn't hesitate to explain the N6 to her, as it could be a perfectly valid way to harmonize this melody!  But I think the effort to maintain a consistent motive in a sequence explains where it came from.


How to define a nullable and unique column inside CREATE TABLE in SQL Server?

Question: I had a table defined as follows:
CREATE TABLE MY_TABLE (
  -- ...
  MY_COLUMN VARCHAR(100) UNIQUE NOT NULL
)

This definition, however, caused problems when having MY_COLUMN as NULL in multiple rows, so I changed it to:
CREATE TABLE MY_TABLE (
  -- ...
  MY_COLUMN VARCHAR(100)
)

CREATE UNIQUE INDEX uq_my_column_not_null
ON dbo.MY_TABLE(MY_COLUMN)
WHERE MY_COLUMN IS NOT NULL;

This solved that problem, but I needed to create a constraint outside the CREATE TABLE expression, since it didn't allow me to put the WHERE inside it.
Is there a way to get this functionality without writing code outside the CREATE TABLE expression? Something like:
CREATE TABLE MY_TABLE (
  -- ...
  MY_COLUMN VARCHAR(100) UNIQUE ALLOW NULLS
)

Answer: Yes, you can create an index (including filtered UNIQUE indexes) within the CREATE table statement, but you can't define it along side the column, you have to define the INDEX specifically:
CREATE TABLE dbo.MyTable (MyColumn varchar(100) NULL,
                          INDEX UQ_MyColumn UNIQUE (MyColumn) WHERE MyColumn IS NOT NULL);

db<>fiddle
Comment: [Pull request](https://github.com/MicrosoftDocs/sql-docs/pull/7628) sent, @MartinSmith .
Comment: Interesting, I did check the `CREATE TABLE` grammar. But `` doesn't mention a `WHERE` clause. Must be out of date! https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver16
Comment: I can only assume that it's implicit included in the `| [  ] }` section, @MartinSmith . But I agree, it's not in the ` ::=` section. I might send a revision if I get the chance.


solution to  equation $a \cdot \cos(\theta) - b \cdot \sin(\theta) = c$

Question: Does the equation
$$ a \cdot \cos(\theta) - b \cdot \sin(\theta) = c$$
have a closed-form solution for $\theta$?  What about the case where $a^2 + b^2 = 1$?
Answer: Yes, if this is acceptable as closed-form for you.
Using the formula, you can solve for $\theta$ and have an answer in terms of nothing more complicated than arcsine and square roots.
$$\theta=\arcsin(c/\sqrt{a^2+b^2})-\phi$$
I'll leave the determination of $\phi$ up to you as an exercise.
Answer: Given your use of signs I'll take it that $a,b \ge 0$. In which case, if $R = \sqrt{a^2+b^2}$ and $\alpha = \tan^{-1} \dfrac{b}{a}$ then
$$a \cos \theta - b\sin \theta = R\cos(\theta + \alpha)$$
and so if $\left| c \right| \le R$, we can solve the equation to get
$$\theta = \cos^{-1} \dfrac{c}{R} - \alpha = \boxed{\cos^{-1} \dfrac{c}{\sqrt{a^2+b^2}} - \tan^{-1} \dfrac{b}{a}}$$
Of course, this is just one solution; we can obtain the others by considering symmetries.
Answer: Using the identity $ sin(x)^2 + cos(x)^2=1 $, we have,
$$a \cdot\, \cos(\theta) - b \cdot \sin(\theta) = c \Rightarrow  a\sqrt{1-\sin^2(\theta)}= b \cdot \sin(\theta) + c $$
$$ \Rightarrow  a^2\,(1-\sin^2(\theta)) = ( b\sin(\theta) +c)^2 $$
$$ (a^2 + b^2)\sin(\theta)^2 + 2bc \sin(\theta) + (c^2-a^2)=0\,. $$
The above equation is quadratic in $\sin(\theta)$. Solving the equation in $\sin(\theta)$ yields,
$$ \sin(\theta) = \frac{ -2bc \pm \sqrt{4b^2c^2-4(a^2+b^2)(c^2-a^2)}}{2(a^2+b^2)}  $$
I believe you know how to find theta from here. Do not forget that $-1\leq \sin(\theta) \leq 1$.


What is the role of a "false 9"?

Question: Recently I read a few articles about strikers playing as a "false 9". My understanding of a "false 9", is that he is a striker whose purpose is to pull defenders out of position so that his teammates will have a better chance of scoring. Is my understanding correct or is there more to this?
Also, where did this term come from?
And who are the best players who made this role popular?
Answer: Let's start from the end. The best player who plays "false 9" today is, without any doubt, Lionel Messi.
There isn't one definition of a "false 9", but I will try to explain it from my understanding.
"False 9" is generally a player who isn't a pure striker as defined in the past. This player will drop deep into the field to be a part of or start the attack. When doing that, opponents / defenders will follow him and leave more space to players from the 2nd line to threaten the goal.
The "false 9" usually has great finishing, a very high level of vision on the pitch, and good dribbling and passing.
Zonal Marking defines it as:

A unconventional lone striker, who drops deep into midfield. Francesco
  Totti perhaps invented it for Roma in 2006/7, Lionel Messi played here
  when he swapped positions with Samuel Eto'o for Barcelona in 2008/09,
  and Robin van Persie played the role for Arsenal at the start of the
  2009/10 season.

Teams who play with a "false 9" generally play in 4-6-0 formation with the "false 9" turning into a striker when needed. I answered a similar question about this formation here: Has 4-6-0 ever worked in high level football?
Another great explanation of the "false 9" according to Barcelona and Josep Guardiola's dream about a team with a goalkeeper and 10 midfielders can be found at the following post.
Answer: When I first heard of it, it was concerning Lionel Messi. He appeared to only be playing as a false 9 at his club, Barcelona.
Observing Messi play, I realised Messi plays more of an attacking midfielder, but he'd smartly convert to a striker when needed so.
Based on my observations, a false 9 is a striker who's influential enough to keep defenders going after him, leaving room for his wingers to take his position in front of goals.
Answer: According to my understanding of a "false 9", a team who starts their game with 4:3:2:1 could play with this strategy provided when they will turn with 4:3:3. An attacking midfielder will make a constant disturbance into opposition's backline (the last 6 to 10 yards of opponent's half).

What is the role of a "false 9"?


Upper Bound for Vertices of Intersection of Subspace and Simplex

Question: Let $S$ be a simplex in $\mathbb R^m$. It can be expressed as the convex hull of the columns of some affinely independent $m \times m + 1$ matrix $A$:
$$S=\left\{A\vec\alpha: \vec\alpha\in\mathbb R^{m+1},\alpha_i\ge0,\sum\alpha_i=1\right\}$$
Or alternately by the intersection of a set of $m + 1$ half-spaces defined by the rows of a matrix $C$, where each row $\vec c$ gives $\vec c^T \vec x \le 1$. (This requires that the origin be in the interior of the simplex, but that can be done without loss of generality).
$$S=\left\{\vec x\in\mathbb R^{m}:C\vec x\leqq 1\right\}$$
Let $Q$ be a subspace of dimension $n<m$, expressed  in terms of a linearly independent basis:
$$Q=span\left\{\vec v_1,\vec v_2,...,\vec v_n\right\}=\left\{V\vec y:\vec y\in\mathbb R^n\right\}$$
If the intersection $Q\cap S$ contains a point in the interior of $S$, then it can be expressed as a convex hull in $Q$. From low dimensional cases, it is clear that there are some restrictions on its geometry. In particular, I am interested in the number of vertices. I believe the best lower bound is $n+1$; that is the minimum for any convex hull in $n$ dimensions, and one can be obtained in any dimension by construction. The the upper bound is much less clear.
At $m=3, n=2$ (a plane intersecting a tetrahedron), the lower bound is 3 and the upper bound is 4, since the planar cross sections of a tetrahedron are either triangles or quadrilaterals. However, it's not clear to me how this argument generalizes to higher dimensions.
The best general upper bound I could come up with is $\binom{m+1}{n}$, which follows from this argument:
The set of $\vec y$ coordinates has the same topology as the hull in $\mathbb R^m$, so we can look at the hull in that space, again assuming that the origin is an interior point.
$$Q\cap S = \left\{V\vec y: \vec y \in \mathbb R^n, CV\vec y\leqq 1\right\}$$
$CV$ is an $m+1\times n$ matrix, so this equation describes the intersection of $m+1$ half spaces in $\mathbb R^n$. Some of them could be redundant, but we can assume that none are to obtain an upper bound on vertices. Since this hull exists in $n$ dimensions, each vertex lies at the intersection of the boundaries of at least $n$ half spaces in order to be fully determined. If it is in the intersection of more than $n$ half spaces, we can find a subset of exactly $n$ whose intersection is the vertex. Thus if we consider every combination of $n$ half spaces, we will obtain all the vertices, which gives an upper bound of $\binom{m + 1}{n}$ vertices.
It seems like there ought to exist a better upper bound. This one gives more vertices than can possibly be attained for the low dimensional cases $(m=2, n=1)$, $(m=3, n=1)$, and($m=3, n=2)$.
Any input on how best to improve this bound (or show it can't be inproved) would be much appreciated. A more general result would be preferred, but I'm primarily interested in the case $m>>n>>1$.
Comment: I don't understand, for $m=3$ and $n=2$ we have $\binom{m+1}{n}=\binom{4}{2}=6$.
Comment: You are correct; I miscounted. I've corrected the question.
Answer: A better bound is $\left\lfloor\frac{(m+1)^2}{4}\right\rfloor$. I think it is valid for all $n\le m-1$ and it is definitely attained if $n=m-1$. For $n<m-1$ I don't have a better upper bound, but there should be one.
Assume $n=m-1$. In that case any $n$-plane is an hyperplane, so it is given by an equation $f(x_1,\dots,x_m)=a_1 x_1+\dots+a_m x_m=r$ for some $a_1,\dots,a_m$ and some $r$. Let the vertices of the $m$-simplex be $e_0,\dots,e_m$. Assume there are $k_1$ vertices with $f(e_i)>r$, there are $k_2$ vertices with $f(e_i)=r$ and $k_3$ vertices with $f(e_i)<r$. All the vertices of the intersection of the $m$-simplex $S_m$ with the hyperplane are either vertices of $S_m$ (so we have $k_2$ vertices of that type), or are the intersection of the straight line connecting a vertex $e_i$ with $f(e_i)>r$ with a vertex $e_j$ with $f(e_j)<r$, hence there are $k_1\cdot k_3$ vertices of that type.
So the intersection has $k_1\cdot k_3+ k_2$ vertices, hence an upper bound is given by
$$
\max\{k_1\cdot k_3+k_2,s.t. k_1+k_2+k_3=m+1\}.
$$
This maximum clearly is attained when $k_2=0$ (since $k_1(k_2+k_3)> k_1k_3+k_2$ if $k_1>1$) and
so we have to maximize $k(m+1-k)$ for $k=0,\dots,m+1$. When $m+1$ is even, the maximum is at $k=\frac{m+1}2$ and is equal to $\frac{(m+1)^2}{4}$, and when $m+1$ is odd the maximum is attained at $k=\frac{m}2$ or $k=\frac m2+1$ and is equal to $\frac m2\left(\frac m2+1\right)=\frac{m(m+2)}{4}=\frac{(m+1)^2-1}{4}$.
So in both cases the maximum value is $\left\lfloor\frac{(m+1)^2}{4}\right\rfloor$.
It is also clear that for an hyperplane in general position $f(x)=r$ one can choose the constant $r$ such that $k_1$ vertices are on one side and $k_2$ vertices are on the other side of the hyperplane for any $k_1$ and $k_2$ with $k_1+k_2=m+1$. So there are hyperplanes for which the upper bound is attained.
Each $n$-plane is contained in an $m-1$ plane if $n\le m-1$, but that doesn't automatically implies that the same bound is valid for $n<m-1$. It should be so, but at the moment I have no proof.


Importing node_revisions records from version 5 to version 6

Question: Probably a dumb question, but could I simply export an SQL file from the database of a Drupal 5 site and import it into a Drupal 6 database in the same table provided I used the same CCK fields for both? I've tried to migrate content in so many different ways and pretty much everything has failed so far... importing csv through the feeds module was my greatest hope and was made to look so easy but I keep getting an HTTP error.
Also is node_revisions the table that contains all of the stories? I tried exporting nodes, but it didn't seem to contain the body field.
Answer: Instead of trying some convoluted way of exporting and then re-importing the data and maintaining all meta-data - have you tried simply upgrading the site to Drupal 6?
This has been heavily documented on drupal.org
When you do a major drupal upgrade, so long as there is a drupal 6 module for your functionality, there will be update hooks that alter the database to convert it to the new schema.
This includes CCK, revisions etc
Comment: Yes I have tried... failed miserably :( the drupal 5 site I am dealing with is very poorly coded, and that may have to do with the many hurdles I'm running into... I will try again if all else fails.
Comment: The trick is to read the whole upgrade guide, make sure ALL contrib is disabled before updating core, and make sure you are running the latest version of 5.x first.
Comment: OK I guess I have no other choice than to try again... but then what do I do to recover the stories once I've upgraded (if I manage to upgrade)? Thanks!
Comment: If you follow the upgrade path, all content will come with you too.
Comment: But the idea here is to transfer the nodes to a different site. Not to keep them in the same site after upgrading...
Comment: @Jane, the different site is empty or have content ?
Comment: It's empty, just a theme, content types and views and a couple of other similar things.


Array.prototype.fill com um objeto reusa a mesma instância em todos as posições do array

Question: Necessito fazer um array multidimensional de tamanho variado, por exemplo 13 x 30.
Já consegui fazer, mas quando altero o valor de uma célula, ele altera de todos os itens daquele mesmo índice.
Já criei um array da seguinte forma:
const arr_teste = new Array(13).fill(new Array(30).fill(''));

O problema foi que quando alterei o valor de um item ele alterou de todos os demais, por exemplo:
arr_teste[1][1] = "Teste"

Resultou em:
(13) [Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30), Array(30)]
0
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
1
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
2
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
3
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
4
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
5
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
6
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
7
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
8
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
9
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
10
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
11
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
12
:
(30) ['', 'Teste', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
length
:
13
[[Prototype]]
:
Array(0)

Como faço para alterar apenas 1 item do array multidimensional?
Answer: Segundo a documentação do método fill:

all elements in the array will be this exact value: if value is an object, each slot in the array will reference that object

Ou seja, todas as posições do array são preenchidas com exatamente o mesmo valor. E se o valor for um objeto, todos os elementos do array serão referências para aquele objeto.
E como em JavaScript, arrays também são objetos, isso quer dizer que todos os 13 elementos do array arr_teste apontam para o mesmo array de 30 elementos.
Indo por partes:

new Array(30).fill('') cria um array com 30 elementos (sendo que todos eles são a string vazia)
depois, este array com 30 elementos é passado para new Array(13).fill, ou seja, é criado um array com 13 elementos, sendo que todos os 13 são referências para o mesmo array de 30 elementos

Por isso que ao mudar um deles, todos acabam sendo alterados, pois no fundo todos eles apontam para o mesmo array.
A própria documentação tem um exemplo para contornar isso. Basta criar várias instâncias deste array de 30 elementos, uma para cada posição do arr_teste:
const arr_teste = new Array(13);
for (let i = 0; i < arr_teste.length; i++) {
    // para cada posição do arr_teste, cria um novo array de 30 elementos
    arr_teste[i] = new Array(30).fill('');
}
// agora a alteração é feita somente no array da posição indicada
arr_teste[1][1] = "Teste";

Outra forma de fazer é usar Array.from, informando o tamanho e uma função de callback que retorna um novo array de 30 elementos a cada vez que é chamada:
const arr_teste = Array.from({ length : 13 }, elem => new Array(30).fill(''));
// agora a alteração é feita somente no array da posição indicada
arr_teste[1][1] = "Teste";


Uncaught TypeError: Cannot call method 'addEventListener' of undefined

Question: can't figure out where is the error in this code. Chrome debug console keep saying "Uncaught TypeError: Cannot call method 'addEventListener' of undefined" at line 31!
jewel.dom = (function() {

    var $ = Sizzle;

    function hasClass(el, clsName){

        var regex = new RegExp("(^|\\s) + clsName + (\\s|$)");
        return regex.test(el.className);
    }

    function addClass(el, clsName) {

        if (!hasClass(el,clsName)) {
            el.className += ""+ clsName;
        }
    }

    function removeClass (el, clsName) {

        var regex = new RegExp("(^|\\s)" + clsName + "(\\s|$)");
        el.className = el.className.replace(regex, " ");
    }

    function bind(element, event, handler) {

        if (typeof element == "string") {
            element = $(element)[0];
        }

        element.addEventListener(event, handler, false)
}

    return {
        $:$,
        hasClass : hasClass,
        addClass : addClass,
        removeClass : removeClass,
        bind : bind
    };
;}) ();

Comment: `element` does not exist. Please post the code which calls `bind()` and the code which definites `element`.
Comment: Found it! It was in another script the problem. I've used google chrome developer console e tracked the callback in the right script :D
Answer: In my case, this is caused by Evernote Clipper extension script. You will find "Evernote" in comment when you click to that script who throws out the error.
Comment: In my case I have this error in another script. Switching it off solved the problem
Answer: Could it be the case that your bind invocation ends up with an undefined element? (e.g. you pass a selector that does not match any of the elements in your DOM)
Answer: some browsers don't know what "addEventListener" is. Try this:
Element.prototype.setEvent = function(eventName, handler)
{
    if(document.addEventListener)
    {
        this.addEventListener(eventName, handler);
    }
    else
    {
        if(document.attachEvent)
        {
            this.attachEvent("on" + eventName, handler);
        }
    }
}
element.setEvent(eventName, handler);

The same goes for removeEventListener.
Also, try to replace
 element = $(element)[0];

with
 element = $("#" + element);

provided that string contains the id of the element, or
 element = $("." + element)[0];

if the string contains the className of the element.
Comment: This browser does know: "TypeError: Cannot call method 'addEventListener' `of undefined`" at line 31!"
Comment: It's not a browser problem, maybe Pavlov is right...who knows where in the various script is the problem...


Quote to Order Reference in punchout

Question: I am trying to figure out how to maintain the quote to order reference when a buyer retrieves a quote/order from my punchout catalog.
What I mean by this is, when the supplier catalog sends back the products to the buyer's requisition system in a "PunchoutOrderMessage" There is no place for the supplier to enter a quote id.  I have looked through the cxml spec but I am not seeing anything.  Am I missing something?
I have included a sample "punchoutordermessage". Can anyone help me figure out how to send a quote ID back to the buyer?
<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
<cXML payloadID="2008-12-24T10:46:32-06:email@example.com" xml:lang="en-US" timestamp="2008-12-24T10:46:32-06:00">
  <Header>
    <From>
      <Credential domain="NetworkId">
        <Identity>testcompany</Identity>
      </Credential>
    </From>
    <To>
      <Credential domain="NetworkId">
        <Identity>testsite</Identity>
      </Credential>
    </To>
    <Sender>
      <Credential domain="www.testsite.com">
        <Identity>PunchoutResponse</Identity>
      </Credential>
      <UserAgent>PunchoutSite</UserAgent>
    </Sender>
  </Header>
  <Message>
    <PunchOutOrderMessage>
      <BuyerCookie>PSFT_2008-12-24T10:44:00-06:00</BuyerCookie>
      <PunchOutOrderMessageHeader operationAllowed="edit">
        <Total>
          <Money currency="USD">205.34</Money>
        </Total>
      </PunchOutOrderMessageHeader>
      <ItemIn quantity="2">
        <ItemID>
          <SupplierPartID>123</SupplierPartID>
          <SupplierPartAuxiliaryID />
        </ItemID>
        <ItemDetail>
          <UnitPrice>
            <Money currency="USD">102.67</Money>
          </UnitPrice>
          <Description xml:lang="en-US">PRESSURE GAUGE</Description>
          <UnitOfMeasure>EA</UnitOfMeasure>
          <Classification domain="UNSPSC">123</Classification>
          <ManufacturerPartID>123</ManufacturerPartID>
          <ManufacturerName>testManufacturer</ManufacturerName>
        </ItemDetail>
      </ItemIn>
    </PunchOutOrderMessage>
  </Message>
</cXML>
</code>
Answer: The "SupplierPartAuxiliaryID" node is designed to be used by the supplier for whatever data you would like to pass with the quote (punchoutordermessage) that will be stored with the order through requisition mgmt, transferred to the PO,and returned to you with the ordermessage. This is where you can send your quote id (or quote id/line number).
Comment: Thanks, for the response. I will be testing this out in the next couple weeks, it it works, I'll come back and mark it as an answer
Comment: I have actually done a little more research on this and I don't think this is the right way to do this...  I will come back with another update once we are complete with this implementation.
Answer: We are going to use the extrinsic elements.
<code>    <ItemIn quantity="1">
         <ItemDetail>
           <UnitPrice>
               <Money currency="USD">1.23</Money>
          </UnitPrice>
          <Description xml:lang="en-US">product 123</Description>
          <UnitOfMeasure>FT</UnitOfMeasure>
          <Classification domain="UNSPSC">31151601</Classification>
          <ManufacturerPartID>1234</ManufacturerPartID>
          <ManufacturerName>Test Company</ManufacturerName>
          <Extrinsic name="QuoteId">12345</Extrinsic>
          <Extrinsic name="QuoteLine">1</Extrinsic>
         </ItemDetail>
   </ItemIn>
</code>

Quote to Order Reference in punchout


I cannot add a new CSS class to the classes_array array

Question: I'm using Drupal 7, and a Bootstrap sub-theme. I am using the following code to add a new CSS class (taxonomy-[vocabulary-name]) to the classes_array array.
template.php
function bootstrap_gstt_preprocess_html(&$variables) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $results = _bootstrap_gstt_taxonomy_node_get_terms($node);
    $taxonomy_vocab = $results->name;
    if (is_array($results)) {
      foreach ($results as $item) {
        $taxonomy_vocab = "taxonomy-".strtolower(drupal_clean_css_identifier($item->name));
        $variables['classes_array'][] = $taxonomy_vocab;

        $variables['classes'] = implode(' ', $variables['classes_array']);
        dpm($variables['classes_array']);
      }
    }
  }
}

function _bootstrap_gstt_taxonomy_node_get_terms($node, $key = 'tid') {
  static $terms;
  if (!isset($terms[$node->vid][$key])) {
    $query = db_select('taxonomy_index', 'r');
    $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
    $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
    $query->fields( $t_alias );
    $query->condition("r.nid", $node->nid);
    $result = $query->execute();
    $terms[$node->vid][$key] = array();
    foreach ($result as $term) {
      $terms[$node->vid][$key][$term->$key] = $term;
    }
  }
  return $terms[$node->vid][$key];
}

html.tpl.php
<!DOCTYPE html>
<html<?php print $html_attributes;?><?php print $rdf_namespaces;?>>

  <link rel="profile" href="<?php print $grddl_profile; ?>" />
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>

  <?php print $scripts; ?>

<body<?php print $body_attributes; ?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

With dpm($variables['classes_array']);, the new CSS classes I added appear in the array, but they aren't output as body CSS classes.
Is there anything I need to change in my code?
Comment: what's code in file html.tpl.php ?
Comment: I'm voting to close this question as off-topic because it's been [cross-posted on Stack Overflow](http://stackoverflow.com/questions/39333719/drupal-7-classes-array-cant-add-class-to-body-tag). Please post a question to one site in the network only.
Comment: Clive - I'll remove it from the other stack overflow as this site is more relevant
Comment: Sounds good - while you're there, probably a good idea to add some more details. It isn't answerable at the moment, but probably will be if you edit the post and include the full preprocessing function (including signature), and details of what theme/base theme you're using
Comment: Clive - I can't seem to be able to delete my question on the other network :/
Comment: Notice that in your html.tpl.php file you are using `>`. Since you aren't using `$classes` to set the CSS classes for ``, you will not see any extra CSS classes. Also, you are saying that you are not able to add new-body-class-name as CSS class for ``, but your code doesn't even seem to add `'new-body-class-name'` to `$variables['classes_array']`.
Comment: @kiamlaluno - sorry, the description was using a shortened example, I've tidied it up now... How would I add the new class name to the $body_attributes variable ?  I suffer the same problem of the body class not being updated when I use {$variables['body_attributes'][] = $taxonomy_vocab;}
Answer: You simply do as Drupal does in its html.tpl.php file. Instead of using <body<?php print $body_attributes; ?>>, you use the following code.
<body class="<?php print $classes; ?>" <?php print $attributes;?>>

$attributes is set from template_preprocess() with the following code.
  // Flatten out attributes, title_attributes, and content_attributes.
  // Because this function can be called very often, and often with empty
  // attributes, optimize performance by only calling drupal_attributes() if
  // necessary.
  $variables['attributes'] = $variables['attributes_array'] ? drupal_attributes($variables['attributes_array']) : '';
  $variables['title_attributes'] = $variables['title_attributes_array'] ? drupal_attributes($variables['title_attributes_array']) : '';
  $variables['content_attributes'] = $variables['content_attributes_array'] ? drupal_attributes($variables['content_attributes_array']) : '';

Also, you don't need the following line in bootstrap_gstt_preprocess_html().
$variables['classes'] = implode(' ', $variables['classes_array']);

template_process(), which is executed after bootstrap_gstt_preprocess_html(), contains the following code.
  // Flatten out classes.
  $variables['classes'] = implode(' ', $variables['classes_array']);

So, what your code is doing is already done from Drupal.
As side note, this what I would change in the code you shown.
$results = _bootstrap_gstt_taxonomy_node_get_terms($node);
$taxonomy_vocab = $results->name;
if (is_array($results)) {
  // Omissis.
}

Since _bootstrap_gstt_taxonomy_node_get_terms() is surely returning an array, you cannot access an object property as you do with $results->name.
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');

If you are going to use the value returned from $query->join(), then you should use the following code.
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = %alias.tid');
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

Also, since you are using $key (whose default value is 'tid') in the rest of the code, you should probably use the following code.
$t_alias = $query->join('taxonomy_term_data', 't', "r.$key = %alias.$key");
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

To understand what %alias means, see SelectQuery::join().

$condition: The condition on which to join this table. If the join requires values, this clause should use a named placeholder and the value or values to insert should be passed in the 4th parameter. For the first table joined on a query, this value is ignored as the first table is taken as the base table. The token %alias can be used in this string to be replaced with the actual alias. This is useful when $alias is modified by the database system, for example, when joining the same table more than once.

If you are sure the same table is not joined more than once, you can simply ignore the value returned from $query->join() and use the following code.
$query->join('taxonomy_term_data', 't', "r.$key = t.$key");
$query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');

Comment: A fantastic, detailed reply - thanks for your time and effort.  It really is appreciated


Prove existence of a bijective combined function given 2 separate bijective functions.

Question: Prove if there exists a bijective function from $A$ to $C$ and a bijective function from $B$ to $D$, then there exists a bijective function from $A \times B$ to $C \times D$. Here, $A \times B$ refers to the set $\{(a,b) | a \in A, b \in B\}$ and $C \times D$ refers to the set $\{(c,d) | c \in C, d \in D\}$.
Comment: Can you make a guess as to a suitable candidate function?
Comment: I'm not sure if I know one but even if I do, I may be making assumptions on the functions.
Comment: You can assume there is a bijection $f:A\to C$, and another bijection $g:B\to D$. So the question is how to combine these two to get a bijection $h:A\times B\to C\times D$. A typical member of $A\times B$ is $(a,b)$. So what would you expect $h(a,b)$ to be?
Answer: Yes there is. If $f : A \rightarrow C$ and $g : B \rightarrow D$, then
$(a,b) \mapsto (f(a),g(b))$ is a bijection.


N is a normal subgroup of G if $aNa^{-1} \subset N $ for all $a ∈ G$. Prove that in that case, $aNa^{-1} = N $.

Question: I said if N is a normal subgroup of G when $aNa^{-1} \subset N $ aN = Na as N is a normal subgroup of $G$.
Therefore $aNa^{-1} = Naa^{-1} $ and $aNa^{-1} = N $.
I would like to go with this proof but it looks too simple for now?
Comment: I am unable to follow your train of thought. Did you go from $aNa^{-1}\subseteq N$ to $aN=Na$? That implication isn't true. It is true if you put $\forall a$s in front of both claims, but you would have to *show* that. What, exactly, are you trying to prove anyway? That if $aNa^{-1}\subseteq N$ for all $a$, then $aNa^{-1}=N$ for all $a$? This strikes me as very difficult to read.
Comment: I just meant aN = Na would be true as N is defined as a normal subgroup!
Comment: What's your definition of normal subgroup? What are you trying to prove?
Comment: Normal subgroup defined as $aNa^{-1} \subset N$.
Comment: It's defined as a subgroup for which $aNa^{-1}\subseteq N$ for all $a$, yes. So the definition has $\subseteq$, not $=$ in it! Thus, $aNa^{-1}=N$ is *not* part of the definition of "normal subgroup" you are working with. You have to actually prove that property. And that *is* what you're trying to prove, no? That if $N$ is normal then we know $aNa^{-1}=N$ for all $a$ (not just $aNa^{-1}\subseteq N$)? Surely you can't assume the thing you're trying to prove in an argument?
Answer: Indeed since $N\lhd G$ then for all $g\in G$ we have $N^g\subseteq N$. Now do this for $g^{-1}\in G$ so we see that $N^{g^{-1}}\subseteq N$ and therefore $$(N^{g^{-1}})^g\subseteq N^g$$ But what is $(N^{g^{-1}})^g$ then?
Comment: Does $N^g$ denote $gNg^{-1}$?
Comment: @angryavian either that or $g^{-1}Ng$, it doesn't really matter which!
Comment: @blue It does matter: $N^g=g^{-1} N g$, since it is a right action. If you want a left action of $G$ on the conjugates of $N$, then you take the other one $^gN=N^{g^{-1}} = g N g^{-1}$.
Comment: @LiorB-S Yes group theorists use that choice because it makes sense as a right action; it would be very weird to write a left action on the right. My comment was pointing out that it doesn't matter which choice of definition one uses; the reasoning in the answer works either way.
Comment: Weirdness is a matter of whether you are used to it or not. In any rate you can write $N^{g^{-1}}$.


reason to use TLS 1.1

Question: is there any real reason why I should keep TLS 1.1 enabled?
I can understand that enabling 1.0 widens compatibility, but can bring security problems if not properly configured, while according to this table
https://en.wikipedia.org/wiki/Template:TLS/SSL_support_history_of_web_browsers#cite_note-Android-SSLSocket-46 there is almost no browser That supports TLS 1.1 but not TLS 1.2.
even though TLS 1.1 is not broken or anything but the PRFs are mainly using SHA1 and MD5 which has its own implications and might get broken easier in the future and as I said TLS1.1 doesnt really increase compatibility.
so is there any real point for using TLS 1.1, at least on an HTTPS Server?
Answer: Yeah there is no real reason to have TLSv1.1 turned on since, as you point out, nearly every browser that supports 1.1 also supports 1.2.
However, there are some edge cases which might benefit from this. See here for an example: https://github.com/ssllabs/ssllabs-scan/issues/258
On the flip side, there is no downside to leaving 1.1 enabled for now since it's still secure (providing it's properly configured) so might as well leave it on IMHO.
You could also turn on TLS protocol monitoring on your site to see how if it's being used by your visitors. For Apache this is done with a custom log format:
https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#logformats and you can do similar with Nginx.

reason to use TLS 1.1


Eigenthings of matrices with nonconstant coefficients

Question: If we have a system of equations of the form
$$\left(\begin{array}{c}
f_1(t)\\
f_2(t)\\
\vdots\\
f_n(t)
\end{array}\right)=\left(\begin{array}{cccc}
a_{11}(t) & a_{12}(t) & \cdots & a_{1n}{t}\\
a_{21}(t) & a_{22}(t) & \cdots & a_{2n}(t)\\
\vdots & \vdots & \ddots & \vdots\\
a_{n1}(t) & a_{n2}(t) & \cdots & a_{nn}(t)
\end{array}\right)\left(\begin{array}{c}
g_1(t)\\
g_2(t)\\
\vdots\\
g_n(t)
\end{array}\right)$$
where, let's say that the coefficients $a_{ij}(t)$ are allowed to have some dependence on $t$ (some of which might be constant anyway) but are 'nice' functions, e.g. simple exponential functions, nothing with any discontinuities or anything, is it still valid to find eigenvectors and eigenvalues by the same methods as for constant terms $a_{ij}$?
Comment: If the functions are polynomial you can use [the Smith Normal Form](https://en.wikipedia.org/wiki/Smith_normal_form)
Answer: Yes. Your eigenthings will now themselves be functions of $t$, but if you're ok with that then have at it!


What is the name of this musical scale: E, F, G, G#, B, C#, D?

Question: What is the name of this scale? As far as a root note goes, I think these three arrangements of it sound like they have a root.

E, F, G, G#, B, C#, D...
D, E, F, G, G#, B, C#...
B, C#, D, E, F, G, G#...
Comment: I don't have an answer, but I'll note that the G#s are probably A flats. You usually try to spell things so each pitch has a different letter name.
Comment: @ElEctric - as far as this is concerned, G# and Ab will be deemed the same pitch.
Comment: @AndyBonner And since G♯ and A♭ are not necessarily the same pitch.
Answer: According to Ianring.com, and depending on the root:

Root = E: Kathian. An Internet search suggests that this scale and its name only show up on scale-naming sites. No practical uses were found.
Root = D: Jeths' Mode.

This scale is named after Dutch composer Willem Jeths [1959–; composer's website]. It is essentially a Diminished Scale omitting the augmented 5th. Strangely, there is no documentation of why this scale was named for Willem, but at some point it wandered onto a list of scales and has been canonized by repetition. (ianring.com)

Root = B: Moravian Pistalkova. This scale, like Kathian, seems to appear only on lists of scales.

All of these scales are related to what ianring.com calls Mela Ramapriya (ianring.com, Wikipedia), but which is also known as the Petrushka (Stravinsky) scale (for reasons unclear, but presumably related to the Petrushka chord [Wikipedia], which is a subset), and the Hungarian Major scale (Wikipedia).
Comment: To spare readers some brainpower: The Petrushka chord rooted on G or C# is a subset because the OP's scale contains both of these major triads.
Comment: "Pistalkova" also appears in track 10 of this collection of Slovak folk music:  [Original Slovak Folk Music 2](https://www.warnerchappellpm.com/album/fontana-music-library-fn165/MTMzMTM4MS1lMWRhZTg).  Not sure if it's actually the same scale.
Comment: Thank you for responding! The scale works great over E7#9, 13 chord and harmonizing the whole thing out makes for some great chord progressions.
Answer: You have here 7 out of 8 notes of the octatonic scale.  You can create this scale by alternating whole- and half-steps.  Related to @PiedPiper's answer, the octatonic scale is also the combination of all the notes in any two diminsihed-seventh chords.
For the present question, take the Edim7 and Fdim7 chords...

E G Bb Db
F Ab B D

E - F - G - Ab - Bb - B - Db - D

You are missing only the Bb.
Also, because there are only seven letter names for the notes you will have to repeat one letter.
Answer: The notes all fit a diminished scale (on D, F or G#) but missing A#(Bb).


Problemas na busca de dados por nome, não retorna nada

Question: Estou com problemas ao fazer a busca de dados por nome. A seguir está o código.
Desde já, agradeço.
<?php include_once 'dbconfig.php'; ?>
<?php include_once 'header3.php'; ?>

    <legend style="color:#FFF" align="center">
Resultado da Busca por Nome
</legend>
    <form action="" method="get" id='form-contato' class="form-horizontal col-md-10">
        Pesquisar

            <input type="text" class="form-control" id="nome" name="nome" placeholder="Infome o Nome">

        <button type="submit" class="btn btn-primary">Pesquisar</button>
        Ver Todos
    </form>

            #
            Nome
            Sobrenome
            Email
            Telefone
            Ação

        <?php
            $nome=(isset($_GET['nome']));
            if(!empty($nome))
            {
                $sql = "SELECT * FROM dbpdo.tbl_usuarios WHERE nome LIKE :nome OR email LIKE :email";
                $stm = $DB_con->prepare($sql);
                $stm->bindValue(":nome", $nome);
                $stm->bindValue(":email", $nome);
                $stm->execute();

                if($stm->rowCount()>0)
                {
                    while($row=$stm->fetchAll(PDO::FETCH_OBJ))
                    {
                        ?>

                            <?php print($row['id']); ?>
                            <?php print($row['nome']); ?>
                            <?php print($row['sobrenome']); ?>
                            <?php print($row['email']); ?>
                            <?php print($row['telefone']); ?>

                            <a href="edit-data.php?edit_id=<?php print($row['id']); ?>">

                            <a href="delete.php?delete_id=<?php print($row['id']); ?>">

                        <?php
                    }
                }
                else
                {
                    ?>

                            Não existem dados para visualizar!

                    <?php
                }
            }

        ?>

<?php include_once 'footer.php';?>

Comment: deixei minha resposta, o valor é um porque o isset retornou true! ele não atribuiu o valor do $_GET['nome'] e sim do retorno do isset($_GET['nome']) que é "true ou 1" pois o valor foi passado no $_GET...
Comment: Qual o problema? Erro de sintaxe, retorna só uma parte, não retorna nada?
Comment: Não retorna nada.
Comment: Daniel, aproveita e coloca na descrição do seu problema isso que você me disse. Qual o valor de `$nome`? Imprima na tela seu valor
Comment: O valor de $nome, pega-se a partir do método $_GET['nome'].
Comment: Sim, eu sei. Qual o conteúdo? Por isso que pedi para imprimir ela na tela. Talvez como um header `` para ficar bem grande
Comment: Ok. O valor de $nome é 1, seja qual for o nome que puser na busca.
Comment: Então eu creio que você não tem ninguém com nome 1 ou e-mail 1. E-mails precisam de @, e nome 1 não faz sentido.
Comment: Isso mesmo! E como faço para que o valor de $nome seja o que eu digitar na busca?
Comment: Isso é de `form html` que faz uma vida que não mexo, mal aí. Tente acessar passando o valor no browser, passando o `query param` de jeito controlado: `127.0.0.1/pagina.php?nome=jeff`
Comment: Passando o valor no browser, continua na mesma, até porque mesmo passando o valor na busca, também vê-se o no browser.
Answer: Olá fiz algumas mudanças no seu arquivo, quando você verifica o isset e atribui ele a uma variável você está atribuindo um valor booleano (true/false) então acredito que possa ser isso. Outra coisa, quando você usa o PDO::FETCH_OBJ você tem que recuperar o mesmo como um objeto e não um vetor. Exemplos:

Acessando atributo de um objeto:

$row->id

Acessando valor de um vetor(array):

$row['id']

Nota: Tente também verificar se tá certo a sua conexão com o banco, assumindo que você seleciona um banco default na sua conexão eu tomei a liberdade de remover o nome do banco (dbpdo.) em seu SQL.

Deixo abaixo as modificações que acredito que deveriam ser feitas para o seu script funcionar.
<?php include_once 'dbconfig.php'; ?>
<?php include_once 'header3.php'; ?>

    <legend style="color:#FFF" align="center">
Resultado da Busca por Nome
</legend>
    <form action="" method="get" id='form-contato' class="form-horizontal col-md-10">
        Pesquisar

            <input type="text" class="form-control" id="nome" name="nome" placeholder="Infome o Nome">

        <button type="submit" class="btn btn-primary">Pesquisar</button>
        Ver Todos
    </form>

            #
            Nome
            Sobrenome
            Email
            Telefone
            Ação

        <?php
            $nome = isset($_GET['nome']) ? $_GET['nome'] : '';
            if(!empty($nome))
            {

                $nome = '%'.$nome.'%';

                $sql = "SELECT * FROM tbl_usuarios WHERE nome LIKE :nome OR email LIKE :email";
                $stm = $DB_con->prepare($sql);
                $stm->bindValue(":nome", $nome);
                $stm->bindValue(":email", $nome);
                $stm->execute();

                if($stm->rowCount()>0)
                {
                    while($row=$stm->fetchAll(PDO::FETCH_OBJ))
                    {
                        ?>

                            <?=$row->id?>
                            <?=$row->nome?>
                            <?=$row->sobrenome?>
                            <?=$row->email?>
                            <?=$row->telefone?>

                            <a href="edit-data.php?edit_id=<?=$row->id?>">

                            <a href="delete.php?delete_id=<?=$row->id?>">

                        <?php
                    }
                }
                else
                {
                    ?>

                            Não existem dados para visualizar!

                    <?php
                }
            }

        ?>

<?php include_once 'footer.php';?>

Comment: Muito obrigado irmão! Solucionou meu problema.
Comment: @DanieldosSantos Opa estamos aqui pra isso.


Do redundant constraints help in big-M reformulation?

Question: I am trying to reformulate an optimisation problem with unknown $x$ of dimension $K\times 1$ into a mixed-integer program using big-M transformation.

In this respect, among my constraints, I have that
$$
\text{ $(\star)$
for $i=1,...,21$: $r_i(x)=0$ $\Rightarrow$ $l_{i,j}(x)=0$ for $j=1,...,8$}
$$
where $r_i, l_{i,j}$ are linear functions of $x$ mapping from $\mathbb{R}^K$ to $\mathbb{R}$.
Following the answers to my previous questions (e.g., here) $(\star)$ can be rewritten introducing $3$ binary variables $\gamma_{1,i,j},\gamma_{2,i,j},\gamma_{3,i,j}$ and a tolerance level $\epsilon>0$
$$
\begin{cases}
\gamma_{1,i,j}=1\Rightarrow r_i(x)\leq -\epsilon\\
\gamma_{3,i,j}=1\Rightarrow r_i(x)\geq \epsilon\\
\gamma_{2,i,j}=1\Rightarrow -\epsilon\leq r_i(x)\leq \epsilon\text{, } l_{i,j}(x)=0\\
\gamma_{1,i,j}+\gamma_{2,i,j}+\gamma_{3,i,j}=1
\end{cases}
$$
Now, the rewriting above means introducing $3*21$ binary variables. This, combined with my other constraints (that include many other big-M transformations), slow things down tremendously.

I have noticed that in my problem BY CONSTRUCTION there are some relations of the type
$$
r_i(x)=0 \Rightarrow r_t(x)=0
$$
for some $i=1,...,8$, $t=1,...,8$ (these are not constraints; they just happen by construction).
Using the same logic as above, this can be rewritten
introducing $3$ binary variables $\beta_{1,i},\beta_{2,i},\beta_{3,i}$ and a tolerance level $\epsilon>0$
$$
\begin{cases}
\beta_{1,i}=1\Rightarrow r_i(x)\leq -\epsilon\\
\beta_{3,i}=1\Rightarrow r_i(x)\geq \epsilon\\
\beta_{2,i}=1\Rightarrow -\epsilon\leq r_i(x)\leq \epsilon\text{, } r_{t}(x)=0\\
\beta_{1,i}+\beta_{2,i}+\beta_{3,i}=1
\end{cases}
$$

Question: does adding these additional constraints make the solver any faster? Or, since we are including even more binary variables, things get worse?
Answer: I think the question of whether redundant constraints help is in general an empirical one. Sometimes they do, sometimes they don't. The extra binary variables might indeed slow things down, but they also might not.
One concern I would have would be whether the $\beta$ variables might "distract" the solver from focusing on other integer variables that perhaps would be more important. If I thought that were happening, I would try adding branching priorities (which at least some solvers let you supply). Branching priorities are basically weights assigned to the integer variables, such that the solver is encouraged/compelled to branch first on the variables with higher priority. Giving the $\beta$ variables lower priorities would at least keep the solver focused on the other integer variables.


No Data Scraped w/Rvest package?

Question: <code># Load Packages
pacman::p_load(tidyverse, rvest)

# Set URL
url <- "https://www.worldometers.info/coronavirus/"
website <- read_html(url)

# Scrape Cases Data
cases_html <- html_nodes(website, "td.sorting_1")
cases <- html_text(cases_html)

cases_html
cases
</code>
I am trying to scrape webdata with rvest, but am getting the following errors when I check my two variables here ("cases_html" and "cases"). The output for each respectively is:
<code>> {xml_nodeset (0)}

> character(0)
</code>
I am not sure why I am getting no data scraped from this website. I have also tried using the RSelenium package like recommended in another post here, but that code also failed with an unrelated error. I figure the solution should be available within Rvest, however, and I would like to figure out what exactly is wrong here.
Answer: It's not clear what you are trying to scrape from the page, but you can get the main data table like this:
<code>library(tidyverse)
library(rvest)

read_html("https://www.worldometers.info/coronavirus/") %>%
  html_nodes("#main_table_countries_today") %>%
  html_table() %>%
  pluck(1)
#> # A tibble: 244 x 22
#>      `#` `Country,Other` TotalCases  NewCases   TotalDeaths NewDeaths
#>    <int> <chr>           <chr>       <chr>      <chr>       <chr>
#>  1    NA "North America" 98,313,200  "+23,167"  1,459,752   "+147"
#>  2    NA "Asia"          147,921,193 "+130,458" 1,423,876   "+395"
#>  3    NA "South America" 56,801,380  "+17,492"  1,294,318   "+31"
#>  4    NA "Europe"        191,122,646 "+187,856" 1,817,850   "+587"
#>  5    NA "Oceania"       7,156,060   "+46,381"  10,626      "+59"
#>  6    NA "Africa"        11,902,057  "+6,666"   253,795     "+4"
#>  7    NA ""              721         ""         15          ""
#>  8    NA "World"         513,217,257 "+412,020" 6,260,232   "+1,223"
#>  9     1 "USA"           83,055,836  "+18,777"  1,020,749   "+89"
#> 10     2 "India"         43,079,157  "+3,293"   523,803     ""
#> # ... with 234 more rows, and 16 more variables: TotalRecovered <chr>,
#> #   NewRecovered <chr>, ActiveCases <chr>, `Serious,Critical` <chr>,
#> #   `Tot Cases/1M pop` <chr>, `Deaths/1M pop` <chr>, TotalTests <chr>,
#> #   `Tests/1M pop` <chr>, Population <chr>, Continent <chr>,
#> #   `1 Caseevery X ppl` <chr>, `1 Deathevery X ppl` <chr>,
#> #   `1 Testevery X ppl` <int>, `New Cases/1M pop` <chr>,
#> #   `New Deaths/1M pop` <dbl>, `Active Cases/1M pop` <chr>
</code>
Created on 2022-04-30 by the reprex package (v2.0.1)
Comment: What does the pluck(1) do in this case?

No Data Scraped w/Rvest package?


Among Kubernetes, OpenShift, Docker Swarm and Docker DataCenter deployment tools which all are having automatic rollback?

Question: Among Kubernetes, OpenShift, Docker Swarm and Docker DataCenter deployment tools which all are having automatic rollback in case of any failure happens?
Answer: All of them have a sort of rollback mechanism built-in with commands available for you to control. However, these are not fully automated and you might have to do it manually. For Kubernetes, here is the related github issue and another issue for Swarm. Docker DataCenter use Swarm already.
Rollback documentations I was able to find:

Kubernetes: Rolling Back a Deployment
Swarm: Roll back to the previous version of a service (features <code>--update-delay</code>)
OpenShift: Rolling Back a Deployment


Check if List exists

Question: This is my code
List<string> list = new List<string>() { "bfd", "jy", "aaaaa", "ndnk", "ntfn", "gfm", "gfm", "mhgd5h", "srsr", "ntr", "mtmyt", "dmy", "mmy6", "ngn9d", "y6m1", "d8dm", "bbbbb", "tym", "dmj", "trsh", "tsr"};
List<string> test = new List<string>() {"aaaaa","bbbbb","ccccc","ddddd","eeeee","fffff","ggggg" };

foreach (var a in list)
{
    foreach (var i in test)
    {
        if (i.StartsWith(a) == false)
        {
            Console.WriteLine(i);
        }
    }
}

I want to output from the list and match in the test. If the test exists, then it will not be displayed. If there is no side output,But there may be a problem with my code, it will output the same value many times
The list contains aaaaa, according to logic, aaaaa should not be output
Comment: I _suspect_ what you want is `var results = list.Except(test).ToList();`
Comment: The code does what you asked it to do. So, take a step back. What **exactly** do you want outputted (the **exact** thing you want outputted)?
Comment: Can you give a couple of examples of inputs & their respective outputs you expect to get?
Comment: Sorry, I updated the code
Comment: What **exact** output do you want? Don't tell us what you _don't_ want - tell us **exactly** what you expect the output to be.
Answer: Try this:
      List<string> list = new List<string>(){"bfd", "jy", "aaaaa", "ndnk", "ntfn", "gfm", "gfm", "mhgd5h", "srsr", "ntr", "mtmyt", "dmy", "mmy6", "ngn9d", "y6m1", "d8dm", "bbbbb", "tym", "dmj", "trsh", "tsr"};

      List<string> test = new List<string>(){"aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "ggggg"};

        foreach (var a in list)
        {
            if (!test.Contains(a))
            {
                Console.WriteLine(a);
            }
        }

Answer: There are simple solutions using LINQ. But since I assume this is an exercise, I will show you the detailed version using loops.
The problem is that the WriteLine is inside the inner loop. Therefore you will get many repetitions. Store the outcome of the test in a Boolean variable and place the display part after the inner loop.
foreach (var a in list)
{
    bool found = false;
    foreach (var i in test)
    {
        if (i.StartsWith(a))
        {
            found = true;
            break; // Exit the inner loop
        }
    }
    if (!found)
    {
        Console.WriteLine(a);  // We must output a here since i out of scope.
    }
}

Also, if you want to know whether a specific string is contained in the list, you should probably replace i.StartsWith(a) with i == a.

The code becomes easier to read, if you extract the list search into its own method
private bool IsInList(List<string> list, string item)
{
    foreach (string s in list)
    {
        if (s == item)
        {
            return true;
        }
    }
    return false;
}

Now, you don't need the Boolean variable any more
foreach (var a in list)
{
    if (!IsInList(test, a))
    {
        Console.WriteLine(a);
    }
}

I used !condition (pronounce: "not condition") instead of condition == false. It's terser.

I assume that this is an exercise. In production code you would simply use the built in method Contains of the list.
foreach (var a in list)
{
    if (!test.Contains(a))
    {
        Console.WriteLine(a);
    }
}

or even (as @mjwills suggests in his comment):
foreach (var a in list.Except(test)) {
    Console.WriteLine(a);
}

Check if List exists


How to force a dev release of my module?

Question: Whenever I go to create a release for my contrib module, it gives me one option - 6.x-1.x (6.x-1.x-dev) - but if I select that it says "The version you have selected (6.x-1.x-dev) is already in use by another release." IIRC dev releases are packaged automatically every twelve hours, so why is this option even appearing? And it seems like dev releases aren't being packaged automatically for my module ...
Comment: Are you seeing the commits show up on the **Revisions** tab on the project?
Comment: See my comment below: I would have thought that the commit at http://drupalcode.org/project/csm.git/commit/b2b9979 would have triggered a new dev release, but it didn't
Answer: In the "Release" tab of your project you've a checkbox with "Show snapshot release". If you check it, you should see the dev releases appear.
Comment: Thanks, @yvan. That box is already checked, though. Dev releases were appearing until January this year, but not any more for the 6.x branch (and there's been a full release on that branch since then, which is appearing fine)
Comment: Well have you made any commits since January?
The dev release is automatically regenerated each day if there are new commits.
Comment: I would have that that this commit - http://drupalcode.org/project/csm.git/commit/b2b9979 - would have triggered a new dev release, but it didn't


Find an expression of the probability function when $f(x)=\frac{x}{10}$ is the PMF.

Question:
Suppose that
  $$
f(x) :=
\begin{cases}
  \dfrac{x}{10}, & x \in \{ 1,2,3,4 \} \\
  0, & \text{otherwise}
\end{cases}
$$
  is a probability mass function. Find an expression of the probability function $F(x)$.

Could you please help me, I solved it but my teacher said to me it was wrong and I searched by google but I did not find explain how can I find an expression of $F(x)$ with a discrete $f(x)$?
Comment: You need to provide more information. Specifically, how is f(x) related to F(x)? Not just have us guess.
Comment: Use the hint of @BjörnFriedrich and split up in cases $x<1$, $1\leq x<2$, $2\leq x<3$, $3\leq x<4$ and $4\leq x$. A would speak of a "[probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function)" (not the confusing "discrete pdf") here.
Comment: If $F(x)$ is the cumulative distributional function, then there is a hint in the name
Comment: just that f(x) is a pdf
Comment: Hint: $F(x) = \sum\limits_{x_i \leq x} f(x_i)$
Comment: yes  , I know this hint , but how can I use it to find expression F(x)
Answer: From $F(x) = \sum_{y \leq x} f(y)$ it follows, using Gauß' sum formula, that
$$
F(x) = \sum\limits_{y=1}^x \dfrac{y}{10} = \dfrac{1}{10} \cdot \dfrac{x(x+1)}{2} = \dfrac{x(x+1)}{20}.
$$
Comment: This only works for $x\in\{0,1,2,3,4\}$. The CDF however is defined on $\mathbb R$.
Comment: Someone downvoted your answer and (quite likely) the same person also downvoted my answer. I repaired by upvoting.
Comment: @drhab You upvoted a deficient answer to *compensate* other votes?? This is not how votes are supposed to work... (Why do you hypothetize that the same user downvoted this (wrong) answer and your (correct) answer?)
Comment: @Did Both answers were downvoted at almost the same moment.
Comment: @drhab And? $ $
Comment: @Did Nothing more to say about it.
Answer: Setting $S_{x}:=\left\{ 1,2,3,4\right\} \cap\left(-\infty,x\right]$
we have:
$F\left(x\right)=\sum_{i\in S_{x}}f\left(i\right)$.
If $x<1$ then $S_{x}=\varnothing$ and we are dealing with an empty
sum so that $F\left(x\right)=0$
If $1\leq x<2$ then $S_{x}=\left\{ 1\right\} $ and find $F\left(x\right)=f\left(1\right)=\frac{1}{10}$
If $2\leq x<3$ then $S_{x}=\left\{ 1,2\right\} $ and find $F\left(x\right)=f\left(1\right)+f\left(2\right)=\frac{1}{10}+\frac{2}{10}=\frac{3}{10}$
et cetera (see my comment).
Comment: One thing is for sure: nothing is wrong with the answer. The downvoter should at least feel the obligation to explain.