What sort of samples you need to record for a good flute sample pack

Question: I would like to create a sample pack of the Native American flute. I am new to this, but having looked around, you don't need thousands of samples in a sample pack, just maybe 100.
What I'm wondering is how to properly record samples for a flute?
That is, what angles and such do you need to record to capture all that the flute can do? (Not talking about which mics you use and all of that, just of the tones and effects you can do with the flute).
For example:

Slowly turning on a note.
Abruptly turning on a note.
The screechy sound of the flute.
The regular sound of the flute.
Transitions between notes?
Every possible note?

For example, do you need to record every possible note you can make on the flute, or can you just record everything in "A" and then use the effect tools in your software to modulate the sound to generate the rest of the notes (and would it sound accurate).
These sorts of things. Basically, what sounds go into a good flute library, and how many (order of magnitude) would be a good set.
Basically, how much variations of samples do you collect, vs. how much can software do the rest.
Comment: Are you planning to sell this, distribute it for free, or just keep it for your own use?
Comment: I am planning to distribute it for free, and use it for personal use.
Comment: Please elaborate on "having looked around" :  what sample packs are you referring to, and how are they intended to be used (e.g. subsequent processing and modification).
Answer: This boils down to "How much detail do you require, how much articulation & can your playback engine support that articulation?"
At one end of the scale we have the single sample, stretched the full length of the keyboard.
This is sampling circa 1985.
To that you could add a variable velocity-sensitive attack & a filter so loud notes are brighter than quiet.
In the middle, we have

Multiple volumes per note, which can be mapped from 1-127. This, by itself, will cover your varying attacks reasonably well. You need to decide how many layers to form this from - 2, 4, 8, 32... the 'good stuff' uses a lot.
Multiple samples at each of your previous 'velocities'. These you then use as a round-robin so it doesn't sound like a machine-gun if someone plays the same note over & over. The human ear is very good at spotting 'the same exact sound again'.

& out the topside of realism

partial waves which can be cross-faded so any single note can be changed over time; eg start soft then get louder - this only applies to wind (& bowed) instruments, but it's a great deal of the 'reality' of how they work. This would include overblow [otherwise you'd have to fake that into the top 10% of your 'velocity set'].
Algorithmic legato between notes, or samples of every possible legato jump at every velocity.
'Noises' - breaths, finger noise, taps & releases. These are all subliminal but contribute to the overall realism.

Additionally, the more detail you require in your data, the better a player you need to generate it & the better a sound engineer you need to record, edit, map & collate it.
You will need a good set of naming conventions too, so you don't get lost in the data pile.
https://audiomodeling.com has some great examples of the 'topside' of realism & there's a description of how their SWAM-W Engine works at https://audiomodeling.com/technology/swam-w/
Comment: Excellent information, exactly what I was looking for. Thank you. What is mapping to 127? And what are the layers? Why powers of 2?
Comment: @LancePollard How hard you hit a key on a MIDI keyboard is translated into a "velocity" value from 1 to 127. You can have different samples play for different (ranges of) values. You can have any number of layers, not just powers of 2.


Hook_menu() and its page callback: how to redirect users on a condition?

Question: I'm trying to redirect users from an existing path in Drupal 7 to another existing path. I want to implement the following rule:
comment/reply/123 should redirect to node/123#comment-form
But
comment/reply/123/456 should NOT redirect anywhere and just go where it goes.
I've tried to implement this behavior with hook_menu(), but here's the problem. When I register an item with the path 'comment/reply/%' that corresponds to comment/reply/123, it automatically includes paths like comment/reply/123/456. I know that's intended and changed my code to include this case, but can't figure out how to redirect users only when they hit comment/reply/123. Here's my code:

function mymodule_menu()
{
    $items = array();
    $items['comment/reply/%/%'] = array(
        'title' => 'bla',
        'page callback' => '_mymodule_redirect',
        'page arguments' => array(2, 3),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function _mymodule_redirect($node_id, $comment_id)
{
    if(isset($comment_id))
    {
        return; //I want to just go to comment/reply/123/456 here, but it gives me a blank page
    }
    else
    {
        drupal_goto('node/' . $node_id . '#comment-form');
    }
}

So how do I go where I want to go?
Update: This is my final solution: I now use hook_menu_alter() to rewrite an already defined link and comment_reply() to serve standard comment form.

function mymodule_menu_alter(&$items)
{
  $items['comment/reply/%node']['page callback'] = '_mymodule_redirect';
}

function _mymodule_redirect($node, $pid = NULL)
{
    if(isset($pid))
    {
         return comment_reply($node, $pid);
    }
    else
    {
        drupal_goto(drupal_get_path_alias('node/' . $node->nid), array('fragment' => 'comment-form'), 301);
    }
}

Answer: If you are altering a hook_menu item that an existing module defines, use hook_menu_alter. You will receive all menu items by reference, and you can alter the necessary menu items as necessary.
In a hook_menu() implementation, if you define example path, http://example.com/example, http://example.com/example/foo, http://example.com/example/foo/bar... and so on will have the same page callback and other properties. However, if you define http://example.com/example/foo/mine, that page will use the explicit definition of example/foo/mine. There is a negotiation with MENU_DEFAULT_LOCAL_TASK too.
PS: If you are trying to redirect comment pages to their node paths, try this module.
Comment: Thanks, I'm now using hook_menu_alter(). I can't mark 2 replies as 'Answers', but your reply was useful and I gave you a +1.
Answer: If I've understood correctly, you want to serve the comment reply page provided by core when your condition is met.
If that's the case, you just need to use the comment_reply() function:
if (isset($comment_id)) {
  return comment_reply(node_load($node_id), $comment_id);
}


Alesis DM Lite to Presonus 1818vsl

Question: Is Alesis DM lite compatible to Presonus 1818vsl cuz I'm gonna use an app called Auria on iPad
Comment: Can you give more information about that you're trying to use Auria for and how Alesis and Presonus relate to your use of Auria?
Answer: I think it seems that you want to record the Alesis DM Lite through the Presonus audio interface then the interface to Auria

Alesis DM Lite to Presonus 1818vsl


Setting value for a view filter

Question: How do I set a view filter so that the date of item makes it disappear WHEN the event occurs?
Right now when I edit the filter I have it Operator set to 'is greater than or equal to' and the Value set to 'today', but I want it to disappear at the exact time the event is occurring.
What do I put in 'value' for that to happen?
Comment: Did you try "now" as filter value?
Comment: no, but i'm going to try it now! Thanks for the suggestion :) Once the event happens we'll see if it works.
Answer: now worked. I also discovered +1 works for one hour before the event.

Setting value for a view filter


What examples to use when learning group theory?

Question: I am trying to learn group theory from the textbook Algebra by Michael Artin 2nd edition. I am looking for finite group and subgroup examples that are useful for developing an intuition about group theory. So far, I have been using the symmetric group $S_3$.
Preferably, I am looking for an example of a finite group and a subgroup that I can use to grasp the concepts of the book. A list would be nice. Or just direction towards a database of group examples could work too.
Comment: See https://en.wikipedia.org/wiki/List_of_small_groups
Comment: $S_3,$ as the smallest non-abelian group, is a good example
Comment: Thank you! Wikipedia is a good start.
Comment: Learn how to compute using cycle notation in permutation groups. https://groupprops.subwiki.org/wiki/Cycle_decomposition_for_permutations
Comment: See also https://people.maths.bris.ac.uk/~matyd/GroupNames/
Answer: Of course any answer to such a broad question has to be incomplete, but you might find the following helpful:

At the very beginning I think that (as you say) $S_3$ is a good example as an easy-to-grasp nonabelian group. And abelian groups aren't entirely uninteresting either - you should understand why $\mathbb{Z}/2\mathbb{Z}\times\mathbb{Z}/3\mathbb{Z}\cong\mathbb{Z}/6\mathbb{Z}$ but $\mathbb{Z}/2\mathbb{Z}\times\mathbb{Z}/2\mathbb{Z}\not\cong\mathbb{Z}/4\mathbb{Z}$. This sets the stage for the classification of finite(ly generated) abelian groups, and ultimately of finitely generated modules over a PID, but long before then is just a key point to understand - and the latter also serves as a good example of how the "obvious" statement $$A/B=C\implies A=B\times C$$ fails miserably in the context of groups, quotient groups, and direct products.
What about a bit further on - e.g. when we start talking about normal subgroups? In my opinion, $A_4$ and $A_5$ are quite good examples. Each is non-abelian, and $A_5$ is simple while $A_4$ is not - and that's already a good thing to have examples of. And proving that $A_5$ is the smallest non-abelian simple group is a good problem. And of course, eventually you'll care about solvable groups, and then $A_5$ is crucial.
There are also examples of groups which early on will just seem weird, but are really valuable. For example, a small semidirect product like $D_3$ (yes, that's just $S_3$, but thinking about it as a dihedral group is a bit better right now). It's easy enough to write out how this group works (without defining semidirect products - just defining this specific group), and compare it with the corresponding direct product $\mathbb{Z}/3\mathbb{Z}\times\mathbb{Z}/2\mathbb{Z}\cong\mathbb{Z}/6\mathbb{Z}$; while it will then be a while (probably) before you care about semidirect products, it will be useful to have in your head early on the idea that there are more complicated ways to combine groups than just the direct product.
And then there are infinite groups which are still "finite-flavored" - I'm thinking e.g. of matrix groups like $GL_n(\mathbb{R})$, the group of all invertible $n$-by-$n$ matrices with real number entries. This isn't such a great example if you're not already familiar with some linear algebra, but if you are it's really quite good to get your hands on it early.
Answer: Yes, you will have to learn the basics of algebra systems.
Magma Calculator
http://magma.maths.usyd.edu.au/calc/
and (or) Wolfram Mathematica. Magma is best to generally investigate the group structure. Mathematica is useful to support Magma with symbolic calculations and edge cases, when Magma is not convenient.
Making paper tetrahedrons and other regular n-gons for rotation symmetries will be a cool experience as well.
Comment: I disagree with the first sentence (which isn't to say they aren't useful). It's entirely possible to get a good sense of group theory without using them (or did nobody understand group theory before they came along?).


What's the model, controller, view in the following backbone.js example?

Question: I got this code:
(function($){
  var ListView = Backbone.View.extend({
    el: $('body'), // el attaches to existing element

events: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.

    events: {
      'click button#add': 'addItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here

      this.counter = 0; // total number of items added thus far
      this.render();
    },

render() now introduces a button to add a new list item.

    render: function(){
      $(this.el).append("<button id='add'>Add list item</button>");
      $(this.el).append("

");
    },

addItem(): Custom function called via click event above.

    addItem: function(){
      this.counter++;
      $('ul', this.el).append("
hello world"+this.counter+"
");
    }
  });

  var listView = new ListView();
})(jQuery);

from this tutorial.
I understand that Backbone.js introduces a MVC pattern to the front end.
But in the code above I can't see that.
Can anyone explain that to me?
Comment: dont use mvc, see criticisms of oop in web programming
Answer: There is technically no controller in backbone.js.  The main structures are Models, Views, Collections (that act as arrays and contain lots of models), and Routers.
The link you listed -  http://arturadib.com/hello-backbonejs/ - is probably the best way to learn Backbone.js - especially with little background in Javascript.  So you are on the right track.  That project is a direct lead-in to the backbone.js ToDo list tutorial:  http://documentcloud.github.com/backbone/docs/todos.html
This site will also explain things at a more basic level - I found it very helpful:  http://backbonetutorials.com/
Answer: That's just the view part code. See other .js files in the same tutorial. Better check out all the files from 1.js to 5.js
Better check it from first: Hello Backbone
Answer: Note that Backbone View isn't the one you expected in MVC its more like a controller or the presenter in MVP. Here is a nice article that describes this differences.


How to make a Shortcuts menu that open with new window or tab?

Question: In Drupal 7, I added the "IMCE" url(www.mydomain.com/imce) into the Shortcuts menu for user to upload file. How to make this menu to open in a new window or tab?
Answer: Shortcuts are menu items, so you might be able to use Menu Attributes to set the target to <code>_blank</code>.
Comment: My site already has Menu Attributes module installed, but this feature is not on "Shortcuts".


How do I add information from one CSV file to another based off of matching values in Python?

Question: I am trying to combine data from multiple CSV files into one CSV file. I have several files that have similar information. I want to add the information that I don't have to a single CSV file by matching similar cell data and appending the missing information to that corresponding row.
This is an image of the CSV file I want to add information to:
table I want to add to
This is an image of the CSV file I want to parse for information, and then add missing information to the joined CSV file: table I want to take information from
This is what I want my CSV file to look like in the end: desired result
I have simply copy and pasted here to demonstrate my goal, however I have a ton of data that I would like to add by checking it against my source table.
My strategy so far has been to use the CSV module and create a nested for loop that compares against the two rows. Right now my code only tries to see if there is a match between the two tables without trying to append anything. This is also proving difficult.
My output so far looks like this: current output
(note that in this image I was trying to add superintendent info, that is why the output is showing a name instead of the other information)
My code is iterating over more than I wanted. I was hoping that it would just compare the dictionary values I had called to.
#Python 3.6.4
import csv
import codecs

count = 0
original_csv = codecs.open("Texas School Districts.csv", 'r', encoding='utf-8', errors='ignore')
fieldnames1 = ['NCES LEA ID', 'State ID', 'District Name']
reader1 = csv.DictReader(original, fieldnames=fieldnames1)

additional_info = codecs.open("new_information.csv", 'r', encoding='utf-8', errors='ignore')
fieldnames2 = ['Name', 'District', 'Type', 'Description']
reader2 = csv.DictReader(additional_info, fieldnames=fieldnames2)

for row1 in reader1:
    for row2 in reader2:
        if row1['District Name'] == row2['Name']:
            print(row1['District Name'], ":", row2['Name'])
        else:
            pass
    count += 1
    original.seek(count)
    append.seek(0)

What would you guys recommend I do to accomplish the task of merging new data to existing values? Am I on the right track or have I gone way off? Please let me know if you have any questions, or if I can provide any more information. I hope I made some sense.
Comment: I would seriously contemplate using a database like SQLITE or Postrgres and just dumping your data into them, and using SQL to manipulate the data.  It's easier, and more efficient.
Comment: `for row1 in reader1:
    for row2 in reader2:` this double loop won't work since the file will be consumed at first pass in the inner loop.
Comment: Are you using python3?
Comment: @DataHerder I am using Python 3.6.4, I will update my post to state this.
Comment: @Jean-FrançoisFabre I had issues with the double loop at first because of this but by adding the .seek() methods that doesn't seem to be the problem anymore.
Comment: Then you don't need `codecs`, you can import just using `csv`.
Comment: okay but double loop are extremely unefficient. create a dictionary instead with contents of table 2 to avoid the loop
Comment: @Jean-FrançoisFabre Yea it is crazy inefficient lol. Could you guide me through the dictionary method? I am rather new to this and would love to learn more.
Comment: I say either use a database, or use pandas and the merge capability to join your tables:
https://pandas.pydata.org/pandas-docs/stable/merging.html
Comment: @anishtain4 I switched to Pandas and used the merge method. This got me the desired results. Thanks all!
Answer: If you want to continue doing this in native python, and not pandas, or a real database, you have to make this code faster:
for row1 in reader1:
    for row2 in reader2:
        if row1['District Name'] == row2['Name']:
            print(row1['District Name'], ":", row2['Name'])
        # seek to avoid reader2 to be EOF ...

no need for the second loop if you build a lookup set beforehand:
existing_names = {row["Name"] for row in reader2}

now use a single loop, and no need to rewind files:
for row1 in reader1:
    if row1['District Name'] in existing_names: # set lookup is faaast
            print(row1['District Name'])

Now code runs in O(n) (average) vs O(n**2)
Comment: This looks much more efficient! I will definitely take a look at Pandas, but this looks like something that I can try.
Comment: @ Jean-François Fabre I switched to Pandas and used the merge method. That solved my problem and did so very quickly! Thank you for recommending it.


numerical argument for $AB=I$ implies $BA=I$.

Question: Say $A$ and $B$ are square matrices with $K$-valued entries, $K$ a field.
There is an 'abstract' argument showing this implies $BA=I$, namely that $AB=I$ implies $A$ is surjective, so it is injective by rank-nullity, so its right inverse must be its left inverse. My question is whether there is some other, more 'numerical' argument showing this, since obviously one can interpret $AB=I$ as some system of equations. The argument should use (I think) the fact that $K$ is a field, since rank-nullity does not work over general modules. So somewhere in the argument division should be involved. Thanks in advance.
Comment: Possible duplicate of [If $AB = I$ then $BA = I$](https://math.stackexchange.com/questions/3852/if-ab-i-then-ba-i)
Comment: You can find many, many answers in [this thread](https://math.stackexchange.com/questions/3852/if-ab-i-then-ba-i).
Comment: You are basically asking for Cramer's rule.
Answer: An algebraic argument in terms of equations ("numerical") is possible, using the determinant. Since $1=\det I=\det(AB)=\det(A)\det(B)$, we know that $\det(A)\neq 0$ so that the inverse $A^{-1}$ exists. Hence $AB=I$ gives $B=A^{-1}AB=A^{-1}$, so that $BA=A^{-1}A=I$.
Comment: This is nice. I wonder whether there is an even more elementary approach.
Comment: @M.Van Possibly $BA=A^{-1}ABA=A^{-1}A=I$,
Comment: no, @J.G. , you just assumed $A$ is invertible!
Comment: @M.Van No; I was suggesting a simplification of the part of the argument that comes after invertibility is established.


jquery .submit()

Question: Trying to make a validation on form without <form> tag.
Its a structure of cms plugin, which uses ajax, don't know why inputs aren't wrapped with <form></form>.
Html:

    <input id="name" type="text" name="ajax-name" value="Your name" />
    <input id="mail" type="text" name="ajax-mail" value="Your e-mail" />
    <button type="submit" id="done">Send</button>

JS:
$(".feedback #done").click(function() {
    var flag = true;
    if (!$("#name").val()){
        $("#name").addClass('error');
        flag = false;
    }
    if (flag == true)
        $(".feedback").submit();
});

This code doesn't work.
How do I make validation on form, without <form> tag?
Ajax doesn't know about this validation.
Thanks.
Answer: Rather than
if (flag == true)
    $(".feedback").submit();

do
return flag;

You can't submit without the <form>, but you can prevent or allow the click() even to complete.  Here's the complete code:
$(".feedback #done").click(function() {
    var flag = true;
    if (!$("#name").val()){
        $("#name").addClass('error');
        flag = false;
    }

    //return the value of flag instead of working with submit()
    return flag;
});

If a click event returns false, that should prevent the click from going any further.  Your flag variable will be true or false, depending on how the validation works out, so that will determine if the process moves forward or not.
Comment: sorry, I don't understand. Please give more detailed answer.
Answer: an alternative way of getting job done, wrap all the child nodes of .feedback with a <form > tag and then perform .submit() on <form  id="someid">
$(function () {
    $('.feedback').children().wrapAll('<form id="form" />');
    $('.feedback #done').click(function () {
        var flag = true;
        if (!$("#name").val()) {
            $("#name").addClass('error');
            flag = false;
        }
        if (flag) {
            $("#form").submit();
            return false;
        }
    });
});

Answer: @edit so i actually read the question and even though it's old this still seems relevant...
Just extend the submit button with a .change() or .bind() or .on() if using jQuery 1.7. e.preventDefault() might work with the ajax handler? chain the razzle dazzle unbind function, like so:
var some_flag_bool = false;
$('#done').click( function (e) {
  e.preventDefault();
  some_flag_bool = true;
  $(this).unbind('#done').submit();
  //return might be considered optional
  return this.some_flag_bool;
});

or something like this in jQuery 1.7 to try and catch things early:
function validation() { if (!foo) { throw new Error("oh noz!"); }
$('body').on('change', 'input', function() { validation(); });

could $.attr('disabled','disabled') the button when the document is ready and then $.removeAttr('disabled') in a validation method
but if it were me i'd just call validation methods from my ajax handler or use the jQuery.validation plugin.

jquery .submit()


Android 10 connect to specific wifi but no internet connection

Question: I connect to wifi by code below, It can connect successful but no internet connection (android show icon network with x), don't know why.
WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
    .setSsid(ssid)
    .setWpa2Passphrase(password)
    .build();

NetworkRequest networkRequest = new NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .setNetworkSpecifier(wifiNetworkSpecifier)
        .build();

connectivityManager = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);

networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(@NonNull Network network) {
        super.onAvailable(network);
        connectivityManager.bindProcessToNetwork(network);
    }
};
connectivityManager.requestNetwork(networkRequest, networkCallback);

Comment: Its a bit different sorry but its all here: https://stackoverflow.com/questions/63227000/android-10-wifi-connection-cant-reach-gateway?noredirect=1#comment112099948_63227000  `connectivityManager.bindProcessToNetwork(network);`
Comment: In onAvailable set the network on wifi. `network.`. Your compiler will let you choose the function which i forgot the name of.
Comment: Thanks but can you explain more, I still don't know what function need to use.
I searching a lot and found that link may problem come from android 10: https://issuetracker.google.com/issues/138335744.
Still don't know how to workaround it.
Comment: I forgot the name. But if you just type network. in Android Studio you are presented with a lot of functions to choose from. Which one to choose should be clear then. Now does AS act as i said?
Comment: Here the list function of Network: https://i.imgur.com/yWvQmD5.png
can you see it, thanks.
Comment: Now I know that wifi connected and only app can access other will be not, the system still show icon wifi no internet connection but it is ok.
For continue connect other wifi need disconnect current wifi first.
Answer: Change your network request
val networkRequest: NetworkRequest = NetworkRequest.Builder()
                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    .setNetworkSpecifier(wifiNetworkSpecifier)
                    .build()

But I got an issue when I called to request to add a network again, networkCallback called in onUnavailable, and nothing to do.


Help in Finding Specific Solutions to Diff. Equations

Question:
Find the general solution for the following differential equation:
  $$f''(t) + f(t) = 3 \sin(2t) + 1, \ f(0) = 3, f′
(0) = 0$$

So, I understand how to find the homogeneous solution to this equation. Given the form $f''(t) + f(t)$, you can deduce that it is in the form of $A\cos(t)+B\sin(t)$. However, I am having difficulty in finding how the specific solution to the $3\sin(2t)$ term comes into play.
I know the answer is $2\cos(t) + 2\sin(t) - \sin(2t) + 1$, but I don't know how to find the specific solution with regard to the initial conditions. Can someone please please help me?
Comment: Hint: undetermined coefficients.
Answer: $$f′′(t) + f(t) = 3 sin(2t) + 1$$
the characteristic polynomial is
$$r^2+1=0 \implies r= \pm i \implies f(t)= c_1\cos(t)+c_2 \sin(t)$$
for the particular solution try
$$y_p= A\sin(2t)+B\cos(2t) \text { or simply } y_p=A\sin(2t)$$
$$f′′(t) + f(t) = 3 sin(2t)$$
$$(A\sin(2t))'' +A\sin(2t) = 3 sin(2t) $$
$$-4A\sin(2t)+A\sin(2t)=3\sin(2t) \implies A=-1$$
$$ \implies  y_p=-\sin(2t)$$
For the constanttry $f_p=C$ so that
$$f′′(t) + f(t) =  1$$
$$(C)'' + C = 1 \implies C=1$$
$$y_p=-\sin(2t)+1$$
Therefore,
$$f(t)= c_1\cos(t)+c_2 \sin(t) -\sin(2t)+1$$
Try to find the coefficients with the conditions you are given..
$$
\begin{cases}
f(0)=3 \\
f'(0)=0
\end{cases}
\implies
\begin{cases}
f(0)=3 \implies f(0)= c_1\cos(0)+c_2 \sin(0) -\sin(0)+1=3 \\
f'(0)=0 \implies f'(0)= -c_1\sin(0)+c_2 \cos(0) -2\cos(0)+1=0
\end{cases}
$$
It's just a linear system that's easy to solve...
Comment: I'm with you until you added the -4Asin(2t)... line. Can you explain your reasoning?
Comment: Differentiate twice $A\sin(2t)$ @ChrisR
Comment: I added some lines @ChrisR


html link get variable address bar php

Question: Have html links including a variable.
Option1
Option2

which goes to next page, and for some reason I am getting always option 1 when I echo the citi variable even when I have clicked option2 and it shows in the address bar. Did I miss something here?
$cit = "";
$citi = "";
// Make sure the _GET cit is set, and sanitize it
if(isset($_GET["o"])){
$cit = preg_replace('#[^a-z0-9]#i', '', $_GET['o']);
} else {
header("location: example.org");
exit();
}

//////////option page routing
if ($cit = "opt1"){$citi = 'Option 1';}
else if ($cit = "opt2"){$citi = 'Option 2';}

Comment: It should be `==` to compare, not `=`.
Comment: See http://stackoverflow.com/questions/14289635/if-statements-not-working
Comment: You're right, I thought I had already tried that. Oops, thanks for saving me time though Barmar, appreciate it
Answer: As @Barmar said it should be comparison not assignment. Like this
$cit = "";
$citi = "";
// Make sure the _GET cit is set, and sanitize it
if(isset($_GET["o"])){
$cit = preg_replace('#[^a-z0-9]#i', '', $_GET['o']);
} else {
header("location: example.org");
exit();
}

//////////option page routing
if ($cit == "opt1"){$citi = 'Option 1';}
else if ($cit == "opt2"){$citi = 'Option 2';}

But I suggest you to use switch since it works faster:
$cit = "";
$citi = "";
// Make sure the _GET cit is set, and sanitize it
if(isset($_GET["o"])){
$cit = preg_replace('#[^a-z0-9]#i', '', $_GET['o']);
} else {
header("location: example.org");
exit();
}

//////////option page routing
switch ($cit) {
    case 'opt1':
        $citi = 'Option 1';
        break;
    case 'opt2':
        $citi = 'Option 2';
        break;
}

Comment: Please don't bother posting answers to questions like this. I think this slows down their automatic deletion.
Comment: `=`  is not "equation", it's assignment :P
Comment: also, consider ternary instead of switch. 8 line of code condensed into one - `$citi =  $cit == "opt1" ? "opt 1" : "opt 2";`
Comment: Thanks Pamblam, just getting back from Christmas vacation and need to get the ball rolling again.
Comment: Thanks @Pamblam for correction.
Comment: It is less code but still slower than switch.
Comment: I think that I'll use switch, I have 500 or more cases though

html link get variable address bar php


Every absolutely continuous function with integrable derivative tends to zero at infinity

Question: I am given $f,f' \in L^1(\mathbb{R})$, and f is absolute continuous, I want to show that:
$$\lim_{|x|\rightarrow \infty} f(x)= 0$$
Not sure how to show this, I know that $f(x)=\int_0^x f'(t) \, dt+f(0)$, and I can assume without loss of generality that $f(0)=0$, any help?
Thanks in advance.
Comment: The standard way is to approach $f$ by compactly-supported functions in $W^{1,1}$.
Answer: Because $f'\in L^1$ you know that $\lim_{x\rightarrow \infty} f(x) $ exists (note $|\int_x^y f'| \le \int_x^y|f'| $ and $\int_x^\infty|f'|\rightarrow 0$ if $x\rightarrow\infty$). Since $f\in L^1$ the limit can only be zero, otherwise $\int|f|$ would not exist.
(Of course the reasoning is the same for $x\rightarrow-\infty$)
Answer: For every $x,s \in \mathbf{R}$ we have
$$
|f(x)| = \left|f(s)+\int_s^x f'(t)dt\right| \le |f(s)|+\int_s^x |f'(t)|dt.
$$
Integrating the above inequality over $x\le s \le x+1$ we get
\begin{eqnarray}
|f(x)|
&\le& \int_{x}^{x+1}|f(s)|ds+\int_{x}^{x+1}(\int_s^x |f'(t)|dt)ds\cr
&\le& \int_{x}^{x+1}|f(s)|ds+\int_{x}^{x+1}(\int_{x}^{x+1}|f'(t)|dt)ds\cr
&=& \int_{x}^{x+1}|f(s)|ds+\int_{x}^{x+1}|f'(t)|dt.
\end{eqnarray}
Thus we have
$$
|f(x)| \le a(x):=\int_{x}^{\infty}|f|+\int_{x}^{\infty}|f'| \ \ \forall  x \in \mathbf{R}.
$$
Since $f, f' \in L^1(\mathbf{R})$ it follows that $a(x) \to 0$ as $x \to \infty$.
Similarly, one shows after integrating over $x-1 \le s \le x$ that
$$
|f(x)| \le b(x):=\int_{-\infty}^x|f|+\int_{-\infty}^x |f'| \ \ \forall  x \in \mathbf{R},
$$
and for the same reason as before we have $b(x) \to 0$ as $x \to -\infty$.
Answer: For each $x_1 < x_2$ we have
$$
f(x_2) - f(x_1) = \int_{x_1}^{x_2}f'(t)dt
$$
Since $f'\in L^1(\mathbb R)$ we can conclude that for $\epsilon > 0$, and $x_1$ great enough,
$$
|f(x_2) - f(x_1)| < \epsilon
$$
Therefore $\lim_{x\to +\infty} f(x)$ exists and since $f\in L^1(\mathbb R)$ it must be $0$.


drupal image field the image doesn't show?

Question: My drupal site has a content type called Published which has a image field.When I migrate the site from Win2003 server to  CentOS , all the Published node's image field doesn't show. It appears like this:

when I click the image name it shows in a now tab.
I had do some google,but no result . someone said the directory sitename/default/files should be set 777
but it is 777.
Any suggestions Thanks in advance.
Answer: Download raw drupal form drupal.org  website, then copy <code>.htaccess</code> file from it to your root directory.
Comment: Can you tell me why . I have do nothing to the .htaccess file.
Answer: You should check if the Public file system path is correct on Drupal. If you go to admin/config/media/file-system and change the file path to the sites/default/files.
Here Recommended Permissions for Drupal Files and Folders

sites/default 750
sites/default/files (including sub folders & files)   755 or 770 *
Comment: sorry it doesn't work. the Public file system path: sites/default/files. And Temporary directory path: /tmp.
and I set all the permission to 777.


We got together with another guitarist. What can we play together?

Question: Recently I met a great guy who also plays guitar. We became friends and decided to get together once in a while to jam. When the time came, we realized that we do not know what to do musically at our sessions.
We are both still learning, our level may be a little above a beginner. We know stuff like chords and scales, but how can we apply it ti dual playing? Where can we find tabs and noted for the two guitars? Maybe there is some set of exercises, that can speed up your learning if you have a jam-buddy?
I play acoustic folk guitar, he plays electric.
Comment: You could try 'Take it Easy' by The Eagles. On accoustic you'd play chords (http://www.chordie.com/chord.pere/www.thudspace.net/tabs/e/eagles/take_it_easy.pro), and electric you'd play the lead (http://tabs.ultimate-guitar.com/e/eagles/take_it_easy_solo_tab.htm).
Comment: Well, he could solo while you play a chord progression. That's the best way to jam with electric and acoustic. You do the rhythm, he does the licks. There's a ton of stuff - be creative!
Comment: Can someone give more advanced answer please??? Like what should I play like second guitar player except solo, and few notes per second as rhythm guitar... But those kind of stuff like we see in any live when two guitarists playing, for example one is playing chords, another one some alternate chords... tell us YOUR practice in band PLEASE
Answer: Since I can't edit answers, I'll post my own, but this builds on what others have written.
When you're at a relatively beginner level (as I am!), you're not gonna be whipping out amazing solos or harmonies. Go for the basics - pick a chord progression (the classic I-IV-V never hurts), and just both strum or pick along to it. Hopefully you can fall into a standard rhythm. As Håvard mentioned, have fun and communicate.
Once you're both playing the same chord progression together and not messing up, have one of the players try a "solo". Don't worry about it being amazing - I can't remember where I heard this advice, but playing on a single string can sound amazing, especially with another person backing you up with the chords. If you know chords and scales, you should be able to play along the scale that matches the chords you're playing, and that's often enough. Don't worry about messing up a note here and there, just keep playing, and when your solo time is done, go back to the chords and let the other person have a go.
After a while, switch up the chords you've chosen.
Lastly, don't be afraid to sing along, even if it's just nonsense, or lyrics from another song, or lyrics about how you can't think of any new lyrics. Some of my greatest laughs while jamming have been over lyrics like "I have no idea what to say next, so I'll just ohhh oh oh ohhhh oh ohhh"!
Comment: The part about both playing complimentary rhythm parts is especially good.  Learning to blend two guitars together is a skill I wish more guitarists had.  Most of the time you just get a guitarist that wants to wail away on a solo, or strum out a big loud rhythm.  Try letting one person take the lead, and have the other work at just filling in the little spaces with complimentary tones.
Answer: You can't go wrong with learning to play 12-bar blues.  Pretty much every guitarist anywhere knows how to play the blues, at least to some degree, so when you meet another guitarist for the first time, you can almost always just sit down and jam.
Both you and your buddy should learn to play both rhythm and solo, and trade back and forth.  You'll both progress quickly if you keep at it.
Answer: I think the best thing you could possibly do; is pick a song which you both like and is within your comfort zone to learn; and play that.
Whether you play this note for note, or make it your own, it will get you playing together, do a couple of these and you will start to get to know each others styles of playing.  Pretty soon you will be jamming 'off the cuff' as it were.
If you want to start doing 'off the cuff' right away; then some standard chord progressions is a good place to start.
Answer: In my view, what makes playing together good has a lot in common with what makes human relations good.
If you're playing for the joy of it, the key that will make it stay fun is to find a common musical ground. Sit down, pick bands and songs that you both like, and get chords/tabs/notes for those songs. Learn the songs, improve by utilizing the strengths of each of you as a guitar player.
If you're playing to learn, a good approach could be to teach each other things one knows better than the other. Also, learn new techniques, songs, etc., and present what you've learned to your partner.
There are a lot of social dynamics involved in playing together, so be sure to communicate well. Praise and critique each other sensitively.
More important than anything, don't forget to have fun!
Answer: Rythm (four quarter note by chord) :
Am Dm E7 Am
Dm Am E7 Am
Solo : Minor pentatonic in A ;D
Answer: Re: The below answer, I didn't notice I had dug up a really old thread, and thought I was looking at an unanswered question. Sorry to raise thread, but i think the below is still a valid suggestion for anyone starting out playing together for the first time. Anyway....
One thing that I ran into when I first started playing with other guitarists was that, depending on experience, the rhythm would usually fall apart, or be uneven, or other mistakes would make attempts to play together fall apart after a few moments. IE: a small hiccup in my playing rhythm would throw off the other inexperienced players and kill the song.
I found that using youtube to search for backing tracks IE: "Blues in A Major", or playing a CD of a backing rhythm while jamming helped in many ways:
1) You can still play rhythm over it, and by playing to a backing track, you will start to improve with keeping time, etc.
2) If the rhythm player makes a mistake or drops out, the backing track keeps the sound filled in, allowing the "lead" player to keep on while the rhythm player finds the groove and hops back in.
3) You can both play lead lines back and forth call and response style. Or share melodic ideas. Harmonize lead lines.
4) Eventually you can turn down the volume on the backing, and then completely get rid of it.
I think doing something like this will make your jam sessions more enjoyable at the beginning, and lead to better playing in the end.
Thanks!
Steve


how to do 3d menu in css 3 with that effect like on page

Question: How to do 3d menu in css3 with effect like on tis page
http://www.nautilusplus.com/
Please help really I cant search any tutorials how to do it...
Answer: You would use rotateX in CSS3 with an offset origin. The subject your looking for is "3D transfoms "
Answer: I found an example called 'css3 flipping cube' (http://cssdeck.com/labs/css3-flipping-cube). This seems to be the effect you're looking for!
Answer: May this could really help you:
Check out :
3d rotate : http://jqueryplugin.net/3d-drop-mega-menu-using-pure-css/
3d flip down when clicked : http://jqueryplugin.net/css3-3d-flip-menu-javascript/


Preventing multiple process instances of a single executable

Question: I am using .NET with C#.
I want to prevent two instances of the same executable to run at the same time, but I don't want to prevent the same process that is run from another folder.
For example, I have an executable that is in two different locations:

C:\MyProject\Master\Program.exe
C:\MyProject\Slave\Program.exe

These are the same .exe files, but in two different locations.
I want to allow one instance of Program.exe that is run from Master folder and one instance from the Slave folder, but no two of any.
I've tried to do this by checking the number of processes that have the same name (Process.GetProcessesByName), but then I can't differ the two.
The closest I have found is to get the Modules from the Process.
The first one in the list is ProcessModule of the exe. But I am not sure if this will always be the first one on the list. Is there any guarantee for that, or is there a better solution to the explained problem?
Comment: I actually voted to close this as duplicate of [this](http://stackoverflow.com/questions/819773/run-single-instance-of-an-application-using-mutex), when I realized to nuance you give. Sorry. However, you could still follow that approach, but encode the complete path-name in the name of the mutex, thus allowing on instance per directory.
Comment: No problem. I don't even know if my explanation is clear enough. :)
Answer: I would use a global mutex instead of relying on the assembly name. Another application may be using the same file name for example.
See e.g. this answer:
Run single instance of an application using Mutex
Answer: One way to do this is, by another service maybe, do something like this:
Process[] processes = Process.GetProcessesByName("Program");

will give you all the active processes of your program.
then you can get the directory from this:
string fullPath = process.MainModule.FileName;

Compare the directories of all instances and if two has the same folder, close one of them.
Comment: Is Modules[0] always the executable process module? Can this be guaranteed?
Comment: you can use also: System.AppDomain.CurrentDomain.FriendlyName

 to have the current exe name
Comment: Just notice that there is a problem regarding 32bit to 64bit consistency


View only content created by that particular user

Question: I want the user to view only the content created by him.
Used "content access module". And change permissions for the user to "Grant own Content Access".
But other users also able to see the content created by other users.
Below is my permissions page:

Not able to find what went wrong.
Please correct me.
If any other module is there please suggest me.
Comment: Rebuild permissions and clear cache.. Make sure you dont have any other content access module's installed... it should work !
Comment: @Anil Sagar: Rebuilded Permissions and cleared the cache when installed the content access module. Its not working.
Answer: Follow below steps to resolve the issue !

Enable Content Access Module
Clear Cache
Go to Edit Content Types, and Select Access Control
Set Access Control As shown below. Remove checkbox view any article content for anonymous and authenticated users.
Save Settings
Go to "admin/reports/status/rebuild" and rebuild permissions
Create a Content of content type that you set access permissions.
Logout and Login as another normal user and check for access.

Let us know if still fails :-)
Comment: My mistake didn't do 3 step in your answer. But now its all working.  Thank you.


Android studio referring to build.gradle from incorrect project

Question: I have three android studio projects:

(path)\LibAddressLookup
(path)\App_A
(path)\App_B

Both App_A and App_B rely on LibAddressLookup and have references to it in their settings/gradle:
include ':app'
include ':LibAddressLookup'
project(':LibAddressLookup').projectDir = new File(settingsDir, '../LibAddressLookup/app')

App_A has about 14 different build flavours, App_B has just the one
When attempting to load App_B into Android Studio, gradle build fails. Looking at my "Build Variants" window, I see that the module "app" has the flavours/build config combinations for App_A. When I go to edit flavours, I see ll the flavours from App_A listed. If I attempt to edit (remove) the flavours I am greeted with an error message saying that the build.grade does not belong to the project, and then lists the location of App_A's build.grade, as pictured:

In the 'Android' view of Android Studio, I see that there are two build.gradle's showing as belonging to "Module" App", as pictured:

When looking at the files, one is indeed the one from App_A, while the other one is the correct one from App_B. I can't find any way to remove this file from the project. Creating fresh copies of the project in new directories leads to the same problem repeating itself. How do I get rid of the incorrect build.grade, and allow myself to continue working on App_B???
Comment: I think you are using same package name in both library and project.
Comment: nope, all three projects have different package names. Even if it were the case, how does Android Studio even KNOW about App_A when loading App_B from a different directory. Even if the package name was the same, it still should work.
Comment: well in some cases android really drive you mad. I had the same issue when I converted a project to a library and used that in another project. Turns out when you create a new project android creates an app folder by default. Now if you add another one it will go by the same name and thus 2 apps will be there to run. I deleted that folder along with all default activities and it worked in my case.
Answer: Ok I've found the solution, but I'm leaving the question open for a while in case anybody can enlighten me as to how this may have happened, so I can prevent it happening again.
In the file (path)\App_B.idea\workspace.xml was the following entry:
<component name="ExternalProjectsData">
    <projectState path="$PROJECT_DIR$/../App_A">
      <ProjectState />
    </projectState>
    <projectState path="$PROJECT_DIR$">
      <ProjectState />
    </projectState>
</component>

After removing the first projectState sub-entry (referring to App_A),  reopening Android Studio, cleaning the project, exiting again, restarting, and cleaning again, Android Studio was finally ready to accept that App_A really did have nothing to do with App_B.
Comment: https://issuetracker.google.com/issues/77944645 should be the same issue as this one.
Comment: Thank you for sharing. It only works at the first time but my AS still auto add "App_A" to "App_B" project after I open "App_A" project and then open "App_B" project. Do you have the same issue? How do you fix it?


How to debug hook_form_BASE_FORM_ID_alter not working?

Question: I am at wits' end. I have a clean install of Drupal 7.28 and a custom module with the following two hooks:

/**
 * Implements hook_form_alter().
 * /
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state, 'form_alter');
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 * /
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state, 'BASE_FORM_ID_alter');
}

And that is all there currently is in the custom module.
I have verified that the the base_form_id for the Article node form is node_form, by printing it out (using dpm($form_state).  This is what is printed:
base_form_id (String, 9 characters ) node_form

And yes, I have cleared the cache (I've even restarted apache and rebooted the server).
I believe my code is identical to what is shown in numerous tutorials about how to use hook_form_BASE_FORM_ID_alter().
Still, when I open the form to create an article, the first hook (hook_form_alter()) fires, and the second (hook_form_BASE_FORM_ID_alter()) does not.
This hook is in 54 functions in the core, so it is very unlikely that it just does not work.
As I said, I am at wits' end.
Has anyone a suggestion for what to try next?
Comment: Strange, I am trying your code and I am receiving output from mymodule_form_node_form_alter().
Comment: Thanks! That at least confirms that it *should* work and that no magic is necessary. There is obviously some quirk somewhere in my site.  Starting again with a *squeaky-clean* install.
Comment: Not sure if relevant but I while copying your code I did received a warning. Warning: Unterminated comment, but perhaps that sneaked in while placing the code in the question.
Comment: FWIW this has never worked for me either, if memory serves I've always had to use `hook_form_alter()` and `strpos` the `$form_id` to target all node forms in one go. Never did look into why, if I get some time I will...
Comment: @undersound, eureka! (and I feel stupid now). Please post this as an answer and you'll get your 25 rep points if you manage to get it typed up before this is closed as PEBKAC.
Comment: Great, glad it works.
Answer: Not sure if relevant but I while copying your code I did received a warning. Warning: Unterminated comment, but perhaps that sneaked in while placing the code in the question.
Answer: These are always fun... First, did you clear your cache?  You always have to clear your cache when adding or changing a hook, and, to be honest, your code looks correct.
Second, to find out the BASE_FORM_ID, to better target a node edit form, you can do this to output all the form ids on the page:
function mymodule_form_alter(&$form, $form_state, $form_id) {
  dsm($form_id);
}

You may discover that the more-targeted $form_id is something like article_node_form.  I have seen it both ways.
Comment: Yup, cleared the cache, restarted apache, rebooted the server. Sorry about leaving that detail out. Your method for getting the `BASE_FORM_ID` is wrong tho'. What your method extracts is the `form_id` (which is `article_node_form` for an article). That is *not* the `base_form_id`.
Comment: Correct, it is the `form_id`, but that works, too.  I just double-checked some of my sites to verify that I remembered it correctly.  We used it when we needed to modify multiple node forms in different ways, so rather than having a big function with a `switch` statement, we targeted the individual forms. The cache clear should have been enough (are you using any exotic caching solutions such as memcached or APC cache?)
Comment: Well, my use case is the opposite, I have around 50 different node forms, and I want to add a field to each of them, so I rather than targeting all 50 individual forms, I want to target all of them with a single hook that (if it had worked) would fire on all of them. That is pretty a common use of `hook_form_BASE_FORM_ID_alter()` if tutorials are anything to go by.


Arquivo de configuração e/ou Constantes, quando usar?

Question: Atualmente uso constantes para guardar dados de configurações em minha aplicação, mas pesquisando vi que é uma "má prática" pela acoplamento que pode gerar, encontrei algumas perguntas aqui mesmo no StackOverflow falando que o melhor a se fazer é colocar todas as configurações num arquivo (.ini, .xml, etc) e criar uma classe para recuperar esses valores.
1 - Um dos "problemas" que encontrei é quando preciso usar esses valores em views/html.
Por exemplo, no carregamento de css/js, atualmente faço assim:
<link rel="..." href="<?=APPURL?>/public/css/...">

nesse caso o uso de constantes é correto? até porque essa constante "APPURL" é gerada fora do arquivo de configuração, dentro de outra classe que gera a url amigável de forma dinâmica.
O que construí para substituir o uso de constantes foi o seguinte:
// interface para forçar implementações de qualquer configuração que eu faça

interface ConfigHandler {

    function setConfigFile($file);

    function getConfigFile($file);

    function getConfigFileContent($file);

    function get();
}

.
// classe que recupera as configurações de um json

class jsonConfig implements ConfigHandler {

    private static $configFile = 'config.json';

    static function setConfigFile ($configFile) {

        if(isset($configFile) && is_readable($configFile))
            self::$configFile = $configFile;
        else
            throw new Exception("Arquivo '$configFile' nao encontrado");
    }

    static function getConfigFileContent () {
        return file_get_contents(self::$configFile);
    }

    static function getConfigFile () {
        return self::$configFile;
    }

    static function get($param = null) {

        $configs = json_decode(self::getConfigFileContent(), true);

        if($param)
            return $configs[$param];

        return $configs;
    }
}

.
 // caso eu precise mudar pra um arquivo xml

    class xmlConfig implements configHandler {...}

Exemplo de uso:
$host = jsonConfig::get('dbhost');
$user = jsonConfig::get('dbuser');
$pass = jsonConfig::get('dbpass');

$PDO = new PDO(...);

2 - Nesse caso das classes de configuração, definir uma constante fora da aplicação com o nome do arquivo a ser lido também é correto? caso contrário se eu quisesse mudar o arquivo somente editando a classe?
Answer: Eu não costumo usar esse tipo de constante define( 'FOO' , 'foo' ) justamente por usar uma classe para trabalhar com arquivos de configuração.
No máximo eu uso constantes em classes pois em nada interferem a parte da aplicação.
Nos arquivos de configuração eu defino tudo e tudo fica numa única pasta sem precisar 'garimpar' arquivos na hora de alterar algo que venha precisar - tipo senha de BD, diretório...
Sobre a sua dúvida de <?=APPURL?>, a questão não é certo ou errado, mas o que é mais prático. Como citei, trabalho com vários arquivos de configuração, e você pode ter um arquivo único com todas as constantes necessárias tornando fácil a manutenção.
O seu exemplo de uso do config DB está correto, e eu também estenderia seu uso para a parte da view e mudaria o valor para o caminho completo do diretório:
css => xxx/public/css/, js => xxx/public/js/... Vejo que dessa forma é mais fácil aplicar e fazer manutenção deixando o mínimo possível na view.
Em suma, vai de caso a caso.


Prove that if $A$ is a set with infinite cardinality, then there exists a bijection between $A$ and $A^2$.

Question:
Prove that if $A$ is a set with infinite cardinality, then there exists a bijection between $A$ and $A^2$.

I know that there exists a bijection between $\Bbb{R}$ and $\Bbb{R^2}$, but I don't think that technique can be generalized.
I think the proof of this may be highly non-trivial. Any help would be great.
Comment: What size of cardinality? You can certainly generalize for countably infinite sets.
Comment: @graydad- Yes. Uncountable sets is the major concern then.
Comment: You could try well ordering the set and generalizing the countable bijection.
Comment: Can you always well order an arbitrary set?
Comment: @MattSamuel- Can this be done assuming Axiom of Choice?
Comment: This is *equivalent* to the axiom of choice. Incidentally, this question has been asked about a zillion times before, and will be closed as a duplicate in a few minutes.
Comment: [This](http://math.stackexchange.com/questions/608538/godels-pairing-function-and-proving-c-cc-for-aleph-cardinals), including links, shows how to do it - without the axiom of choice - for ordinals.
Answer: The only way I can think of proving this for uncountable sets is invoking the Cantor-Schroder-Bernstein theorem. http://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Bernstein_theorem
You can easily find an injective function $f: A \to A\times A$ defined by something like $f(a) = (a,a)$. If you can in turn find an injection $g:A\times A \to A$ then you'll know the two sets have the same cardinality. I imagine finding $g$ will be difficult.
Comment: This is equivalent to the axiom of choice. Of course that coming up with an injection back is "difficult". This is not quite an answer to the question (even if it were easy to find such injection).


Displaying parts of main menu in separate blocks

Question: I need to display my main menu in separate blocks: the first sub-menu in one block, and the following two sub-menus in another block. I'm using Drupal's native menu module and also the nice menus module.
How can I do that?
Answer: Consider using menu_block and defining 2 blocks with the depths you desire within the main-menu for each block; and then place them in the drupal Regions you want. The menu_blocks I believe will play nicely with Nice Menus if you have "expand all child elements" of this menu option checked.


Can any at most countable metric space be embedded topologically in $\mathbb{Q}$?

Question:
Theorem. (Sierpiński) Any countable metric space without isolated points is homeomorphic to $\mathbb{Q}$.

Let $\mathbb{N} = \{1, 2, ...\}$, $\mathbb{Q}_- = \{r\in \mathbb{Q}: r<0\}$.
If $X$ has a finite number of isolated points then we should be able to embed it in $\mathbb{Q}_-\cup \mathbb{N}$ by placing the isolated points in $\mathbb{N}$, and using Sierpiński's theorem to create a homeomorphism of limit points of $X$ and $\mathbb{Q}_-$.
Similarly if $X$ has a finite number of limit points, then it should be homeomorphic to a finite disjoint union consisting of copies of $\{0\}\cup\{1/n : n\in\mathbb{N}\}$. But then we can easily embed each copy of $\{0\}\cup\{1/n : n\in\mathbb{N}\}$ in $[2m, 2m+1]\cap \mathbb{Q}$ for $m\in\mathbb{N}$.
What happens in the general case?
Comment: Are you asking for a metric or topological embedding?
Comment: Topological one
Answer: I use "countable" to mean "finite or countably infinite".

Theorem. (Sierpiński) Any nonempty countable metric space without isolated points is homeomorphic to $\mathbb{Q}$.

Corollary. Any countable metric space is homeomorphic to a closed subspace of $\mathbb Q$.
Proof. If $X$ is a nonempty countable metric space, then $X$ is homeomorphic to a closed subspace of $X\times\mathbb Q$, and $X\times\mathbb Q$ is homeomorphic to $\mathbb Q$ by Sierpiński's theorem.


Mean value theorem related question

Question: Let $f:[a,b]\to\mathbb{R}$ be a differentiable function such that $f(a)=a$ and $f(b)=b$. Prove that there exists a $c\in(a,b)$ such that $f'(c)=1$ and that for every $n\in\mathbb{N}$ there exist different $c_1,c_2,\ldots,c_n$ such that $f'(c_1)+f'(c_2)+\ldots+f'(c_n)=n$.
First part is direct from Mean value theorem.
Could you give me any hints for second part?
Answer: This is only a hint. Divide the interval $(a,b)$ into $n$ equal intervals. The average of average slope of these $n$ intervals must equal the average slope of the interval $(a,b)$.
Answer: Let $a = x_0 < x_1 < \cdots < x_{n-1} < x_n = b$
where $x_i := a + \frac{i}{n}(b-a)$.
For each $i \ge 1$ there exist $c_i$ such that $f'(c_i) = \frac{f(x_i)-f(x_{i-1})}{x_i-x_{i-1}}$. Then $$\sum_{i=1}^n f'(c_i)
= \sum_{i=1}^n \frac{f(x_i) - f(x_{i-1})}{x_i - x_{i-1}}
= \frac{1}{(b-a)/n} \sum_{i=1}^n (f(x_i) - f(x_{i-1}))
= n.$$

Mean value theorem related question


Where to programmatically enable a Feature module

Question: I created a Drupal 7 feature and usually I would enable it with Drush, but someone suggested that I enable it with an update hook (which I assume means it gets enabled on updb or update.php).
I saw this discussion on enabling modules programmatically How do I programmatically install and enable a module?, but it blithely skips over where to write the code. Does it go somewhere in the installation profile? Does it have to be called from another custom module that is already enabled?
I'm actually an experienced Drupaler that has somehow managed to miss this one crucial lesson, I've just been using Drush to enable modules but I want to do this the best way.
Comment: @PatrickMan – Yepp, I'd scan the custom profile's or sites/all/modules/custom or sites/all/modules/features directory for `module_enable`, just this string. Than you should find it.
Comment: @PatrickMan – Yes, to have code inside a `hook_update_N` triggered, it needs to be placed in an enabled module.
Comment: This has been very helpful.  So if there are other features on the site that have been enabled with update hooks (by other developers), where am I likely to find those update hooks.  In a non-feature custom module?  In the installation profile?  Thanks!
Answer: A feature module is just another module. And you can enable it programmatically using the linked code from another enabled module's hook_update_N placed in this another enabled module's *.install file. This even can be another feature module. Then have this hook fired via drush updb on the command line or by visiting your site's /update.php.
You also could do that from a form submit handler. Or even from a menu callback providing some custom endpoint you can access with cURL for example.
It's safe to use other feature modules' *.install files. Since Features never touches *.module and *.install files during regeneration. So you are free to use them to your needs.


What are all the factor groups of $D_{4}$ up to isomorphism?

Question: I know $D_{4}$ has $5$ subgroups and I've figured out the normal subgroups but I'm having trouble figuring out how the factor groups are isomorphic to $\mathbb{Z}_{4}$ and $\mathbb{Z}_{2} \times \mathbb{Z}_{2}$ and $\mathbb{Z}_{2}$.
Answer: You should know that the groups of order $4$ up to isomorphism are $C_4,C_2\times C_2$. In particular a group of order $4$ with no element of order $4$ is $C_2\times C_2$. $D_4$ is a group of order $8$, in particular a $2$-group. Any factor group has size $1,2,4,8$. In particular, we're interested in the groups of order $2,4$. For $2$, the factor group is always isomorphic to $C_2$.  $Z(D_8)=\{1,r^2\}$ is normal, and $D_8/Z(D_8)$ thus has order $4$. This has the effect of making $r$ have order $2$, so the quotient is isomorphic to $C_2\times C_2$. It remains to see if there is a quotient isomorphic to $C_4$. I claim this is not the case. Can you prove it? Hint Look at the lattice of $D_8$.
Comment: So non of the quotient groups are isomorphic to Z4?
Comment: @JessyWhite No. The lattice of $C_4$ is a chain of length $3$, which you cannot produce from the lattice of $D_8$ by "cutting below" any subgroup.
Comment: Thank you. Can I ask you another quick question? Please?
Comment: @JessyWhite You can always use the "ASK QUESTION" button without asking.
Comment: I know, I asked the question before but i didn't understand part of the solution so I don't want to get voted down for asking the question again
Comment: @jessywhite Ok.


powershell -and operator with Test-Path syntax error

Question: In the code below I can use the -and operator to make a compound if statement, but when using Test-Path with -and there is a syntax error.
What is the proper way to use -and with a command like Test-Path?
$a = 1
$b = 1
$c = 1
if ($a -eq $b -and $a -eq $c ) {
    write-host "Variables are equal."
}
$path1 = "C:\Windows"
$path2 = "C:\Users"
if (Test-Path $path1 -and Test-Path $path2) {
    write-host "paths exist."
}

Answer: If you put brackets around your usages of Test-Path then it works, i.e.
$path1 = "C:\Windows"
$path2 = "C:\Users"
if ((Test-Path $path1) -and (Test-Path $path2)) {
    write-host "paths exist."
}

Comment: @AustinFrench: Yes: Commonwealth countries (the UK and former colonies) use the term "brackets" for `(` and `)`, whereas US English refers to these characters as "parentheses" (singular: "parenthesis").
Comment: Is it a regional thing to call parenthesis brackets?
Comment: @AustinFrench more a case of having to type 9 chars instead of 11 ;) Although it would be better again to call them braces; only 6 chars.
Answer:
DeanOC's helpful answer provides an effective solution.
As for why the parentheses (brackets) are needed:
PowerShell has two fundamental parsing modes:

argument mode, which works like traditional shells
expression mode, which works like traditional programming languages.

Running Get-help about_Parsing provides an introduction to these modes.

Test-Path $path1 and Test-Path $path2 in isolation are parsed in argument mode.
Operator -and can only be used in expression mode.
In order to use the output of the argument-mode Test-Path commands in expression mode, they must be enclosed in (...):

Use of (...) forces a new parsing context, and
the 1st token of a given parsing context determines whether it is parsed in argument or expression mode.

Another thing to consider is PowerShell's pervasive support for collections, which often allows you to operate at a higher level of abstraction:
$paths = "C:\Windows", "C:\Users" # define *array* of input paths
if ((Test-Path $paths) -notcontains $False) { # See if ALL paths exist.
  "ALL paths exist."
}

Test-Path accepts an array of paths to test, and outputs a corresponding array of Booleans indicating the respective existence.
Operator -notcontains tests non-membership in the LHS array; in other words: if no Boolean returned by Test-Path is $False, the implication is that all input paths exist.
Note that Write-Host was deliberately omitted, because in order to send something to PowerShell's success stream (the analog to stdout in traditional shells), you don't need an explicit output command at all, and, conversely, Write-Host actually bypasses the success stream - see this blog post.


Padrão de nomenclatura no código para o C#

Question: Reconheço que é comum que cada linguagem utilize um padrão para compor seus identificadores (variáveis, constantes, objetos, controles etc).
No caso do C#, quais seriam as boas práticas com relação à maiúsculas/minúsculas, tamanho e utilização de caracteres especiais?
Answer:
Adote o mesmo padrão de maiúsculas do .NET segundo a tabela abaixo. Quando usar acrônimos, prefira manter só a primeira letra em maiúscula para facilitar a leitura. O membro ser estático, constante ou somente leitura não afeta o padrão. Há controvérsias se campos protegidos realmente devem ser camelCase ou é melhor com PascalCase. Depende se você está considerando ele mais próximo de ser privado ou mais próximo de ser público.

PascalCase
camelCase

Classes
Variáveis locais

Assembly
Parâmetros de métodos

Classes
Campos privados e protegidos

Structs

Intefaces (sempre com o I antes do nomes)

Delegates

Enums

Métodos

Propriedades

Campos públicos

Eventos

Recomendações gerais de escrita

Tente usar uma forma mais fluente para dar entendimento ao que se pretende mas não exagere. Procure usar uma linguagem que seja adequada ao domínio que está sendo desenvolvido para aquela tarefa específica.
Raramente um número deve fazer parte de um nome de qualquer identificador. Se usar ele deve ter algum significado. Ex.: Norma452.
Evite nomes que podem ser confundidos com alguma outra coisa. Ex.: b001.
Procure manter nomes semelhantes para coisas semelhantes.
Nomes devem ser fáceis de serem localizados com ferramentas de busca em código. Você deve achar facilmente o que está querendo, preferencialmente nada mais e nada menos do que o desejado. Tenha isto em mente.
Decida se vai usar acentuação em identificadores ou não e mantenha o padrão, se aceitar acentos, todo mundo tem que respeitar a acentuação correta, não pode ficar escolhendo momentos para não acentuar.
DoThis() pode ser ótimo como exemplo generalizado mas não tem nenhum significado para o código. O mais importante é dar nomes significativos. Principalmente não dê nomes que signifiquem outra coisa, mesmo que eventualmente. Ex.: string nonBlank = " ";
Procure entender as sutilezas dos nomes. Counter é um contador, Count é uma contagem e TotalCount é o totalizador da contagem. Seja o mais específico possível. SalveNome() é melhor que SalveCampo() a não ser que o segundo salve qualquer campo a ser especificado.
Evite abreviações a não ser que faça sentido para todos e não crie ambiguidades. A abreviação pode ser tão conhecida que ela pode ser até melhor. Ex.: Ftp, UI, IO, DB, PK, AlgumaCoisaInfo, Config, ValorIcms, Id, Args, ex (para o que só pode ser exceção), i para loops (i tem um significado óbvio para qualquer programador), temp ou mesmo tmp (mas não use ambas). Em variáveis locais a abreviação não é tão problemática se não criar mnemônicos incompreensíveis. O melhor é evitá-las, mas não precisa exagerar. Passa ser problema se tudo estiver abreviado ou não dê para entender a intenção da variável por qualquer programador com o mínimo de experiência. Não me pergunte porque é melhor PascalCase em Ftp mas ALLCAPS em UI, IO, etc. Eu imagino que seja o fato de ter apenas duas letras no acrônimo. Já Id é uma só palavra. Há quem prefira ID. Eu não, mas mantenho um padrão.
Não use underscore (sublinhado) em nomes de identificadores a não ser que tenha um motivo muito forte, talvez para evitar conflitos possíveis em código lidando com situações em mais baixo nível (geradores). Especialmente não use o prefixo m_. O sublinhado pode ser usado para um parâmetro irrelevante em uma lambda. Ex.: (_, __) => FazAlgo(); quando você sabe que precisa receber dois argumentos mas eles não serão usados na sua execução.
Já ficou claro que notação húngara não deve ser usada. Um identificador deve indicar o significado dele naquele contexto e não alguma característica técnica dele. No entanto você dizer que está usando um TextBox com descrição não é notação húngara, é importante para entender o que é aquele identificador. Já um método GetInt() pode ser já que não está dizendo o que está pegando e sim o tipo do que está pegando, a intenção é esta, não é uma simples característica. carArray provavelmente é húngara, prefira carros.
Evite palavras reservadas usualmente presentes em outras linguagens que funcionam em cima da CLR.
Se o tipo fizer sentido em um nome de identificador (tipicamente um método), prefira o nome do tipo conhecido pela CLR e não o nome definido no C#, assim o identificador pode ser facilmente usado em outros linguagens. Até poderia evitar isto em identificadores privados ou que é absolutamente certo que nunca será usado em outra linguagem, mas por coerência, é melhor não criar exceções. Isto vale para nomear identificadores, não para usar declaração de tipo.
Procure alguns termos comuns fáceis e padronize seu uso quando realmente não dá para identificar o significado do identificador ou ele não é relevante. Use value ou valor, item, etc.
Tente achar a semântica correta do que está tentando fazer e principalmente manter uma relação correta entre termos que se complementam. Por exemplo: Begin vem antes de um End, não confundir como um Start que vem antes de um Stop e um Initiate antes de Finish, um Open antes de Close, Lock antes de Unlock, Block e Deblock, Head e Tail, Header e Footer, Before e After, Read e Write, Input e Output, First e Last, Previous e Next, Increment e Decrement, Enter e Leave, Add e Remove, Create e Destroy, Insert e Delete, Show e Hide,  Suspend e Resume, Top e Bottom, etc. Outros são mais complicados de afirmar ou depende de contexto. Do casa com Cancel? E Go tem relação com Quit? Ou o inverso entre os termos anteriores? E que tal o uso Run, Execute, Perform, Abort?. É bom aprender antes de usar. Entenda a diferença entre Find, Seek, Search, Lookup, Scan, Traverse, Locate, Select, Query, Pick, Trace, GetAbcXxx e assemelhados e suas traduções. Não se atenha a estas palavras, são apenas exemplos de conceitos parecidos que podem ser definidos mais precisamente com a palavra correta. Calcule é diferente de Pegue que é diferente de Leia. Uma propriedade TemPedidos é muito diferente de um método VerifiqueExistênciaDePedidos(). Entenda a diferença entre Increment, Add, Plus e Accumulate. Escolha nomes que identifiquem se haverá efeito colateral, mutação do objeto ou não.
Evite nomes que cause duplo negativo quando usa um operador de not. Ex.: !family.hasNoChildren. Seja afirmativo.
Se está difícil dar um nome à um tipo ou método provavelmente ele faz mais do que deveria ou não está claro o que ele faz ou porque existe. Se precisa usar um And ou E tem chance de algo estar errado.
Não costuma haver problemas em usar uma variável ou propriedade com o mesmo nome do tipo como camelCase (Color color = Color.Red;). Isto só deve ser evitado se o nome da variável não indica bem o que ela está fazendo ali. O significado contextual pode ser perdido quando se adota este padrão (talvez melhor Color statusColor = Color.Red;).
Identificadores de tipos booleanos podem, ou mesmo devem, ter prefixos indicando uma capacidade. Ex.: is, can, has, isThere (alguns preferem usar só o has), allow (que pode ser o mesmo que can). Ou em português é ou eh, está ou estah (costuma ser seguido de um verbo no particípio ou adjetivo), pode (normalmente seguido de um verbo no infinitivo), tem (provavelmente seguido de um substantivo), Existe (seguido de substantivo). O plural pode ser usado, ou outra conjugação, ex.: foiTentado. E lembre-se que uma enumeração costuma dar mais semântica que um booleano, mesmo quando só existe dois estados. A semântica do booleano é apenas dizer se é verdadeiro ou falso, não use para outras coisas que possuem apenas dois estados.

Variáveis

Variáveis que guardam coleções podem estar no plural. Isto é válido na maioria dos casos mas há situações que pode não ser o ideal. Há quem use coletivo nestes casos.
Em eventos é comum usar o sufixo EventArgs para o parâmetro que vai receber os argumentos do evento. Isto deixa claro a intenção deste parâmetro. Provavelmente este parâmetro será um tipo subclasse do tipo EventArgs.
Variáveis podem ter várias formas conforme o contexto mas o mais comum é que sejam substantivos.

Tipos

Classes, estruturas e enumerações devem ser substantivos mesmo que adjetivados ou compostos. Interfaces podem ser substantivos ou adjetivos indicando uma capacidade, sendo comum terminar em able ou ável. Em alguns projetos classes abstratas costumam levar o sufixo Base. Tenho minhas dúvidas se isto é consistente, até onde sei não é recomendado pela Microsoft. Usar o nome da classe base como parte do nome da nova classe derivada costuma ser uma boa opção mas é preciso cuidado para não haver exageros e ter nomes longos demais que acabam não identificando bem o que é a classe.
Classes estáticas com métodos de extensão devem ter o sufixo Extension. Há quem ache que Ext é suficiente. Em alguns casos uma classe estática normal pode ter o sufixo Utility ou Helper mas estas classes devem ser evitadas. Se ela tiver alguma função bem definida o sufixo é desnecessário. Se espelhe na Math e Console.
Enumerações devem usar o singular a não ser nos raros casos que faça muito mais sentido estar no plural que é o caso do uso como [Flags]. E não use um prefixo ou sufixo Enum no nome. Redundâncias deste tipo em outras coisas, principalmente em nomes de colunas em banco de dados é um dos maiores abusos que vejo em nomenclatura.
Exceções devem ter o sufixo Exception para evitar confusões. Desta forma deixa claro para o que deve ser usado.
Atributos devem terminar com Attribute na sua definição. O próprio compilador sabe que o uso dos atributos não usam o sufixo, ou seja, ele sabe inequivocamente que aquilo é um atributo e que o nome original precisa de um sufixo. Não colocar o sufixo na declaração pode trazer problemas, assim como colocar no uso.
Há quem diga que tipos delegados devem ter o sufixo Delegate. Há quem ache desnecessário. A Microsoft costuma usar o sufixo mas parece ser "tão necessário" quanto o sufixo Enum em uma enumeração. Prefira usar uma lambda e não se preocupe com isto :).
Prefira usar letras únicas maiúsculas para identificar os slots de tipos genéricos (T, U, K, V). Se tiver um bom motivo pode usar palavras mais significativas mas não use nomes que podem ser confundidos com tipos existentes (você nunca sabe quando vai gerar confusão), especialmente não use Type para evitar confusão com o tipo Type. Se for usar um nome mais descritivo utilize o prefixo T. Ex.: TKey e TValue.

Membros de tipos

Métodos costumam ser verbos, principalmente no imperativo, muitas vezes seguidos do substantivo a que se referem. Um método é uma ação que você está mandando o computador fazer. Delegados não costumam diferir de métodos comuns. Mas estas regras podem variar para dar uma leitura mais fluente para o que se deseja. Só não tente fazer que todo o código se pareça com o inglês fluente, ou pior, com o português, porque isto não é possível sem tornar o código ainda mais confuso. O método pode indicar em seu nome o que eles estão retornando (mas em geral, não seu tipo), especialmente os que começam com Get ou Pegue ou Compute, etc. Há quem use PegarXXX() ou CalcularXXX que aparentemente seria o infinitivo. Não sei se isto é um erro por desconhecimento ou há algum motivo para a escolha consciente. Acredito mais no primeiro.
O sufixo Async deve sempre ser usado em métodos que possuem esta característica. É importante identificar um método com uma característica tão especial e ajuda distinguir da versão síncrona.
Eventos são verbos no gerúndio (pré-evento) ou particípio passado (pós-evento) conforme a situação. Evite criar eventos com sufixo Before ou After ou nomes parecidos. Se o evento deve executar a ação o nome deve ser no infinitivo. Ex.: Deleting, Deleted e Delete. Os manipuladores de eventos devem ter o prefixo on. Há controvérsias se deveria existir a forma aportuguesada para on.
Propriedades e campos públicos tendem a ser usados como adjetivos. Se usar como verbo, pode ter algo errado.
Membros de enumerações podem assumir várias formas, substantivos, adjetivos, verbos em alguma conjugação.
Evite colocar os chamados "membros sentinela" que são membros artificiais de enumerações que ajudam manipulá-las. Coloque apenas membros naturais ao domínio. Ex.: NotSelected.
Evite qualquer redundância a não ser que ela sirva para evitar ambiguidade. Prefira Line.GetLength() à Line.GetLineLength().

Arquivo, Assembly e Namespace

Use uma classe por arquivo e nomeie o arquivo com o mesmo nome da classe.
Prefira usar nomes totalmente qualificados (incluindo o namespace) em exemplos pequenos ou arquivos curtos onde apenas um membro de um namespace é usado. E prefira usar a diretiva using sempre que for usar vários membros de um namespace em arquivos maiores (maioria dos casos).
Não nomeie namespaces com um domínio de internet (talvez o pior caso de super-engenharia que já vi). Você pode usar o nome da empresa e depois o nome do produto ou tecnologia em um subgrupo mas não tente tornar o nome único abusando dos subgrupos. Se realmente o nome da empresa responsável pelo namespace for muito comum, utilize uma variação que deixe único. O ponto deve ser usado para separar agrupamentos que façam sentido e não para separar palavras. Prefira ServiceModel à Service.Model.
Namespaces não devem ter o mesmo nome de tipos membros dele. Se isto for necessário, tente fazer alguma alteração como colocar o namespace no plural. Lembre-se que é possível ter alguma redundância em namespaces já que eles não aparecem obrigatoriamente no uso de seus membros. Então ter uma classe XmlDocument dentro do NS Xml não é um exagero redundante.
Evite criar membros poluindo namespaces que você não criou (de terceiros). O melhor motivo para não seguir esta recomendação é a criação de métodos de extensão, mas não abuse disto.
Sempre que possível o nome de um assembly deve seguir o nome do namespace. Organizar um namespace (pelo menos a parte principal dele) por assembly é uma boa organização mas não precisa ser seguida cegamente.

Miscelânea

Em uma API mais moderna use o mesmo nome da antiga com um sufixo indicando que é a versão nova, se possível indicando a novidade. Isto facilita achar ambas. Ou prefira um nome nome que seja mais significativo quando o nome anterior não havia sido bem escolhido. Ex.: AlgumaCoisaAsync, FazAlgoEx.
Quando realmente não for possível dar um bom nome para um identificador use um comentário próximo da declaração para ajudar dar melhor entendimento. Mas isto deve ser raro.
Não relacionado com o nome mas com a legibilidade: declare as variáveis o mais perto possível de onde ela vai ser usada, não existe mais necessidade ou vantagem em declarar tudo no começo do código. Os membros sim, podem ser declarados organizados pela sua função no tipo.
Se o desenvolvimento for internacional tudo deve estar em inglês. Se for certo que nunca sairá do domínio do seu país, pode usar a sua língua onde o domínio está na sua língua. Deixe em inglês as coisas mais técnicas, o domínio mais ligado ao mecanismo.
Quando diretrizes conflitam você tem que escolher uma, óbvio. Eu prefiro escolher a que me parece causar menos problemas ou pelo menos que me agrada mais. Isto costuma bater com o que a linguagem/framework prefere. Ex.: CA1500 vem do compilador. SA1309 vem de uma ferramenta externa. Eu prefiro a primeira. Porque me parece mais limpo e não causa nenhum problema.
Evite trazer para o C# convenções excelentes (ou nem tanto) de outras linguagens. Eu já identifico que um programador é preguiçoso ou não sabe programar em C# quando ele coloca constantes como ALL CAPS. Isto era útil em C porque era a única forma de indicar, pelo menos para o programador, que um identificador era uma constante. Depois isso deixou de ser importante mas as pessoas continuaram fazê-lo (leia sobre a experiência com macacos, aqui no SOpt acontece muito isto, só não pode achar que fazer o que sempre foi feito está errado por definição, o problema é não saber porque). Levaram isto para outras novas linguagens por influência de seus autores ou por vontade própria. Este exemplo é uma variação de notação húngara. Você usa uma convenção para demonstrar algo que não precisa ser demonstrado e pior, que pode ser alterado no futuro, mesmo que não devesse.

A maioria destas recomendações foram definidas pelos criadores da linguagem/framework para facilitar e padronizar o entendimento do código por todos. O mais importante é manter uma consistência entre uma equipe. Porém se você pensar que seu código pode acabar sendo compartilhado com pessoas que você ainda não conhece (aqui por exemplo) é melhor tentar seguir padrões universais.
É claro que algumas convenções ajudam mais que outras e o que mais ajuda é manter clareza do que está tentando indicar ali. Isto só costuma ser fácil fazer quando você domina totalmente o problema. Nomear alguma coisa eventualmente já é difícil, imagina nomear milhares de coisas que você não domina em alguns dias de trabalho.
Estas convenções facilitam a leitura e manutenção do projeto. Indiretamente pensar sobre isto ajuda entender o que você está fazendo. Mas procure entender as motivações para a recomendação, isto pode lhe ajudar mais, pode ajudar seu código ser melhor escrito além da nomenclatura.
Obviamente não fiz uma lista completa de convenções e muito menos expliquei cada uma.
A resposta do AP já deu boas indicações do que se deve fazer para tentar atingir um resultado melhor, tentei me ater a alguns guidelines que encontrei e que sigo ou que você poderia seguir.
Discordo um pouco de tomar cuidado com nomes que podem impactar tráfego de dados. Isto não deveria ser uma preocupação. Se for importante (normalmente não é) é melhor criar uma maneira pós-código de reduzir do tamanho. A questão do underline não é a recomendação oficial mas claro que em convenções não existe o certo e errado, só estou ressaltando isto. Linguagem ubíqua pode ser uma boa se não entenderem errado o que é isto, que não exagere. Normalmente é difícil achar consenso universal do que é mais ubíquo. Sinceramente não sei se é melhor nomeTextBox ou textBoxNome (isto é um TextBox do Nome ou é um Nome encapsulado em um TextBox?), então escolho um e mantenho a consistência.
Como já foi dito você pode usar ferramentas para ajudar a forçar estes padrões, mas só uma pequena parte é possível. Pode dar uma olhada nas regras já existentes no StyleCop e poderá criar suas próprias.
Lembre-se sempre que se houver um bom motivo, não siga a recomendação. Saiba que algumas deslizadas serão punidas de forma mais intensa que outras. E o principal, nenhuma convenção é obrigatória. Não gosta? Acha que é problemático? Existe um bom motivo para não seguir em determinado momento? Use outra forma. Convenções e guias são como boas práticas, só são bons quando você sabe quando não seguir.
StyleCop evolui.
Guia de estilo do próprio .NET.
No SO tem muitas respostas sobre o assunto de forma individualizada.
Escrevo mais sobre o assunto nessa resposta.
Posso ter errado em alguma coisa, comente.
Coloquei no GitHub para referência futura.
Comment: @ViníciusLima você pode usar, mas não é o padrão adota, não há vantagem nisto se adotar os outros padrões. Quem o faz não segue o padrão, inclusive o Visual Studio. Tem coisas ruins nele e na documentação.
Comment: Resposta excelente!! Deveria estar como a aceita.
Comment: "Tente usar uma forma mais fluente para dar entendimento ao que se pretende mas não exagere. Procure usar uma linguagem que seja adequada ao domínio que está sendo desenvolvido para aquela tarefa específica." - Acho isso primordial, acredito que é o que mais pode facilitar o entendimento do código.
Comment: Sabe me dizer se é preferível utilizar `_` (underline) no início de um campo privado? Fico muito confuso, vejo códigos com ele, outros não. O VS também me confunde, quando ele cria os campos privados e atribui o valor a partir dos parâmetros do construtor, ele não utiliza o `_`, porém quando é pra **converter em uma propriedade completa**, acho que é assim que está lá, ele utiliza =/
Answer: De um modo geral, para o C#, o padrão camel case é amplamente utilizado. Resumindo, nesse padrão, os nomes são compostos simplesmente unindo-os sem qualquer tipo de separador, como o sublinhado (_). O que ajuda a diferenciar as palavras é o FatoDeCadaUmaIniciarComMaiúscula. Além disso, escolher bem o nome do elemento pode contribuir - e muito - para o entendimento de seu código pela equipe (e por você mesmo, na hora de voltar depois de uns meses para uma eventual manutenção). Abaixo algumas considerações que podem facilitar na hora de escolher o nome de seus identificadores:
Seja claro!
Em primeiro lugar, escolha um nome que dê sentido àquele elemento. Leia novamente o código, como se fosse um texto em português e tente avaliar se a frase que acabou de ler faz sentido, ou seja, se é coerente e não induz o leitor à qualquer tipo de ambiguidade. Se você não lembra pra que serve uma variável (x é um péssimo nome), é provável que tenha escolhido o nome errado.
Abreviações
Geralmente, siglas e abreviações tendem a atrapalhar o entendimento do código, a menos que sejam amplamente utilizadas por todos na equipe e na empresa. Um padrão cada vez mais em desuso, a notação húngara, prevê o uso de abreviações para a nomeação de controles e até hoje muita gente a usa para dar nomes a elementos do banco de dados. Assim, uma caixa de texto poderia se chamar txtNome. Ao optar por uma linguagem mais eloquente, a abreviação seria substituída por textBoxNome.
Linguagem ubíqua
Por influência de Eric Evans, em seu livro Domain Driven Design, há uma tendência em atribuir nomes que expressem antes o negócio e depois a tecnologia. Pra um desenvolvedor isso representa um desafio, pois nos expressamos a maior parte do tempo usando uma linguagem essencialmente técnica e cheia de termos próprios. Focando no negócio, o controle txtNome passaria a ser chamado nomeTextBox, por exempo. Linguagem ubíqua é considerada aquela que todos os envolvidos falam, que está presente no vocabulário cotidiano da organização e facilita o entendimento de um conceito por todos.
Maiúsculas e minúsculas
No padrão CamelCase é comum que haja distinção para a primeira inicial:

para Classes, é em maiúscula: SituacaoVenda. Para Constantes e Enumeradores também.
para objetos, controles e variáveis, em minúscula: notaFiscal, contadorItemNotaFiscal.

Tamanho
O limite para o tamanho do nome de um identificador é o bom senso apenas, não há limitação imposta pelo framework. Assim, nomes muito extensos podem ocupar muito espaço na tela e atrapalhar a leitura. É bom lembrar também que, para nomes de controles na web (na view, propriamente), a questão do tamanho pode impactar o tráfego de dados, já que cada caractere representa um byte.
Caracteres especias
No C#, é comum usar o sublinhado (underline, underscore) para inicializar os campos privados, também conhecidos como atributos. São aqueles elementos declarados no escopo da classe e, portanto, disponíveis para todos os métodos dessa classe. Assim, um campo para representar o repositório de clientes poderia se chamar _clienteRepositorio.
Toda linguagem possui suas palavras reservadas (key words). No C# é possível usar o arroba (@) se for muito necessário que uma variável se chame class, por exemplo (@class).
Ferramentas de produtividade
O próprio Visual Studio sugere nomes para controles usando esses padrões. Se você cria um item de menu com a descrição Clientes, a IDE vai sugerir que o respectivo nome do controle seja clientesMenuItem, por exemplo.
Outra ferramenta que implementa essas práticas é o ReSharper, da JetBrains. Essa ferramenta já sugere um conjunto bem mais abrangente de boas práticas, destacando no código a nomenclatura que foge ao padrão.
Comment: Resposta bem completa. Parabéns.
Comment: @GuilhermeJSantos e a minha resposta é completa? :)
Answer: Existe um padrão de nomeação das variáveis e facilita na codificação
Métodos => Letra Maiúscula na primeira letra exemplo: private void GetCadastrarUsuario()
Propreties => Letra Maiúscula na primeira letra exemplo: public String Nome { set; get; }
Event => Letra Maiúscula na primeira letra exemplo: public event EventHandler OnChange;
Variáveis Globais no escopo da Class => Utilizar o '_' antes do nome da variável exemplo: int _variavelExemplo = 0;
Variáveis Internas: => exemplo: int valor = 0;
Obs: Quando se referência a algum item do layout através do C# é importante colocar o exemplo : this.ButtonSave , pois facilita identificar de onde vem essa variável.


How to reload files in app/models/subdirectory in dev environment for STI

Question: I implemented STI in one of my models, using some tips from Alex Reisner's blog post. I already had all my subclasses use the superclass's controller, with serialize/store to hold the extra attributes. I added the model_name and self.select_options methods to the superclass, and the preload initializer from Alex's blog. I also changed my collection_select in the _form view helper and attribute validation to use the self.select_options method. All my subclasses are in individual files in a app/models/subfolder, though they're not namespaced like SubFolder::Subclass.
Then I start running into problems. Upon changing any code, self.select_options stops returning all of the subclasses. It only returns a small subset or none. Thus due to the validation and _form tie-in, I can't edit/update my models after a code change. From what I could tell, when I change any code, Rails reloads the environment, but not the models in the subfolder.
I tried adding the routes to config.autoload_paths like many suggest, but ultimately that didn't work.
So ultimately, I want:

Something to fix the autoloading, so I won't have to restart the server after every change
Base it off the subdirectory containing all the children, to avoid manually maintaining an array
Rails 3.2.11, ruby 1.9.3p125, ubuntu 12.04.01, rvm
Answer: I ended up combining the code from this answer and this one and knowledge gleaned from the wondible blog posts at the bottom. The config.autoload_paths never seemed to help anything, but I kept them in there. The key part is the initializer that requires all the files in the subdirectory on startup and then at each reload. I tried load over require_dependency, which didn't work. It's definitely been nice not having to reload all the time.
In application.rb
config.autoload_paths += %W(#{config.root}/app/models/configuration)

In development.rb
config.autoload_paths += Dir["#{config.root}/app/models/configuration/**"]

In preload_sti_models.rb
if Rails.env.development?
  Dir.entries("#{Rails.root}/app/models/subfolder").each do |c|
    require_dependency File.join("app","models", "subfolder", "#{c}") if c =~ /.rb$/
  end
  ActionDispatch::Reloader.to_prepare do
    Dir.entries("#{Rails.root}/app/models/subfolder").each do |c|
      require_dependency File.join("app","models", "subfolder", "#{c}") if c =~ /.rb$/
    end
  end
end

Some blog posts with useful information

http://wondible.com/2012/01/13/rails-3-2-autoloading-in-theory/
http://wondible.com/2011/12/30/rails-autoloading-cleaning-up-the-mess/
http://wondible.com/2011/12/23/give-rails-autoloading-a-boot-to-the-head/
http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/

Edit: it's a known thing.
Answer: This solution is similar to undefinedvariable's above, but a bit more DRY.
# organize your sti classes in directories named after the parent
sti_directory_paths = [
  Rails.root.join("app","models","subfolder_one"),
  Rails.root.join("app","models","subfolder_two"),
]

def require_sti_model(path, filename)
  require_dependency (path + filename).to_s
end

# if you use something like guard, just exclude from production
unless Rails.env.production?
  sti_directory_paths.each do |sti_directory_path|
    Dir[sti_directory_path + "*.rb"].each do |filename|
      require_sti_model(sti_directory_path, filename)
      ActionDispatch::Reloader.to_prepare do
        require_sti_model(sti_directory_path, filename)
      end
    end
  end
end


ng2-signalR throwing error after angular upgrade to 9

Question: Recently upgraded to angular 9 able to run but got the below error in certain components where ng2-signalR is used.
enter image description here
enter image description here
Here is the component code
import { SignalR, IConnectionOptions } from 'ng2-signalr';

constructor(private _signalR: SignalR)

ngOninit(){
 let o: IConnectionOptions;
    let conx = this._signalR.createConnection();
    conx.status.subscribe((s) => {if(s.name=='disconnected') {conx.start()}});
    conx.start().then((c) => {
      let listener = c.listenFor('getChanges');
      listener.subscribe((data) => {
        if (data == 'UpdateSitRep') {
         //do something;
        }
      });
    });
}

Here is the app.module.ts
import { SignalRModule, SignalRConfiguration } from "ng2-signalr";

export function createConfig(): SignalRConfiguration {
  const c = new SignalRConfiguration();
  c.hubName = 'NotifyHub';
  c.qs = { user: '' };
  c.url = `${environment.apiUrl}/signalr`;
  c.logging = true;
  c.executeEventsInZone = true; // optional, default is true
  c.executeErrorsInZone = false; // optional, default is false
  c.executeStatusChangeInZone = true; // optional, default is true
  return c;
}

version of ng2-signalr
"ng2-signalr": "^6.1.0"
Answer: There is a fork called "@henkkelder/ng2-signalr" that can be used as ng2-signalr support has stopped after angular 9 .


head_title drupal

Question: in html.html.twig in title tags
<code>{{ head_title|safe_join(' | ') }}
</code>

This code display " home | " how to remove( | ) from display in home page?
also in other page display " page | Home " i want title in other page display "Home | page " ?
Comment: In your second example "page | Home", is 'Home' meant to be the name of the website?
Answer: It's easier and better to override this using the Metatag module.
The D8 version UI looks different than the picture below which is from D7.
This video goes over the D8 version.

head_title drupal


Occurence and Position of digits in a combination lock

Question: If you have a $6$ digits combination Lock and you can use the digits from $1 \to 9$
Now I have these two cases, how many possible combinations there are if
(case 1) Every digit that occurs in the combination, occurs exactly twice.
(case 2) The digit 1 occurs twice, but not consecutively.
For (case 1), This is what I think, The problem is that we don't know where the digits are repeated. But I thought, Imagine if we knew where the digits are repeated then we have $9 \times 8 \times 7$ different possibilities right ? And after this we are left with the problem of locality, and so I reduce the problem to the following.
How many different ways of arranging $AABBCC$, this is $\large{\frac{6!}{2 \times 2 \times 2} = 90}$ right ?
And so I multiply $(9 \times 8 \times 7) \times (90)$ to get my answer. Is this correct ?
So basically I am saying, first calculate the number of ways if you already know where are they repeated times the number of ways you can change their arrangement ?
It seems very logical to me, But I want someone to confirm or deny this argument, also, is there another way to do it ?
Now for (case 2) The digit 1 occurs twice, but not consecutively
I figured out there are 10 ways for $1$ to occur twice but not consecutively
$1 - 1 - - - $
$1 - - 1 - - $
$1 - - - 1 - $
$1 - - - - 1 $
$- 1 - 1 - - $
$- 1 - - 1 - $
$- 1 - - - 1 $
$- - 1 - 1 - $
$- - 1 - - 1 $
$- - - 1 - 1 $
And for each one of them we have 4 other places to fill but this time we only can insert digits from $2 \to 9$, and so we would have $8^4 \times 10$ in total ?
Answer: Everything is correct except one typo: $1\to 8$ in the last sentence should read $2\to 9$.
In the second case it is easy to see that there are ${5\choose 2}=10$ ways to place $1$'s non-consecutively, so full search is not needed.
Comment: Thanks for pointing this out :)