Does "Let" imply existence?

Question: Many years ago I kept trying to explain a proof to professor. Each time I started the proof saying "Let x be..." the professor would interrupt with "what do you mean by let?"
I came to believe what they meant is when you use "Let" you are asserting such an object exists. In this case the existence of the object had not been established so we were not free to choose it. More or less I stopped using "let".
But I notice in proofs people often say "Let" when no such object exists. So I was wondering what is the proper use of "Let"?
Comment: @RobArthan: The professor made a comment which (1) made a lasting impression (this was years ago) and which (2) caused the OP to start thinking about hidden implicit assumptions in mathematical terminology. Sounds quite helpful to me. Getting students to question things they took for granted can be more valuable than teaching them specific pieces of knowledge.
Comment: This isn't formal, so just a comment, but the way I mostly see it is that when you say "let..." during a proof, it asserts the existence of such an object, but when you use "let..." in the statement of a theorem/proposition, it doesn't assert existence, but only functions as conditional in an implication.
Comment: I don't think there is any implication of existence.  Proofs by contradiction often use "Let" to describe things that do not in fact exist.  For instance, the standard proof that there are infinitely many primes begins with something more or less akin to "Let $N\in \mathbb N$ be such that all the primes are less than $N$. "  From which one then derives a contradiction.
Comment: I thought the idea of education was that teachers pass on knowledge to their students - of course, I understand that teachers don't always want to spoon-feed their charges. Your professor sounds like an unhelpful idiot.
Comment: [How to interpret "let" in mathematics](https://math.stackexchange.com/a/4053215/21813).
Answer: Whatever you prove after "Let $x$ be [blah]" is a theorem under the assumption that $x$ is a blah. Notice that it's not a theorem under the assumption that there exists a blah, but that $x$ is such a blah.
In particular it is a result with a free variable, but it doesn't say anything about whether such a blah exists. "Let $x$ be a real number with square $-1$. [blah] Therefore $0=1$" (I'll let you fill in the gaps of this proof !) is a perfectly valid proof, and it is not operating under the assumption that there exists a real number with square $-1$. It is operating under the assumption that $x$ is a real number with square $-1$.
In particular, if you already know that $0=1$ is false, then you can deduce the following result (with no free variable) : there is no real number with square $-1$.
Let me now state things more precisely. In most formal deduction systems, you have variables $x,y,z,x_0,...$. In a formula (not a proved formula, just a syntactically correct formula), some variables can be bound (for instance $x$ appearing within the scope of a quantifier such as $\forall x$), some can be free.
To deal with this precisely in the deduction system, one very convenient tool is the tool of contexts - this is better known in things such as type theory but it makes complete sense and is very relevant in classical logic as well. A context $\Gamma$ is a declaration of free variables, and assumptions on these variables (in type theory, you can somehow package these into just saying the type of the variable, but in classical logic this will come in the form of formulas). An example of a context $\Gamma$ is "variables : $x$, assumptions: $x$ is a real number, $x> 0$" - one variable, and two formulas.
Along a deduction, the context can change, which can make your deduction system very flexible and much closer to actual mathematical practice than other deduction systems without contexts. One example of such a change of context is the $\exists$-introduction rule.
This says, very vaguely (there are precise hypotheses that I will not spell out) that if in the context $\Gamma \cup \{x, \psi(x)\}$, where $\Gamma$ does not talk about $x$, you can deduce $\phi$, which does not talk about $x$ either, then in the context $\Gamma$, you can deduce $(\exists x, \psi(x))\implies \phi$. Informally, what this is saying is "if just by assuming that $x$ satisfies $\psi(x)$, and nothing else on $x$, I can deduce that $\phi$ is true, then just the existence of such an $x$ implies $\phi$" - it's obvious, when you say it like that, but in a formal deduction system you have to write it down.
In any case, what's the point of all of this ?
Well the sentence "Let $x$ be a [blah]" should be seen as a context declaration : you're declaring that you're working in the context $\Gamma = x$, such and such assumption on $x$. This does not, in any way, assume anything about existence. When you conclude your proof, say you prove $\phi$ which doesn't mention $x$, then you reach the state "$\Gamma \vdash \psi$" (read "$\psi$ can be proved in the context $\Gamma$")
This does not allow you to conclude that $\psi$ is correct, of course, because you're working within a context. Now, by the $\exists$-intro rule that I mentioned earlier, this does give you $\vdash (\exists x, blah)\implies \psi$ - in the empty context (or under some axioms, with no free variables, defining a global context which you don't specify at all times).
Theorems are results that are proved in the empty context. Now if you want to deduce $\psi$ from this theorem, then you have to make a statement about existence of an $x$ such that blah - this is how implications work : if I want to prove $B$ but only know $A\implies B$, I better say something about $A$ !
So in conclusion you are completely free to use "let" even when things don't exist, or when you don't know whether they exist - as long as you draw the right conclusion from what you've actually proved, and don't say something like "let $x$ be such that blah, therefore $\psi$. Therefore $\psi$" without knowing whether such an $x$ exists.
Note that it would be absurd to have this restriction on "let" : math is not decidable, and so that means that there would be sentences where it's not decidable whether or not you're allowed to write them down !!
Answer: Technically it would probably be better to say Suppose that $x$ is (rather than Let $x$ be) when we don't know for a fact that such an $x$ exists or when we intend to prove by contradiction that it does not: we can always suppose something hypothetically. In practice, however, it is common — I would even say quite normal — to use let in both contexts, and I have little if any sympathy for your professor, who seems to me to have been riding an idiosyncratic hobbyhorse.
Answer: "Let" uses an existential proposition implicitly. In formal logic, there is a rule for existence elimination. What it says is that if you have a proposition $\exists x P(x)$, where $P$ is a predicate, then you can construct a subproof with $P\left(c\right)$ as a premise through introducing a new symbol $c$. If you can derive a proposition $Q$ which is irrelevant to $c$ in your subproof, then you $Q$ can be placed outside your subproof and be a derived proposition in the main proof. So "let ..." can be seen as a combination of an existence proposition and the introduction of a subproof with a new symbol.
I strongly recommend reading the book "language, proof and logic" by Jon Barwise and John Ethemendy and getting familiar with the fitch proof style introduced in this book. Honestly, most of the difficulties in learning rigorous math like real analysis or linear algebra lie in the lack of understanding of formal logic. Universities are lacking fundamental math education for new undergraduates and expect them to understand complicated proofs without knowing thoroughly first order logic. It is very difficult for students to understand the so-called $\epsilon-\delta$ language and the implicit use of logic rules in English. The book provides you with a fundamental understanding of first order logic and its application in set theory. Even if it is unrealistic to write daily proofs in fitch style, understanding it helps you figure out the correspondence between daily language and formal language.
Answer: I don't think that "let" necessarily implies existence, it's just a symbolic assignment. For example, I think it's valid to do something like "let $x$ be something that doesn't exist" - you could show $x$ doesn't exist by showing it contradicts some property that is known to be true. Ultimately we should be careful about what words we use in what context, but I don't think using "let" in this way is abusive at all.

Does "Let" imply existence?


Distribution function of arrival in an interval

Question: With the following question :
"Alice and Bob show up at the post office between 3 and 4 p.m. Their arrival times
respectively $T_A$ (Alice) and $T_B$ (Bob) are independent and uniformly distributed
in this interval. We call $T_{min}$ the time of the first arrival (therefore $T_{min} =
min(T_A, T_B)$), and $T_{max}$ the time of the second arrival (thus $T_{max} = max(T_A, T_B)$).
To simplify the notations on the representative measurement of time in hours:
time $0$ is 3 p.m., time $1$ is 4 p.m., time $1/2$ is 3:30 p.m., etc.
Find the distribution function $F_{min}$ of $T_{min}$.
Hint: Alice and Bob both arrive strictly after 3:15 p.m. if and only if $T_{min} > 1/4$."
I don't understand some things in the solution, which is:
"The hint tells us that $T_{min} > 1/4$ iff $T_A > 1/4$ AND $T_B > 1/4$. This observation is true for any time $t$: $T_{min} > t$ iff $T_A > t$ AND $T_B > t$. We remember that $F_{min}(t) = P(T_{min}\leq t)$. So $1 - F_{min}(t) = P(T_{min}> t) = P(T_A > t)P(T_B > t)$ by independence of $T_A$ and $T_B$. So $F_{min}(t) = 1-(1-t)^2 = 2 t - t^2$ for $t \in [0,1]$. For $t\leq0$, $F_{min}(t) = 0$ and for $t\geq1$, $F_{min}(t) = 1$."
What I don't understand:

Why do we do $1 - F_{min}(t)$ to switch the direction of the inequality in $P(T_{min}> t)$? (in short, why don't we directly try to find $P(T_{min}\leq t)$ ?)

How do we get $P(T_A>t) = (1-t)$? I can't find the law or the formula giving this. Also, if it's pure logic, I always come back to my previous question.

By the way $P(T_A>t) = P(T_B>t)$ hence the square of $(1-t)^2$, that I understand.
Answer: For your first question: you need to use the observation that "$T_{\min} > t$ if and only if $T_A > t$ and $T_B>t$" which gives a direct route to computing $P(T_{\min} > t)$. There isn't a "corresponding" observation of the form "$T_{\min} \le t$ if and only if $T_A \le t$ and $T_B \le t$" (or something similar), so the provided approach for finding $P(T_{\min} \le t)$ is as direct as you can get, even if it goes via finding $1 - P(T_{\min} > t)$.
$P(T_A > t) = 1-t$ comes from the definition of $T_A$ being uniform on $[0, 1]$.


How do I change the machine name of a field once it's been created

Question: I spaced out while typing the field name an now the machine name is not what I wanted it to be. I know it's just an annoyance. but I'm wondering if there is some way to alter the machine name of a field once it is created.
I suppose this leads me into the second part of my question. if I created a field, and it is no longer being used, how do I go about deleting it, does this have to be done from the database, or can it be done somewhere in the UI.
Answer: My procedure is to use drush to clone the field first, then copy the field data with DB queries into the new field table. After I verify the contents of the cloned field, I delete the original field.
I do it this ways because I think the drush method of cloning fields will always be at least as reliable as any cloning code I might craft myself, the data copy query is pretty simple, and I get to check the new field before deleting the original.

drush field-clone field_my_field field_my_field_clone
Insert rows into field_my_field_clone, e.g., INSERT field_my_field_clone SELECT * FROM field_my_field;
Verify the contents of field_my_field_clone.
Delete the field using the UI, e.g., admin/structure/types/manage/my-content-type/fields
Comment: This is great!  For D7:

INSERT field_data_field_my_field_clone SELECT * FROM field_data_field_my_field;
INSERT field_revision_field_my_field_clone SELECT * FROM field_revision_field_my_field;
Comment: It looks like `field-clone` was dropped in Drush 9. Drupal developers that use 8.4+ will not be able to use this feature.
Comment: I didn't know there was a "drush field-clone" command ! Awesome :)
Comment: What about views, panels, etc?  Manual fixes?
Comment: if you are using drush you can direclty delete the field with  `drush field-delete xxx` and you could also like `drush sql-query` as suggested by neubreed. @zkent, you will have te relink the new field in the existing views, panels, etc.
Answer: In short, you can't change the machine name. In theory, it's obviously possible, but it will require quite a bit of messing with the database. If you've only just created the field, it's far easier to remove it and create a new one.
The basics would be to rename all entries on field_config and field_config_instance, but as soon as you start using the field, the machine names get's stored in a hundred different places. Views config, Panels config, Features and more, and by then, changing it is not fun.
Deleting fields can be done on: admin/structure/types/manage/[machine_name_of_content_type]/fields, which you can reach through the "Manage fields" tab on any content type.
Comment: There is a functionality that I haven't investigated a lot, that deletes fields and their content over time. The reason is to prevent that a site grinds to a halt when deleting a fields with thousands of entries. If the field is not used anywhere, I would expect it to go away on the next cron run.
Comment: @Dmitry Vyal: The field name is stored in a few places in a serialized array – replacing one string with another string of a different length would break the unserialize() of the array and probably break the next bootstrap or Drupal.
Comment: But don't the fields still remain in the database, for instance, I created a new field with the popper name, however when I go to add a new field to a content type, the old field name still appears as an option ... perhaps I'm not understanding exactly how fields work.
Comment: I tried to do a sed -i -e s/old_field/new_field/ on a site code and database dump. Unfortunately, something went wrong and after the dump restoration site was malfunctioning. Any ideas how to do it right way?
Comment: @Charlie S: Thanks, will take care of it in the future.
Comment: This isn't entirely true. Although Drupal seems to store references to certain fields in multiple places, the biggest catch seems to be the serialized data storage in the field_config table in the data column. If you replace each instance of the old field name with the new field name, you must remember to recalculate the length of the new string and replace the character count the precedes each reference. For instance, something like: s:29:"field_revision_field_category" would become s:33:"field_revision_field_new_category" because I added 4 characters to the name. Hope this helps.
Comment: Author is correct in that you can't change the machine name easily.  However, deleting the field WILL NOT help. The machine name is retained even after deleting the field. I think that if the entire content type is whacked, you can start over. That is not a great solution in most cases, especially if there is already content that you don't want blown away
Answer: In Drupal 7, you can use the Field Rename module.
In Drupal 6, you can use CCK field rename module.
Comment: There is now a Drupal 7 Version of this module at https://www.drupal.org/project/field_rename
Comment: It works. Just remember to keep the name length under the maximum.
Comment: any D8 project ?
Answer: I have written an update script, which actually creates a new field and instance with the new machine name, copies all the old field data to the new one and lastly deletes the old instance.
// Set variables
$old_name = 'field_old_name';
$new_name = 'field_new_name';
$entity_type = 'node';
$bundle = 'page';

// Get old field info
$old_field = field_info_field($old_name);

// Create new field
$new_field = $old_field;
$new_field['field_name'] = $new_name;

if (!field_info_field($new_name)) {
  field_create_field($new_field);
}
else {
  field_update_field($new_field);
}

// Get old field instance
$old_instance = field_info_instance($entity_type, $old_name, $bundle);
$new_instance = $old_instance;
$new_instance['field_name'] = $new_name;

if (!field_info_instance($entity_type, $new_name, $bundle)) {
  field_create_instance($new_instance);
}
else {
  field_update_instance($new_instance);
}

// Migrate old fields' data to the new ones
$field_data = db_select('field_data_' . $old_name, 'old')
  ->fields('old')
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->execute();

while ($data = $field_data->fetchAssoc()) {
  $data_new = array();
  foreach ($data as $column => $value) {
    $column = str_replace($old_name, $new_name, $column);
    $data_new[$column] = $value;
  }
  db_insert('field_data_' . $new_name)
    ->fields($data_new)
    ->execute();
}

// Migrate old fields' revision data to the new ones
$field_revision = db_select('field_revision_' . $old_name, 'old')
  ->fields('old')
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->execute();

while ($revision = $field_revision->fetchAssoc()) {
  $revision_new = array();
  foreach ($revision as $column => $value) {
    $column = str_replace($old_name, $new_name, $column);
    $revision_new[$column] = $value;
  }
  db_insert('field_revision_' . $new_name)
    ->fields($revision_new)
    ->execute();
}

// Delete old instance
field_delete_instance($old_instance);

// Purge fields
field_purge_batch(1000);

Answer: I just had to do this, and found it to not be too difficult, but my site is fairly simple.
Try this:

Create a new field with the proper name.
Run these queries in MySQL:

INSERT INTO field_data_[NEW MACHINE NAME] (entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_fabric_color_pattern_tid) SELECT cf.* FROM  `field_data_[OLD MACHINE NAME]` cf

INSERT INTO field_revision_[NEW MACHINE NAME] (entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_fabric_color_pattern_tid) SELECT cf.* FROM  `field_revision_[OLD MACHINE NAME]` cf

(swap out [NEW MACHNIE NAME] and [OLD MACHINE NAME] with field_your_field_names)

Update any views involved to use the new field, and any other modules that point to that specific field (this is where things might get ugly if your site is complicated).  You can see any views that use your old field here: /admin/reports/fields/views-fields
Clear site cache
Comment: what for d8? is it working for paragraph too?
Answer: // Change the field storage table names.
Here we are altering the name of the old table with new name.
db_rename_table($data_table_name, 'field_data_' . $new_field_name);
db_rename_table($revision_table_name, 'field_revision_' . $new_field_name);

// Change the field names in the field_config and field_instance_config tables.
db_update('field_config')
  ->fields(
    array(
      'field_name' => $new_field_name,
    )
  )
  ->condition('field_name', $field_name, '=')
  ->execute();

db_update('field_config_instance')
  ->fields(
    array(
      'field_name' => $new_field_name,
    )
  )
  ->condition('field_name', $field_name, '=')
  ->execute();

Answer: With the drush field-clone answer above you can do the last MySQL step with Drush also (D7 example):
drush sql-query "INSERT field_data_field_my_field_clone SELECT * FROM field_data_field_my_field"

drush sql-query "INSERT field_revision_field_my_field_clone SELECT * FROM field_revision_field_my_field"

Answer: If you don't want to fiddle around in mysql you could try a drush script I wrote called Field value copy.
You will need to setup your new field first and then call
drush fieldcopy OLDFIELDNAME NEWFIELDNAME

This will move existing data to the new field once done delete the old field.
Answer: The db_change_field() function may help you.
Answer: Export the SQL file of your database, use the command line sed to replace all occurrences of the term to change, and re-import your database.
Comment: Downvoted your comment because this approach will wreak havoc on your Drupal installation since there are a few places in the database where the field names are PHP serialized. For more information about this, see the comments from @CharlieS (and others) under the accepted answer above.


Not allowed to create or change a record in MS Access

Question: I have read numerous thread on the above question, but none of the answers satisfy the problem.  My problem is two tables that are linked to each other (in a one to one relationship) using an "ID" field which is also the primary key.  When I try to enter a record in the the main table (Don't know if Access knows this is the main table) the I get the following error:
<code>"You cannot add or change a record because a related record is required in table"</code>
Could anyone please help me with this?
Thanks
Answer: A "One-To-One" relationship is really a One-To-Zero_or_One relationship, but the table diagrams on the Relationships page in Access do not make it clear which table is the "parent":

However, if you right-click on the line joining the tables and choose "Edit Relationship..." you will see

In this case [Table1] is the "parent" table and [Table2] is the "child" ("Related") table, so we must insert a row into [Table1] before trying to insert the corresponding row into [Table2].
Comment: Thank you for your help.  I am just going to use a workaround to write into the database.
Answer: The issue seems to be occuring because you are trying to set the primary key of your table as a foreign table.
What you need to do is create a new column in the 2nd table and link it to the id of the first table, therefore creating a relationship.
Let's take the following simple example since you haven't mentioned the names given to your tables.
In a university environment, you would have the table LECTURER which is linked to the table SUBJECT, so that a lecturer can teach a subject. The relationship between the 2 tables would be so:
LECTURER TABLE
LECTURER_ID | LECTURER_NAME | LECTURER_ADDRESS
SUBJECT TABLE
SUBJECT_ID | SUBJECT_NAME | SUBJECT_DESCRIPTION | SUBJECT_LECTURER_ID
The link between these two tables would be between the SUBJECT_LECTURER_ID from the SUBJECT table and the LECTURER_ID from the LECTURER table. This is a one to one relationship since we are assuming that each subject in this particular university is only taught by one lecturer, and a lecturer can only teach one single subject.
Hope this helps :)
Comment: That works nicely.  Thank you.  But how do you link these tables so that a record will be created in the SUBJECT_ID field containing default values?  I have a database to keep track of users and their log in information.  I am trying to add a record to the "LOG" table when a new user registers
Comment: I think and insert needs to be done here to handle a new user who registers into the system. This is not handled by relationships. Relationship link the existing data in one table to already existing data in a second table.
Comment: Okay thanks.  I have tried using insert through code, but I still get the error.  I am working with Delphi 7.  This is for a school project, thus I must use this version
Comment: What is the SQL you are using to insert the new record in the LOG table?
Comment: I am not using SQL at the moment.  A simple ADOTable.insert method is called with all the information regarding a user inserted after that
Comment: I never worked with Delphi, but maybe this link can help you: `http://www.delphipages.com/forum/showthread.php?t=176191`


Why is this natural language sentence written in a formal predicate language the way it is here?

Question: I have this sentence: "All teachers and students are here." Also I have these predicates: t(x) - x are teachers, s(x) - x are students, h(x) - x are here. In my textbook the sentence is written in a predicate language this way: $\forall x((s(x)∨t(x))\to h(x)$ .
The question is: Why there is OR symbol instead of AND symbol?
Comment: x can either be a teacher or a student, but not both
Comment: Oh I see. Thanks!
Comment: Note this is equivalent to $(\forall x)(t(x)\implies h(x)) \land (\forall x)(s(x)\implies h(x))$ which contains "and".
Answer: An "and" here would mean "for every $x$, if $x$ is a teacher and $x$ is a student, then $x$ is here". In English the "and" is intended as a union, which is expressed in logic as "or".
Answer: This is a classic. The one I always use is 'All fruits and vegetable are nutritious'
So yes, given the 'and', you might be inclined to symbolize "All teachers and students are here" as:
$$\forall x ((T(x) \land S(x)) \to H(x))$$
but that would mean that "Anyone who is both a teacher and a student is here"
So, what's going on? Why doesn't the 'and' in English give you the logical $\land$?
It's because "All teachers and students are here" is really short for "All teachers are here and all students are here".
Indeed, we could translate this sentence as:
$$\forall x (T(x) \to H(x)) \land \forall x (S(x) \to H(x)) $$
which is equivalent to:
$$\forall x ((T(x) \to H(x) \land (S(x) \to H(x)) $$
And now, here is the crucial equivalence that swithces the $\land$ into an $\lor$:
$$(P \lor Q) \to R \Leftrightarrow (P \to R) \land (Q \to R)$$
So with that, we can symbolize the sentence also as:
$$\forall x ((T(x) \lor S(x)) \to H(x))$$
and if we translate that back to English, we get:
"Anyone who is  a teacher or a student is here"
which is, if you think about it, exactly what we want!


Why wont my code load properly?

Question: In class we have to create a save/load function utilizing the split() method for a class and dictionary.  I managed to get the save function working, but the load function does not seem to want to work for me.  I either get it almost working but the saved file does not load, or i get the error
"playerclass" has no "player" attribute.  needs to use the init method. Here is the code in its entirety def loaddata(): is mainly the area of concern.
class playerclass:
    name = ""
    phone = ""
    jersey = ""
    def __init__(self, name, phone, jersey):
        self.name = name
        self.phone = phone
        self.jersey = jersey
    def setname(self, name):
        self.name = name
    def setphone(self, phone):
        self.phone = phone
    def setjersey(self, jersey):
        self.jersey = jersey

    def getname(self):
        return self.name
    def getphone(self):
        return self.phone
    def getjersey(self):
        return self.jersey
    def disroster(self):
        print("Player Bio")
        print("-----------")
        print("Name: ", self.name)
        print("Phone #: ", self.phone)
        print("Jersey #: ", self.jersey)

def savedata (players):
    filename = input("Enter file name: ")
    print("Saving....")
    outFile = open(filename, "wt")
    for x in players.keys():
        name = players[x].getname()
        phone = str(players[x].getphone())
        jersey = str(players[x].getjersey())
        outFile.write(name+","+phone+","+jersey+"\n")
    print("Save Complete")
    outFile.close()

 def loaddata ():
    players = {}
    filename =input("Enter filename to load: ")
    inFile = open(filename, "rt")
    print("Loading.....")
    while True:
        inLine = inFile.readline()
        if not inLine:
            break
        inLine = inLine [:-1]
        name, phone, jersey = inLine.split(",")
        players[name] = playerclass(name, phone, jersey)
    print("Load Successfull.")
    inFile.close()
    return players

def roster(players):
    if len(players) == 0:
        print("No players on roster: ")
    else:
        for x in players.keys():
            players[x].disroster()

def add_player (players):
    newName=input("Enter name of player to add: ")
    newPhone = int(input("Enter phone number of player: "))
    newJersey = int(input("Enter number of assigned jersey: "))
    players[newName]= playerclass(newName, newPhone, newJersey)
    return players

def ed_player (players):
    oldName = input("Enter players name to edit: ")
    if oldName in players:
        newName = input("Enter new name for player: ")
        newPhone = int(input("Enter new phone number for player: "))
        newJersey = int(input("Enter newly assigned jersey number: "))
        players[oldName] = playerclass(newName, newPhone, newJersey)
    return players

def del_player(players):
    delName = input("Enter players name to delete from roster: ")
    if delName in players:
        del players[delName]
    return players

def displayMenu():
    print("-------Main Menu-------")
    print("1. Display Team Roster.")
    print("2. Add Member.")
    print("3. Remove Member.")
    print("4. Edit Member.")
    print("5. Save Data.")
    print("6. Load Data.")
    print("9. Exit Program.")
    return  input("Menu Choice:  ")

print("Team Management Tools.")

players = {}
menu_choice = displayMenu()
while menu_choice != '9':
    if menu_choice == '1':
        roster(players)
    elif menu_choice == '2':
        players = add_player (players)
    elif menu_choice == '3':
        players = del_player (players)
    elif menu_choice == '4':
        players =  ed_player (players)
    elif menu_choice == '5':
        savedata (players)
    elif menu_choice == '6':
        loaddata ()
    menu_choice = displayMenu()
print("Updating roster Goodbye:")

Answer: Remove players = {} from your loaddata function, and it'll load properly.
If you actually want to reset the contents of the dictionary when loading (which might have been your intent, although I would say that's a questionable design decision), you can do:
def loaddata():
    global players
    players = {}
    ...

This is because any variables you write to are assumed to be local variables (as in, local to the function) unless you say otherwise.
I might be overlooking something, but I'm not seeing anything that attempts to read a player attribute from any object, so I'm not sure where the error is coming from. Was it from a different version of this code? Or, if it is the posted version that has that error, can you provide exactly what series of inputs lead to the error?

The rest of this answer isn't directly relevant to your question, just some tips based on things I noticed in your code.
I would remove the:
name = ""
phone = ""
jersey = ""

Because you set them in __init__ and so they're redundant and not doing anything. For looping over lines in files, you can use a for loop, which is more readable than while loops. Example:
for line in infile:
  print(line)

And you should look into with. It's another type of block, and they're very useful when working with files because they'll automatically close the file when the block ends, so you don't have to. As an example:
with open("foo", "r") as stream:
    for line in stream:
        print(line)
# stream got implicitly closed because the block ended

Why wont my code load properly?


Variable Base with Variable as Factor in Exponent, Find Value

Question: I saw a problem recently that looked like this:
Assume $w$ and $z$ are positive.  If $z^{4w} = 64$, what does $z^{6w}$ equal?
And I had absolutely no idea how to even begin attempting this equation.  How could I have gone about figuring out the answer?  This question was multiple choice, though I don't remember the answers available to me.
Comment: What's the relationship between $a,b,z,w$?
Comment: Sorry, "a" and "b" were mistakes on my part.  It should have been "z" and "w" only.
Comment: Well then, do you know that $x^{ab} = (x^a)^b$?
Comment: Yes, but I'm not sure how to apply that knowledge to this problem.
Comment: $4 \times \frac{3}{2} = 6$.
Comment: So then...Uhm...I'm still unsure as to how to answer the question.
Answer: Given $z^{4w} = 64, z^{6w} =$ ?
We need to find a relationship between the exponents. Since $x^{ab} = (x^{a})^b$,
$$\Large{z^{6w} = z^{4w\cdot1.5}} = (z^{4w})^{1.5} = 64^{1.5} = 512$$
Comment: Oh!  Thank you!  Now it makes sense!!  :D


JQuery toggle slide out tab and click outside to close

Question: i have a problem with this script:
http://jsfiddle.net/bZw83/
It toggles a tab with language selection in or out the screen if a click occurs inside the tab.
Now i'm stuck, i tried to write a function that toggles the tab out of the screen if the click is outside the tab usin something like
<code>$('html').click(function() {...});
</code>
but i cannot exclude the area of the tab from firing the event.
I tried using event.stopPropagation() but i' not able to achieve the goal :-/
Can someone help me figure this out?
Thank you very much
Comment: try to use not selectors of jquery.......try this link http://www.w3schools.com/jquery/sel_not.asp
Comment: @raman can you update your comment and select `not` as source code using backticks? Otherwise it *could* be misread as "*try not to use jQuery selectors*". :)
Answer: You can create a handler for the document, and then check if it the #navigation or a child of it.
Seee: http://jsfiddle.net/bZw83/1/
<code>$(document).click(function(e) {
    $target = $(e.target);
    var is = $target.is('#navigation');
    var isChild = $target.parents('#navigation').length;

    if(!(is) && !(isChild)) {
        $('a', $(this)).stop().animate({
            'marginLeft': '-44px'
        }, 200);
        stato = "chiuso";
    }
});
</code>
Answer: do something like this
<code> $(document).click(function(e) {
    if($(e.target).parents("*").andSelf().is('#navigation')==false)
    {
       //your code here
    }
});
</code>
Answer: You can do it by handling the click event for the document, as follows:
<code>$(document).click(function() {
   $('a',$(this)).stop().animate({'marginLeft':'-44px'},200);
   stato="chiuso";
});
</code>
See working demo


View of attached files to a node

Question: I use D8 Editor File upload to add files to a node. But i want an overall view from all the files in that node, but only in that node. I can create a view for all the files but i can't filter on the nid of the current page.
The project: attachment_links seems to kinda do what i want but its only for Drupal 7.  Does anyone know of a similar Drupal 8 project or a way do code it manually into a block?
Answer: The D8 Editor File upload is using the Drupal file system, so the files uploaded through module do have FID and can be listed in Views.
Here are steps to create a block to show only the files used on the currently visited node:

Create a View of type File with a Block display showing Filename (you probably have this already)
Add a Contextual filter in your Views Block Display called Entity ID from the File Usage Category.
Adjust the settings for that Contextual filter:
When the filter value is NOT available
Provide default value
Type to Content ID from URL
When the filter value IS available or a default is provided:
Specify validation criteria
Validator to Content
Content type [choose appropriately]
 Leave the rest as default
Place the Block in a region you like, adjust the Block options File Usage: Entity ID to Node from URL and restrict to display only on relevant Content types.

Now when you visit nodes of the types you selected in Block and Contextual filter settings will list only the files uploaded to those nodes.
Comment: Awesome this work exactly like i wanted, thanks a lot.
Comment: I also work with paragraphs in the nodes i want to show files, but the files i put in paragraphs don't show up. I repeated the steps but with paragraph as the validator. This does not work. Is there a way to make it work with Paragraphs?
Comment: When i try to configure the 'file usage: entity id' in the  paragraph view block. My only option is -None-
Comment: I fixed the paragraph problem by making a custom block and then loading file ids and paragraph ids. But i just noticed i can't remove the files uploaded with d8 editor file uplload. so i have a big problem.
Comment: Paragraphs complicate things a bit and if you need more help try posting a new question with all the relevant information. About the d8 editor files: why are you using that module? If you wanted structured list of files used on a node using File field would give you that automatically. And if you delete the file from the field, it will no longer display on the list on that node. D8 editor file upload seems best suited for when you need a super simple file upload through the editor. For more complex needs File field would probably be better.

View of attached files to a node


How do I merge subdirectories into a single executable?

Question: I understand that every subdirectory has to have a CMakeLists.txt, but I don't want to create a library or an executable for each directory.
My folder structure:
/src
  /exportedHeaders
  /server
  main.cpp

Each subfolder has a mix of .h and .cpp files. I don't understand how I can mix all of it up into a single executable, there doesn't seem to be a command for that.
Comment: Typically you compile the .cpp files (which include the .h files) into a single executable. Is that what you are asking about? Or do you know how to compile but are asking something else?
Comment: @jwd:  right, but how do I add cpp files inside the subfolders to the executable which gets generated from the topfolder? I think I'm missing something bigger :(
Answer: I haven't really used CMake, so there is probably a better way, but as far as I know you can just specify the path to all the source files.
eg:
add_executable (myProgram main.cpp subdir1/foo.cpp subdir2/bla.cpp)

I imagine you could use file globbing to get  *.cpp in each subdir, to reduce typing.
See this mailing list message for info about file globbing in CMake.
Comment: With CMake, it is better to list your files explicitly than to use any file globbing techniques. If you list them explicitly, then you have to change your CMakeLists.txt file when you add and remove files... and the build system can note that CMakeLists.txt file is out of date and automatically re-run CMake when you make such a change. With a file globbing technique, there is no such file change occurring, and you do not get the benefit of CMake running automatically when necessary.
Comment: Yes, this is the typical way of handling this. FWIW, I typically set up my projects to have `include/`, `src/` and `test/` folders, and I usually just have one `CMakeLists.txt` file in the top directory for all my targets which may be scattered (organized!) in different source folders.
Comment: Each directory having separate cmakelists.txt


How do I choose a random value from an array with JavaScript?

Question:
Possible Duplicate:
JavaScript: Getting random value from an array

I have an external js with the following line:
var postmessage = "hi my favorite site is http://google.com";

but is there a way to pick a site a random from an array so like this
var postmessage = "hi my favorite site is +'random'";

random= http://google.com, http://yahoo.com, http://msn.com, http://apple.com

how do i make it work?
Comment: Getting the language right in the title would be a start
Comment: first: your title of your post should be "Javascript" .... shouldnt it? you can init an array with: var random = array(....); and then take an index with "Math.random()"
Comment: https://stackoverflow.com/a/45606635/8202629
Answer: var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"];
var favorite = favorites[Math.floor(Math.random() * favorites.length)];
var postmessage = "hi my favorite site is " + favorite;

Create an array of your sites, then pick one element from the array. You do this by choosing a random number using Math.random(), which gives you a result greater than or equal to 0 and less than 1. Multiply by the length of your array, and take the floor (that is, take just the integer part, dropping off any decimal points), so you will have a number from 0 to one less than the length of your array (which will thus be a valid index into your array). Use that result to pick an element from your array.
Comment: Has a bug -- needs a paren after `favorites.length`.
Comment: `Math.round(7.919417901018048);// 8` & `Math.floor(7.919417901018048); // 7`
Answer:

var sites = new Array('http://www.google.com', "http://www.stackoverflow.com")

var postmessage = "hi my favorite site is" + sites[Math.round(Math.random()*(sites.length-1))];

First stick all of your sites in an array. Then get a random number from the array length (the -1 is because an array is zero indexed and the length that is returned starts at 1)
Answer: Do something like this:
function getRandomSite(){
   var sites = ["google.com","bing.com","xyz.com","abc.com","example.com"];
    var i = parseInt(Math.random()*(sites.length-1));
    return sites[i];
};

Comment: Since you're multiplying by 10, and then testing whether it is larger than the length, you're introducing a bias for the last site in the list: it will be picked much more often (almost 50% of the time, in your example). Rather multiply with the length of the array.
Comment: Hi, I thought about this right after I answered the question. You're totally right here.


Bounds for a continuous function given that f(0)=e and f(R)=(-2,-1)U[1,5)

Question: Let  $f:R→R$ be a function such that $f(R)$ is a subset of $(-2,-1) \cup [1,5)$ and $f(0)=e$. Can you give realistic bounds for $f$?
This is a question I got from a book and I didn't understand the question nicely. A solution to this will be appreciated.
Thanks in advance!
Answer: Take $M = 6$ then $| f(x) | \le M$ for all $x \in \mathbb{R}$ .
Comment: but f(0)=e is not used in this case..there must be a further strong conclusion than this..
Comment: @Dishant $f(0)=e$ has no effect. The best upper bound for $f$ is $5$.
Comment: @Dishant The best you can say is $$1\le f(x)\lt5$$
Comment: Well, I wanted to mention one more thing in the description..f is continuous..so does that help in getting stronger conclusion?
Comment: No. It's not getting stronger.


Find the numbers that do not exist in a String

Question: The problem is as follows: I have a set of numbers from 1 to 80.
In Textbox1.Text I have the following numbers:
TextBox1.Text = "1,4,5,6,7,8,12,13,14,15,16,17,18,19,20,21,22,23,25,28,29,31,33,
                 34,35,36,37,39,40,41,45,46,47,48,49,51,53,54,55,57,59,60,61,62,
                 63,64,66,67, 68,69,70,71,72,73,75,76,77,78,79,80"

How can I display, in TextBox2.Text, the numbers that are not in TextBox1, from 1 to 80?
TextBox2.Text = "2,3,9,10,11 and so on..."

Comment: Please show us what you have done...
Answer: Considering that the question references numbers, so the resulting values might be used somewhere as actual numbers (not just as a string representation of numbers) you could:

Extract the values from the source string in a List(Of Integer)
Create a List(Of Integer) initialized with a number of elements corresponding to the maximum value of the source numbers using Enumerable.Range
Filter the full list of numbers using the partial one using Enumerable.Except
Convert the resulting List(Of Integer) to a comma-separated string of values if required.

Note:
I'm supposing that the source string has already been validated. If it's not, use Integer.TryParse instead of Integer.Parse. A related sample code is in this (so very similar) question.

Dim BaseNumbers As List(Of Integer) =
    txtInput.Split(","c).Select(Function(n) Integer.Parse(n)).OrderBy(Function(n) n).ToList()

'Get the List of missing numbers in the source range of values
Dim ResultList As List(Of Integer) =
    Enumerable.Range(1, BaseNumbers.Max()).Except(BaseNumbers).ToList()

'Convert to string the resulting List
Dim resultString = String.Join(",", ResultList)

Comment: System cannot be converted a string to -1 dimmensional array. Error(  Dim ResultString = String.Join(",", ResultList)
Comment: You need a reference to `System.Linq`. Depending on the VB.Net version, you might need to use `String.Join(",", ResultList.AsEnumerable())`. If it's still not working for you, you need to tell me what VB.Net version (or Visual Studio version) you're using.
Comment: Visual Basic 2008
Comment: These methods are all available from .Net version 3.5. You need, as already mentioned, to add a reference to `System.Linq`, `System.Collections` and `System.Collections.Generic`. Open up the `Project -> Properties -> References -> Imported Namespaces` and add what's missing. If you're targeting .Net 2.0, you need to chage this too, upgrading to 3.5 at least. This VB.Net version is **very** old. You'll miss many of the solutions proposed by StackOverflow answers. You need to upgrade (unless, of course, it's some school assignment).
Answer: Here are two examples not using LINQ.
This one uses a Dictionary and a List:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim n As Integer
    Dim present As New Dictionary(Of Integer, Boolean)
    For Each strValue As String In TextBox1.Text.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        If Integer.TryParse(strValue, n) Then
            present.Add(n, True)
        End If
    Next

    Dim notPresent As New List(Of Integer)
    For i As Integer = 1 To 80
        If Not present.ContainsKey(i) Then
            notPresent.Add(i)
        End If
    Next

    TextBox2.Text = String.Join(",", notPresent.ToArray)
End Sub

This one simply uses two Lists:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim n As Integer
    Dim present As New List(Of Integer)
    For Each strValue As String In TextBox1.Text.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        If Integer.TryParse(strValue, n) Then
            present.Add(n)
        End If
    Next
    present.Sort() ' optional; if you need these sorted for something else

    Dim notPresent As New List(Of Integer)
    For i As Integer = 1 To 80
        If present.IndexOf(i) = -1 Then
            notPresent.Add(i)
        End If
    Next

    TextBox2.Text = String.Join(",", notPresent.ToArray)
End Sub


@keyframes não funciona

Question: tenho uma função jQuery que adiciona a uma div a classe abaixo:
.brancoTransparente {
  animation: cor;
  opacity: .9;
  transition: all .3s;
}
.brancoTransparente a {
  color: #000;
}
@keyframes cor{
  0% {
    background-color: transparente;
  }
  100% {
    background-color: #fff;
  }
}

a cor do link está trocando de boa, o que leva a crer que o jQuery está inserindo a classe. Mas a cor de fundo não está trocando.
O que fiz de errado?
Obs.: fazendo como abaixo funciona. No entanto, o novo background aparece abruptamente e eu gostaria que aparece como efeito fadein:
.brancoTransparente {
    opacity: .9;
    background: #fff;
}
.brancoTransparente a {
    color: #000;
    height: 80px;
    line-height: 80px;
}

É uma corrida no scrool do navegador abaixo de 5px troca de cor
Answer: Para que a class mantenha as propriedades da animação basta adicionar a propriedade animation-fill-mode e escolher o valor necessário.

Valores
none
  A animação não aplicará nenhum estilo ao destino quando ele não estiver sendo executado; Em vez disso, ele será exibido usando seu estado com base em todas as outras regras CSS aplicadas a ele.
forwards
  O destino reterá os valores computados definidos pelo último quadro-chave encontrado durante a execução.
backwards
  A animação aplicará os valores definidos no primeiro quadro-chave relevante assim que ele for aplicado ao destino e reterá isso durante o animation-delay período.
both
  A animação seguirá as regras para frente e para trás, estendendo as propriedades da animação em ambas as direções.

Recomendo você a utilizar animation-fill-mode: both, assim a classe irá manter as propriedades definidas na animação.

.brancoTransparente {
  opacity: .9;
  transition: all .3s;
  animation: cor;
  background-color: blue;
  animation-duration: 1s;
  animation-fill-mode: both;
}
.brancoTransparente a {
  color: #000;
}
@keyframes cor{
  0% {
    background-color: transparente;
  }
  100% {
    background-color: red;
    display: block;
    padding: 10px;
  }
}

    Teste

Answer: Na verdade funciona, só que ele volta ao estado inicial dele, não fica no estado da animação.
Coloque um animation duration de algum tempo e observe que a animação vai funcionar:

.brancoTransparente {
  opacity: .9;
  transition: all .3s;
  animation: cor;
  background-color: blue;
  animation-duration: 1s;
}
.brancoTransparente a {
  color: #000;
}
@keyframes cor{
  0% {
    background-color: transparente;
  }
  100% {
    background-color: red;
    display: block;
    padding: 10px;
  }
}

    Teste

Note: The animation-duration property defines how long time an
  animation should take to complete. If the animation-duration property
  is not specified, no animation will occur, because the default value
  is 0s (0 seconds).

  Nota: A propriedade animation-duration define quanto tempo uma
  animação deve demorar para ser concluída. Se a animation-duration não
  for especificada, nenhuma animação ocorrerá, porque o valor padrão é
  0s (0 segundos).
  https://www.w3schools.com/css/css3_animations.asp
Comment: entendi! Mas eu preciso que essa cor apos alterada, não mude mais até que o volte aos 5px do topo da pagina. Ou seja, mudar gradativo até chegar nos 100% da aimação e apos isso, ter uma opacidade .9 e ficar durante toda a pagina
Comment: Adicionei informações à pergunta!

@keyframes não funciona


Is the content of a predicate in c++ wait_for method mutex protected or not?

Question: Suppose, countMe is a global variable and I am launching 10 threads at the same time to this while loop, is the variable countMe mutex protected in the predicate?
I think because when the code reaches to the wait_for it unlocks and releases the lock, the variable countMe isn't mutex protected. Am I right?
while (true)
{
    std::unique_lock<std::mutex> lock(mtx_kill);
    cv_kill.wait_for(lock, 500ms, [&]() {++countMe; return killFlag; });

    if (killFlag)
    {
        break;
    }
}

Answer:
Am I right?

Nope, you're wrong.

I think because when the code reaches to the wait_for it unlocks the
lock, the variable countMe isn't mutext protected.

No, the mutex is in a locked state when the lambda gets evaluated. Guaranteed.
cppreference.com describes the predicate version of wait_for in terms of wait_until, which is described as follows:
while (!stop_waiting()) {
    if (wait_until(lock, timeout_time) == std::cv_status::timeout) {
        return stop_waiting();
    }
}

Note that the initial state of the mutex is that it's locked. The predicate, called "stop_waiting" here, is always called when the mutex is in the locked state.
You can think of wait_for as just a predicate-less wait, with the additional predicate check as a discrete, separate step. After wait returns the mutex gets relocked, and that happens before the predicate, your lambda, executes. If it votes thumbs down the mutex gets, once again, atomically unlocked together with the condition variable getting waited on again.
P.S. The above discussion presumes that your countMe is always accessed, elsewhere, with the same lock being held. This is presumed by your question, but merely formally noted.
Comment: Well, whether there should or should not be is something that requires a complete understanding of not just this execution thread but all other execution threads' logic that's not shown here.This will, obviously, change the scope of the locking. Whether the resulting logical changes are what they should be, that's something that you'll need to figure out.
Comment: Thanks for the explanation. Should there be something like 'std::unique_lock lk(cv_m);' before that while loop and also should it be 'cv_m.wait_unitl(lock, timeout_time) == std::cv_status::timeout)'?


Fundo preto na aplicação cordova

Question: Estou tendo um problema, uma das páginas da minha aplicação (para o iPhone 4s esse problema está em todas as páginas), tem um fundo preto atrás de todo o conteúdo, quando eu faço o bounce do iPhone (touch arrastando pra baixo depois para cima, além do limite da tela) no iPhone 4s esse problema também aparece entre as divs e pelo GapDebug eu não consigo ver onde ela é definida.
Estou usando o Cordova 6.3.1.
Já tentei o seguinte:
A opção Status Bar Style Light no XCode,
<code><preference name="StatusBarStyle" value="lightcontent" />

<preference name="StatusBarOverlaysWebView" value="false" />

<preference name="StatusBarBackgroundColor" value="#c0c0c0" />
</code>
mas nada altera isso, segue as capturas de tela:
Esta é a tela padrão e correta no iPhone 5+, o overscroll está com a cor correta que é definida pelo css do body
Em outra página, rodando também no iPhone 5+ quando eu dou o Bouce(overscroll)  aparece o fundo preto
No iPhone 4S aparece o fundo preto entre as divs até mesmo na tela inicial
E no Bounce (overscroll) também
O problema é que no iPhone 5+ o fundo preto no overscroll somente acontece em uma página da aplicação, nas outras está padrão cinza (https://i.stack.imgur.com/mwC6R.png)
PS: Não consigo colocar mais que 2 links no meu post porque a minha reputação é menor que 10.
Comment: nunca tive esse tipo de problema, mas nao consigo imaginar outra coisa alem de css, ate por que a cor default do body do navegador é branco, pelo menos a maioria é branco. Se puder posta o css tambem
Comment: Já testei, se eu inspeciono pelo GapDebug, em nenhum lugar diz que o background tá definido pra preto.
Answer: Resolução:
Eu estava procurando por alguma classe que definisse o preto que aparecia, black ou #000000, mas na verdade o que estava definindo de algum jeito era uma classe CSS que estava sendo inserida por outra biblioteca JavaScript que eu utilizava.
<code>.app-content {
    background-color:#FFF;
}
</code>

Fundo preto na aplicação cordova


Prove that the polynomial $a_nx^n+\cdots+a_1x+a_0$ has no rational roots

Question:
Let $\overline{a_n \ldots a_1a_0}$ be the decimal representation of $65^k$ for some $k \geq 2$. Prove that the polynomial $a_nx^n+\cdots+a_1x+a_0$ has no rational roots.

I thought about using the rational root theorem. We know that $a_0 = 5$ since $65$ ends in a $5$, so any rational root must be of the form $-\dfrac{5}{a}$ or $-\dfrac{1}{a}$ where $a$ is an integer factor of $a_n$. How can we continue?
Comment: That follows from $\log_{10} 65$ being irrational, @erfink
Comment: Potentially useful: a quick computer experiment shows that all the digits $\{1, \dots, 9\}$ occur for $a_n$.
Comment: @астонвіллаолофмэллбэрг What do you mean by reduced it to 1 case?
Comment: you have $a_1=2$ too, though that probably won't be helpful.
Comment: Similar to @dezdichado comment, for $k\geq 6$, we seem to have that all the decimal representations end with $\dots 890625$. For $k \geq 7$, we seem to have endings of $\dots 2890625$ or $\dots 7890625$.
Comment: I have managed  to reduce the number of cases to $1$. Can I post this as an answer, albeit incomplete?
Comment: By that, I mean that I have precisely one candidate for the possible rational root of the above polynomial. I am unable to rule out that candidate for the time being.
Comment: The above polynomial seems even to be irreducible over $\mathbb Q$ for all $k\ge 2$. for $2\le k\le 400$, we have an irreducible polynomial. I will continue the search.
Comment: No reducible polynomial for $2\le k\le 550$
Comment: And we have no rational root for $2\le k\le 10,000$
Answer: An incomplete answer, but I hope it may help in getting the final answer itself.
Let $\frac pq$ be a rational root of $f$. Since $f-f(10)$ has $10$ as a root, it follows that  $f-f(10) = (x-10)g(x)$  for some $g$. Now, let $x = \frac pq$:
$$
\left(\frac pq - 10\right) g\left(\frac pq\right) = -f(10) \neq 0
$$
Multiplying by $q^n$ :
$$
\left(p-10q\right)q^{n-1}g\left(\frac pq\right) = -f(10)q^n
$$
From here, we know that $\deg g = n-1$, so that $q^{n-1}g\left(\frac pq\right)$ is an integer. Hence, $p-10q | q^n f(10)$, and by co-primality, $p-10q | f(10) = 65^k$.
We have that $p|5$ and $q | a_n$. So, $p = 1/5$, and $q$ must satisfy $p-10q | 65^k$, where $-9 \leq q \leq -1$ (the polynomial does not have positive roots by Descartes' rule of signs).
Note that if $p=1$, then for the above $q$, not case matches. However, if $p=5$, then $q=-6$ fits the criteria. So all we have to  do is to check that $\frac{-5}{6}$ is not a rational root, then we are done. In fact, this shows that if the leading coefficient $a_n \neq 6$, then we are done.
Comment: have not written down it rigorously, but if you let $f(x)=(6x+5)h(x)$ and manage to prove $h(x)\in\mathbb{Z}[x]$, then $h(10) = 65^{k-1}$ and $h$ is monic, which is a contradiction I think.
Comment: Can't you also have $q=-2$?
Comment: Let $f_n(x)=(6x+5)f_{n-1}(x)+(x-10)R(x)$. Then $f_n$ has $-\frac{5}{6}$ as a root iff $R$ does. But if $n \geq 2$ then $f_{n-1}(0)=f_n(0)=5$, which means we must have $R(0)=2$. So $R(x)$ can't possibly have $-\frac{5}{6}$ as a root. I still don't see any way to rule out $-\frac{5}{2}$ (which your argument does not do; if $p=5$ and $q=-2$ then $p-10q=25$ is a factor of $65^k$ for $k \geq 2$).
Comment: The argument with the Descartes-sign rule is correct, but it is obvious without this rule that a polynomial with positive coefficients cannot have non-negative roots.
Comment: Oh, I forgot about $q=-2$! All right, thank you all for reminding me of that. However, my feeling is that we can get a trivial bound, from the fact that all coefficients are bounded by $10$, and the first and last are $6$ and $5$ respectively. I am not sure, but I'll look for some bounds and tell you.
Comment: Why is $p-10q$ coprime to $q^n$?
Comment: @i9Fn Because $\frac pq$ was assumed to be in lowest terms,  $p$ and $q^n$ don't share any common factors, then the proposition follows.
Answer: Let $f_n$ be the polynomial obtained from the digits of $65^n$. The other answer shows that if $p/q$ is a root of this polynomial in lowest terms, then $p-10q|65^n$; along with the bounds on $f_n$, this implies that we must have $p=-5$ and either $q=2$ or $q=6$. That is, the only possible rational roots are $-\frac{5}{6}$ and $-\frac{5}{2}$.
Note that $(6x+5)^n$ is also a polynomial which evaluates to $65^n$ at $x=10$. So we can write
$$
f_n(x)=(6x+5)^n+(x-10)R(x)
$$
for some polynomial $R$.
Setting $x=0$ in this expression, we have
$
5=5^n-10R(0)
$,
and so $R(0)=\frac{5^{n-1}-1}{2}$, which is not a multiple of $5$.
Now, suppose $n \geq 3$ and $x$ is either $-\frac{5}{6}$ or $-\frac{5}{2}$. Then $(6x+5)^n$ has $5$-adic valuation at least $3$ (that is, its numerator is a multiple of $5^3$ when it is written in lowest terms). In contrast, the $5$-adic valuation of $R(x)$ is $0$ (because the $5$-adic valuation of $R(0)$ is $0$) and $(x-10)$ is either $-\frac{5}{6}-10=-\frac{65}{6}$ or $-\frac{5}{2}-10=-\frac{25}{2}$, neither of which has $5$-adic valuation greater than $2$. So $(6x+5)^n$ and $(x-10)R(x)$ have unequal $5$-adic valuations, which means that $f_n(x)=(6x+5)^n+(x-10)R(x)$ cannot possibly be $0$.
It only remains to check that $f_2$ has no rational roots, which is an easy calculation.


The definition of a convex optimization problem

Question: I am trying to understand whether the following problem is a convex optimization problem:
\begin{align}
\min  1 \\
s.t. \\
& -x \le 0 \\
& -y \le 0 \\
& -xy \le 0,
\end{align}
The objective is constant, hence it is a convex function.
$-x$ and $-y$ are linear hence they are convex functions.
However, $-xy$ is neither convex nor concave.
According to Boyd's book on convex optimization, the definition of a convex optimization (Equation (1.8) in the book) requires that the objective and all functions above on the lhs of each inequality will all be convex.
So it appears that the above is not a convex optimization.
However, it seems to me that the feasible domain of the above problem is:
\begin{align}
& x \ge 0 \\
& y \ge 0, \\
\end{align}
which is a convex domain, hence intuitively, this should be a convex problem as it minimizes a convex objective over a convex domain.
Comment: There is nothing earth-shattering that would happen if you decide the convention should be "yes" or "no." That constraint $-xy\leq 0$ does not specify a convex subset of $\mathbb{R}^2$.  However, given the other constraints, that constraint is redundant and can be removed.  A computer that expects the convex program to be in standard form would likely want you to remove that constraint yourself, else it would give you an error.
Comment: Another example would be to minimize $-x$ subject to $x\leq 0$ and $x \in \{0,1\}$. This last "binary" constraint is nonconvex but the result of both constraints is the convex set consisting of one point.
Answer: This is a matter of definitions. Let us consider the problem
\begin{align*}
 \text{Minimize} \quad & f(x) \\
 \text{such that} \quad & g(x) \le 0.
\end{align*}
Here, $f : \mathbb{R}^n \to \mathbb{R}$, $g : \mathbb{R}^n \to \mathbb{R}^m$
and the inequality constraint $g(x) \le 0$ is considered coefficient-wise.
The feasible set is
\begin{equation*}
 \Omega = \{ x \in \mathbb{R}^n \mid g(x) \le 0\}.
\end{equation*}
Now, there are two notions of convexity for the above problem:

$f$ and all components of $g$ are convex.
$f$ and $\Omega$ are convex.

It is easy to see that
the first notion implies the second one
but note
vice-versa (see your example).
However, it is more reasonable to use the first definition,
since we are working explicitly
with the functions $g$.
Comment: Take $g(x) = x^3 - 1$, then $\{x : g(x) < 0\}$ is convex, yet $g$ is not convex. In optimization we like all  $g$ to be convex since then our nice theorems (like KKT) apply.
Comment: I understand that it is a matter of definition but a convex problem is a well established concept. Since the two possible definitions are NOT equivalent, there is some confusion.
I wonder if the inconsistency for the specific example above is only due to the fact that the third condition is redundant. In other words, assuming that there is a single inequality constraint g(x)<0, x \in R^n, is it true that the domain is convex if and only if g(x) is a convex function? Or can one find example of nonconvex g(x) such that g(x)<0 is still convex?
Comment: Thanks. That was a very useful simple example to illustrate what I wanted.
Comment: @gerw Could I have a question? I have the following nonlinear problem: $$\min f(x)\\g(x)\le 0\\h(x)=0.$$ I have found two definition of a convex problem in sources on the internet.

$1.$ Problem is convex if function $f$ and all components of $g$ are convex and all components of $h$ are affine.

$2.$ The feasible set $\{x\in\mathbb{R}^{n}:g(x)\le 0,h(x)=0\}$ is convex.

Of course $1$ implies $2$, but $2$ does not imply $1$.
This is clear, however which definition is correct, if they are not equivalent?
Comment: @gerw For example $$\min (x+2)^{2}+(y+2)^{2}$$ $$ xy\ge 4\\ x\le 4\\ y\ge 2.$$ According to the definition $1.$ it is not convex, because function $4-xy$ is not convex, but according to the definition $2.$ it is convex. I am confused with these diferent definitions. What is right? Thank you for your answer.
Answer: I must gently disagree with @Michael's first comment. There would certainly be a significant shift in what we could say about convex optimization problems if we relax the definition as the OP suggests we might: we suddenly would not be able to claim that convex optimization problems, as a class, are tractable.
The most important reason we study convex models is that, unlike the larger class of mathematical models, they admit a variety of tractable numerical methods for solving them. And if I'm going to get beyond a theoretical paper to the actual solution of a given class of problems, I'm going to need describe them in a computer-friendly manner. For instance, I might write code to compute the values and derivatives of the objective and constraint functions. I might express the problem in conic form and use a barrier or scaling point method. Or I could rely on a cutting plane oracle or barrier function to describe the constraint set.
But if I were start to allow any sort of constraint combination you wish, then the likelihood that I will find such a computational description drops considerably. Consider the constraint $x^2 \geq 1$---it has no cutting plane oracle, and its barrier method is not convex; heck, the set it describes isn't even connected. But wait, if I also happen to know that $x\geq 0$, then I still have a convex problem, right? Well, sure, but of course the first thing I will do is transform my problem into a solvable form by replacing $x^2\geq 1$ with $x\geq 1$. I'm back to my comfortable Boyd-convex domain.
Sure, there are going to be some examples where a "non-convex" description of the problem still admits a tractable solution method. But hopefully we would agree that exceptional cases do not provide a useful foundation on which to build an entire practice.


D: Creating an array of templated objects

Question: I'm trying to create an array of Regex objects, like so: Regex[] regexes;.
The compilation fails with main.d(46): Error: template std.regex.Regex(Char) is used as a type.
I find the documentation cryptic. All I understand is that templates generate code on compilation, but I don't see what's preventing me from creating an array of Regex.

There's an existing question on StackOverflow with the same problem, but it deals with C++, not D.
Answer: You cannot create a regex object without first instantiating the template with a type. this is because the actual type is generated at compile time based on the instantiation type you give. Regex itself is not an actual type, it is just a template function allowing you to generate a type when instantiated.
In this case you probably want to change:
Regex[] regexes;

into:
Regex!char[] regexes;

to tell the compiler that your regex contains chars as opposed to some derived type. This means specifically you are instantiating the Regex template with the type char.


Computing the Laplacian of $\frac{\mu\ \cdot\ \mathbf{r}}{\|\mathbf{r}\|^3}$

Question: How does one compute the Laplacian of
$$\dfrac{(\mathbf \mu \cdot \mathbf r)}{r^3} \;\; \text{where} \;\; r = \Vert \mathbf r \Vert?$$
I am aware that the Laplacian is defined to be $\Delta f=\sum_i \partial_i^2f$ but am a little confused about this computationally in this case.
I have got as far as saying $\partial_i^2[1/r^3(\mu_1r_1+\mu_2r_2+...+\mu_nr_n)]$, but don't know how to compute this.
Comment: Are you working in polar coordinates?
Comment: @danzimm I am not told. All I am told is that $\mu$ is in $R^3$
Comment: Well it would appear to be in spherical coordinates - in this case you can either convert to rectangular coordinates and then use the usual laplacian or you need to use the laplacian for spherical coordinates. More information can be found [here](http://en.wikipedia.org/wiki/Del_in_cylindrical_and_spherical_coordinates). (Sorry I misspoke at first, I meant to say spherical not polar)
Comment: Great @danzimm ! I'm still a little confused how I actually 'plug in' what I'm given to get the answer? Not really sure how it should look
Comment: If $\vec{\mu}$ is a constant vector, everything lives in $\mathbb{R}^3$ and you don't care what happens at the singularity $r = |\vec{x}| = 0$. You have $$\nabla^2 \left( \frac{\vec{\mu}\cdot \vec{x}}{r^3} \right) = - \nabla^2 \left( \vec{\mu} \cdot \vec{\nabla}\frac{1}{r} \right) = -\vec{\mu} \cdot \vec{\nabla} \left(\nabla^2 \frac{1}{r}\right) = -\vec{\mu} \cdot \vec{\nabla} 0 = 0$$
Answer: WARNING: GRAPHIC CONTENT! It's not going to be pretty as Joonas' answer (btw thank you for the correction!)
Let's do it in cartesian coordinates. The function is
\begin{equation}
u(x_1,\dots,x_n)=\frac{\sum_i\mu_ix_i}{\left(\sum_j x_j^2\right)^{3/2}}=\frac{\mu\cdot\mathbf{r}}{r^3}
\end{equation}
We have that
\begin{equation}
\frac{\partial\ r^s}{\partial x_k}=sx_k\ r^{s-2}
\end{equation}
and also
\begin{equation}
\frac{\partial\ (\mu\cdot\mathbf{r})}{\partial x_k}=\mu_k
\end{equation}
so,
\begin{equation}
\frac{\partial u}{\partial x_k}=\frac{\mu_kr^3-3x_kr(\mu\cdot\mathbf{r})}{r^6}=\frac{1}{r^5}\left(\mu_kr^2-3(\mu\cdot\mathbf{r})x_k\right)
\end{equation}
and
\begin{equation}
\frac{\partial^2 u}{\partial x_k^2}=
\frac{1}{r^{10}}\left[(2\mu_kx_k-3\mu_kx_k-3(\mu\cdot\mathbf{r}))r^5-5x_kr^3(\mu_kr^2-3(\mu\cdot\mathbf{r})x_k)\right]=\\
=\frac{1}{r^7}\left[-\mu_kx_kr^2-3(\mu\cdot\mathbf{r})r^2-5\mu_kx_kr^2+15(\mu\cdot\mathbf{r})x_k^2\right]=\\
=\frac{3}{r^7}\left[(\mu\cdot\mathbf{r})(5x_k^2-r^2)-2\mu_kx_kr^2\right]
\end{equation}
Summing everything over $k$ we get
\begin{equation}
\Delta u = \sum_k\frac{\partial^2u}{\partial x_k^2}=\frac{3}{r^7}\sum_k\left[(\mu\cdot\mathbf{r})(5x_k^2-r^2)-2\mu_kx_kr^2\right]=\\
=\frac{3}{r^7}\left[(\mu\cdot\mathbf{r})\sum_k(5x_k^2-r^2)-2r^2\sum_k\mu_kx_k\right]=\\
=\frac{3}{r^7}\left[(\mu\cdot\mathbf{r})(5r^2-nr^2)-2r^2(\mu\cdot\mathbf{r})\right]=\\
=3(3-n)\frac{(\mu\cdot\mathbf{r})}{r^5}
\end{equation}
Comment: There is an error in your third equation. When you differentiate $\sum_i\mu_i x_i$ with respect to $x_k$, you get $\mu_k$, not $\mu_kx_k$. This error then propagates through your calculations.
Comment: Thank you very much Joonas, now I'll correct everything!
Comment: How could this be solved by using instead spherical coordinates?
Answer: If you have two functions $f$ and $g$, then $\Delta(fg)=f\Delta g+g\Delta f+2\nabla f\cdot\nabla g$.
Now we obviously want to choose $f(x)=|x|^{-3}$ and $g(x)=\mu\cdot x$.
Recall that $\nabla |x|^\alpha=\alpha|x|^{\alpha-2}x$; to remember this rule, remember that the gradient is a vector and the formula should hold true in dimension one.
These choices give
\begin{eqnarray}
\nabla g(x)&=&\mu\\
\Delta g(x)&=&0\\
\nabla f(x)&=&-3|x|^{-5}x\\
\Delta f(x)&=&-3(\nabla|x|^{-5})\cdot x-3|x|^{-5}\text{div(x)}
\\&&\quad=15|x|^{-5}-3n|x|^{-5}
\\&&\quad=(15-3n)|x|^{-5},
\end{eqnarray}
whence
\begin{eqnarray}
\Delta(fg)
&=&
f\Delta g+g\Delta f+2\nabla f\cdot\nabla g
\\&=&
|x|^{-3}0+(\mu\cdot x)(15-3n)|x|^{-5}-6|x|^{-5}x\cdot\mu
\\&=&
(9-3n)|x|^{-5}\mu\cdot x.
\end{eqnarray}
Answer: There are basically two approaches to a problem like this; the first, to write out everything in terms of coordinates and simply grind away with the computation of all the requisite derivatives and so forth; the second, to as much as possible utilize standard and well-known identities satisfied by $\nabla$ to reduce the amount of such explicit calculation as much as possible; I generally prefer the second approach, since I feel it is usually cleaner, less work, more likely to yield easily understood results, and less likely to be error prone.  Hopefully, these notions are well-illustrated in the following.
Before proceeding, I must hand it to Joonas Ilmavirta for a particularly elegant solution based upon the formula $\nabla^2 (fg) = f\nabla^2 g + 2 \nabla f \cdot \nabla g + g\nabla^2 f$; very nice indeed, +1.  The calculations presented in the present answer do not make direct use of this identity; neither to they rely on single-coordinate-at-a-time calculation of $\nabla u$ and $\nabla^2 u$ as done so concisely by our other poster, marco trevi (and a +1 for that effort as well!).  Instead, I have tried in the following to use a small number of general identities satisfied by $\nabla$, and expressed in equations (3), (8), and (18); they are all easy to prove by resorting to Cartesian coordinates; also see here for more information.  By repeated application of such general formulas, the amount of direct calculation in a coordinate system is is substantially reduced; only (7), (12), and (28) are done in the $x_i$-system, and they are all relatively simple evaluations.
The following derivation might be a little long-winded, but I have tried to show every step in detail, including the derivation of $\nabla \vert \mathbf r \vert^\alpha = \alpha \vert \mathbf r \vert^{\alpha - 2} \mathbf r$, which is taken is given in Joonas Ilmavirta's argument.  In practice, once one is used to the method, working as much as possible with higher-level, abstract entities such as $r$ etc. (rather than $\sqrt{\sum x_i^2}$), generally proves to involve less work.
Incidentally, as anyone who reads this post will soon discover, I took the liberty of performing the calculations for the slightly more general case
$\nabla^2 (\dfrac{\mu \cdot \mathbf r}{r^m}), \tag{0}$
where I take $0 \ne m \in \Bbb R$.
Having typed on enough, I present:
Setting
$\phi = \dfrac{\mu \cdot \mathbf r}{r^m}, \tag{1}$
and noting that
$\nabla^2 \phi = \nabla \cdot \nabla \phi, \tag{2}$
we first compute $\nabla \phi$ making use of the product rule for gradients:
$\nabla(fg) = f\nabla g + g\nabla f, \tag{3}$
which we apply to (1), thus:
$\nabla (\dfrac{\mu \cdot \mathbf r}{r^m}) = \dfrac{1}{r^m} \nabla (\mu \cdot \mathbf r) + (\mu \cdot \mathbf r) \nabla(\dfrac{1}{r^m}); \tag{4}$
we evaluate the gradients occurring in (4):  first, it is easy to see that
$\nabla (\mu \cdot \mathbf r) = \mu; \tag{5}$
since
$\mu \cdot \mathbf r = \sum_1^n \mu_i x_i, \tag{6}$
we have
$\dfrac{\partial}{\partial x_j}\mu \cdot \mathbf r = \mu_j; \tag{7}$
(5) follows directly from (7).  As for the second term in (4), we may use the formula
$\nabla (f(g)) = \dfrac{df}{dg} \nabla g, \tag{8}$
where $g:\Omega \to \Bbb R$ and $f:\Bbb R \to \Bbb R$, $\Omega \subset \Bbb R^n$ being some open set.  Like (3), (8) may also be verified one coordinate at at time, using the chain rule:
$\dfrac{\partial}{\partial x_j}f(g) = \dfrac{df}{dg} \dfrac{\partial f}{\partial x_j}, \; \; 1 \le j \le n; \tag{9}$
(8) follows readily from (9).  Thus
$\nabla (\dfrac{1}{r^m}) = \dfrac{d(r^{-m})}{dr} \nabla r = -\dfrac{m}{r^{m + 1}} \nabla r. \tag{10}$
It is easy to compute $\nabla r = \nabla \Vert \mathbf r \Vert$, again using (8):
$\nabla r = \nabla \Vert \mathbf r \Vert = \nabla \langle \mathbf r, \mathbf r \rangle^{1/2} = \dfrac{1}{2}\langle \mathbf r, \mathbf r \rangle^{-1/2} \nabla \langle \mathbf r, \mathbf r \rangle; \tag{11}$
but
$(\nabla \langle \mathbf r, \mathbf r \rangle)_j = \dfrac{\partial}{\partial x_j}\sum_1^n x_i^2 = 2x_j, \tag{12}$
which shows that
$\nabla \langle \mathbf r, \mathbf r \rangle = 2\mathbf r; \tag{13}$
thus (11) becomes
$\nabla r = \dfrac{1}{2}\langle \mathbf r, \mathbf r \rangle^{-1/2} (2 \mathbf r) = \dfrac{\mathbf r}{r}, \tag{14}$
which is the unit vector field in the radial direction, in the direction of $\mathbf r$.  In any event, (10) and (14) combined yield
$\nabla (\dfrac{1}{r^m}) = -\dfrac{m}{r^{m + 1}} \dfrac{\mathbf r}{r} = -\dfrac{m}{r^{m + 2}} \mathbf r, \tag{15}$
and bringing together (5) and (15) into (4) we find
$\nabla (\dfrac{\mu \cdot \mathbf r}{r^m}) = \dfrac{\mu}{r^m}  - \dfrac{(m\mu \cdot \mathbf r)}{r^{m + 2}} \mathbf r. \tag{16}$
Having $\nabla \phi$, we proceed to calculate $\nabla^2 \phi$ as follows:
$\nabla^2 \phi = \nabla \cdot \nabla \phi = \nabla \cdot (\dfrac{\mu}{r^m} - \dfrac{m\mu \cdot \mathbf r}{r^{m + 2}} \mathbf r) = \nabla \cdot (\dfrac{\mu}{r^m}) - \nabla \cdot (\dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}\mathbf r). \tag{17}$
Each of the terms on the right of (17) is of the form $\nabla \cdot (fX)$, where $f$ is a function and $X$ is a vector field on $\Bbb R^n$; for such expressions, we have in general
$\nabla \cdot (fX) = X \cdot \nabla f + f \nabla \cdot X. \tag{18}$
(18) may be verified, as may (3) and (8), by writing out each side in a Cartesian coordinate system.  Applying (18) to (17), we have
$\nabla \cdot (\dfrac{\mu}{r^m}) = \mu \cdot \nabla(\dfrac{1}{r^m}) + \dfrac{1}{r^m} \nabla \cdot \mu; \tag{19}$
now
$\nabla \cdot \mu = 0, \tag{20}$
since $\mu$ is constant; from (15),
$\mu \cdot \nabla(\dfrac{1}{r^m}) = -\dfrac{m \mu \cdot \mathbf r}{r^{m + 2}}, \tag{21}$
so that
$\nabla \cdot (\dfrac{\mu}{r^m}) = -\dfrac{m \mu \cdot\mathbf r}{r^{m + 2}}. \tag{22}$
Next,
$\nabla \cdot (\dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}\mathbf r) = \mathbf r \cdot \nabla (\dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}) +  (\dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}) \nabla \cdot \mathbf r; \tag{23}$
we compute, in a manner similar to the above:
$\nabla (\dfrac{\mu \cdot \mathbf r}{r^{m + 2}}) = \dfrac{1}{r^{m + 2}} \nabla (\mu \cdot \mathbf r) + (\mu \cdot \mathbf r) \nabla (\dfrac{1}{r^{m + 2}}), \tag{24}$
by (3); again using (8) and (14), we see in a manner similar to (15) that
$\nabla (\dfrac{1}{r^{m + 2}}) = -\dfrac{m + 2}{r^{m + 3}} \nabla \mathbf r = -\dfrac{m + 2}{r^{m + 3}} \dfrac{\mathbf r}{r} = -\dfrac{m + 2}{r^{m + 4}} \mathbf r. \tag{25}$
Using (5) and (25), (24) becomes
$\nabla (\dfrac{\mu \cdot \mathbf r}{r^{m + 2}}) = \dfrac{\mu}{r^{m + 2}} - \dfrac{(m + 2)\mu \cdot \mathbf r}{r^{m + 4}} \mathbf r, \tag{26}$
whence
$m\mathbf r \cdot \nabla (\dfrac{\mu \cdot \mathbf r}{r^{m + 2}}) = \dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}  - \dfrac{m(m + 2)\mu \cdot \mathbf r}{r^{m + 4}} \mathbf r \cdot \mathbf r = \dfrac{m\mu \cdot \mathbf r}{r^{m + 2}} - \dfrac{m(m + 2)\mu \cdot \mathbf r}{r^{m + 4}}r^2$
$= \dfrac{(m - m^2 - 2m)\mu \cdot \mathbf r}{r^{m + 2}} = -\dfrac{m(m + 1)\mu \cdot \mathbf r}{r^{m + 2}}. \tag{27}$
We also have
$\nabla \cdot \mathbf r = \sum_1^n \dfrac{\partial x_j}{\partial x_j} = \sum_1^n 1 = n, \tag{28}$
whence
$m(\dfrac{\mu \cdot \mathbf r}{r^{m + 2}}) \nabla \cdot \mathbf r = \dfrac{mn \mu \cdot \mathbf r}{r^{m + 2}}. \tag{29}$
And lo! by virtue of (27) and (29), (23) has turned into
$\nabla \cdot (\dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}\mathbf r) =  -\dfrac{m(m + 1)\mu \cdot \mathbf r}{r^{m + 2}} + \dfrac{mn \mu \cdot \mathbf r}{r^{m + 2}} = \dfrac{(mn - m(m + 1))\mu \cdot \mathbf r}{r^{m + 2}}. \tag{30}$
We finally assemble the components we have built so far into the framework of (17); from (22) and (30) we have
$\nabla^2 \phi = \nabla \cdot (\dfrac{\mu}{r^m}) - \nabla \cdot (\dfrac{m\mu \cdot \mathbf r}{r^{m + 2}}\mathbf r)$
$=  -\dfrac{m \mu \cdot\mathbf r}{r^{m + 2}} -  \dfrac{(mn - m(m + 1)\mu \cdot \mathbf r}{r^{m + 2}} = \dfrac{(m^2 - mn)\mu \cdot \mathbf r}{r^{m + 2}}. \tag{31}$
If we take $m = 3$, (31) agrees with the results of marco trevi and Joonas Ilmavirta.


Which binomial confidence interval is correct?

Question: Background: I am working with a data set that requires a transformation. It's prevalence data so I have proportions to deal with, and as the proportions are quite low, I'm using the Freeman-Tukey transformation. My aim is to perform a meta analysis on the prevalence data.
I have transformed the proportions, and found confidence intervals using the transformed data.
I have a forest plot with CIs calculated exactly, and another with CIs calculated after a backtransformation. The largest difference between the two sets is 0.07, so they are very similar.
My issue is deciding whether I should be reporting the exact confidence intervals, or those that have been back transformed. There are ten studies in my data, so an approximation is not appropriate.
Question: In order to gain the correct confidence intervals, do I have to perform a back transformation?
I currently have two sets of answers and I'm not sure of the correct method.
Example: Let's say I have a proportion: 123/9876.
(1) In calculating the exact CIs without transformation, I get:
p=0.01245443; LB=0.01036126; UB=0.01484199

(2) After transforming the original data, and using (p-z*SE(p), p+z*SE(p)), where SE(p)=sqrt(1/(n+0.5)),  I get:
p=0.224109; LB=0.2043868; UB=0.2438312

(3) Back transforming gives:
p=0.01245443; LB=0.01035768; UB=0.01474083

But which of these three results is correct?
Comment: See this great answer: http://stats.stackexchange.com/questions/82720/confidence-interval-around-binomial-estimate-of-0-or-1
Comment: 123/4321 is not 0.01245443.
Comment: Apologies, I initially used an example with 4321 but decided I wanted to make the proportion smaller to make it clear that I was using the Freeman-Tukey transformation. I have edited it now.
Comment: In my real example, I have a forest plot with CIs calculated exactly, and another with CIs calculated after a backtransformation. The largest difference between the two sets is 0.07, so they are very similar. My issue is deciding whether I should be reporting the exact confidence intervals, or those that have been back transformed. There are ten studies in my data, so an approximation is not appropriate.
Answer: The Wilson score interval is a simple and accurate confidence interval for the binomial proportion parameter, that automatically adjusts near the boundaries of the range.  The coverage properties of various intervals have been examined in Brown, Cai and DasGupta (2001) and this is one of the intervals they recommend as having good coverage properties.
The interval is constructed as follows.  Suppose you observe $N_1$ "successes" and $N_0$ "failures" giving a total of $n=N_0+N_1$ data points.  The Wilson score interval uses the normal approximation to give the following pivotal quantity:
$$\frac{(N_1 - n \theta)^2}{n\theta (1-\theta)} \overset{\text{Approx}}{\sim} \text{ChiSq}(1),$$
Letting $\chi_{\alpha}^2$ denote the critical point (upper tail area of $\alpha$) of the chi-squared distribution with one degree-of-freedom, and solving the resulting quadratic inequality for $\theta$, then gives the probability interval:
$$\begin{align}
1-\alpha
&\approx \mathbb{P} \Bigg( (N_1 - n \theta)^2 \leqslant n \theta (1-\theta) \cdot \chi_{\alpha}^2 \Bigg) \\[6pt]
&= \mathbb{P} \Bigg( \theta \in \Bigg[ \frac{2N_1 + \chi_{\alpha}^2}{2n + \chi_{\alpha}^2} \pm \frac{n \chi_{\alpha}}{n + \chi_{\alpha}^2} \sqrt{\frac{N_0 N_1}{n} + \frac{\chi_{\alpha}^2}{4}} \Bigg] \Bigg). \\[6pt]
\end{align}$$
Substitution of the observed values of $n_0$ and $n_1$ then gives the resulting confidence interval.  This confidence interval is implemented in various functions.  You can implement this interval in R using the CONF.prop function from the stat.extend package.  Here is the interval you get with your data:
#Compute confidence interval using Wilson-score method
library(stat.extend)
CONF.prop(alpha = 0.05, sample.prop = 123/9876, n = 9876)

Confidence Interval (CI)

95.00% CI for proportion parameter for infinite population
Interval uses 9876 binary data points with sample proportion = 0.0125

[0.0104489771546811, 0.0148390256803883]

Answer: You need to report the back-transformed ones. This is because the original proportions are very small, you need to transform them and then transform them back into proportions.


How to find UIKeyboard Notifiactions outside of our app(app running in background)...........?

Question: I want to know if user using keyboard outside,when my app running in background.?
I have to know whether user sending a text message using default Messaging app in iPhone.
I  tried in this way:

By using Keyboard we can send Text Messages(80%),when ever user presses any key in keyboard outside of our app how we can know?.

I searched a lot,i found with in the app by using UIKeyboardWillShowNotification, but when app running in background?
Please Share Answer if any....!
Thanks In Advance.
Comment: why on the Earth are you interested in when any other application uses the keyboard? that is their private thing, as your app's personal issue when you use the keyboard, no one has to access the typed information.
Comment: Thanks For Your Reply, Is there any way to find whether user texting while driving through Default Message App in iPhone,please help to find is there any way for this....?
Answer: I think it is not possible because when your app is running in background mode it does not execute any code from you application.
Only some limited tasks/background modes are supported.
Please check following link for more information: https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3.
Comment: This documentation refers to iOS 7, I believe, whereas the OP's query regards the unreleased iOS 8.
Comment: Thanks For Your Reply, Is there any way to find whether user texting while driving through Default Message App in iPhone,please help to find is there any way for this....?
Answer: App can only listen the Keyboard notification only when the app is in running state and notification is with in the app only in ios.
However there are the notifications in OS X, an application can listen the keyboard notification outside the app.
Comment: Thanks For Your Reply, Is there any way to find whether user texting while driving through Default Message App in iPhone,please help to find is there any way for this....?
Answer: This isn't possible. According to Apple's documentation:

While an extension is running, it communicates directly only with the
  host app. There is no direct communication between a running extension
  and its containing app; typically, the containing app isn't even
  running while its extension is running. In addition, the containing
  app and the host app don't communicate at all.

You can request network access for your keyboard, but my guess is that most people would refrain from downloading any keyboard that has the capacity to log their keystrokes.
Comment: Thanks For Your Reply, Is there any way to find whether user texting while driving through Default Message App in iPhone,please help to find is there any way for this....?
Comment: No. Your custom keyboard cannot interact with the host application, so you can't know what application the user is currently interacting with. This may be possible for jailbroken iPhones, but you cannot currently do this using a custom keyboard distributed through the App Store.
Comment: Is there any way to find whether user ,texting or not by using Default Message app?
Comment: No. You cannot hook into the default messaging app.
Comment: Is there any other way to find that texting?
Comment: I'm sorry Krishna Stv. You cannot achieve this on a standard iOS installation.


Fields UI export to code for editing?

Question: I am creating a new registration form with the Fields UI module and need to
be able to add variable_get instances for username, email, etc and also add
select lists for birthday info, typical drop downs like range(1,12), range(1,31),
and range(2015,2012). I'm having trouble trying to figure out how to do this,
or how to put preset variables into my fields. Can I dump this and edit it
myself, or can I put in what I need?
EDIT
I found out that I can use list(int) then select widget type select list to create
select boxes, BUT I still cannot assign things known variables.
To further this along, lets say I have I have $variables['bio']['firstName'], I
am trying to assign name_bio_firstName to the field for name, if that doesn't confuse
anyone more.
Answer: You can export it with Features module. Basically it creates a new module which you download and plug into modules folder. There you can further edit it's code.

Fields UI export to code for editing?


Objective-c update NSTextField at ControllerView init

Question: @interface TestViewController : NSViewController
@property (nonatomic, retain) IBOutlet NSTextField *myLabel;

- (IBAction)sendMessage:(NSButton *)sender;

@end

@implementation TestViewController
@synthesize myLabel = _myLabel;

- (id)init{
    self = [super init];
    if(self){
        [self updateLabel];
    }
    return self;
}

- (IBAction)sendMessage:(NSButton *)sender {
    [self updateLabel];
    NSLog(@"Message sent");
}

- (void) updateLabel{
    NSLog(@"Update!! %@");
    [self.myLabel setStringValue:@"random text"];
}

@end

I want to update an NSTextField when view is displayed, and i put my updateLabel at init in the log i see Update!! but the NSTextField it's not update with my text.
But when i press the button that calls the same updateLabel the NSTextField is updatet. Can someone help me to understand why it's not working as expected ?
Comment: Did you try putting a log statement in your init method to make sure it's being called?
Comment: i said that at `init` this is printed out `NSLog(@"Update!! %@");` but text in the field is the same
Comment: Sorry, missed that.  It could be that doing this in an init method is too early in the process.  How are you loading the view controller's view?  Are you implementing loadView?  If so, try putting the call to updateLabel in there.
Comment: thank you `loadView` did the job :D
Answer: I follow the suggestion of @rdelmar to use loadView. Thank you.
And here is how to implement it if anyone interested.
- (void)loadView
{
    [super loadView];
    [self updateLabel];
}


Do I ever have to decrypt S3-encrypted files?

Question: I'm using S3 instead of KMS to store essentially a credentials file, and Python to read the file's contents.
I manually set the file encrypted by clicking on it in S3, going to Properties - Details - Server Side Encryption:AES-256
And in my Python script, I read the key without making changes from when I read the file when it was unencrypted. And I was also able to download the file and open it without having to do anything like decrypting it. I was expecting to have to decrypt it, so I'm a little confused.
I'm just unable to understand what server-side encryption protects against. Would anyone already with access to S3 or the S3 bucket with the key/file be able to read the file? Who wouldn't be able to open the file?
Answer: The "server-side" encryption you have enabled turns on encryption at rest. Which means the file is encrypted while it's sitting on S3. But S3 will decrypt the file before it sends you the data when you download the file.
So there is no change to how you handle the file when downloading it if the file is encrypted or not.
This type of encryption does not protect the file if the file is downloaded via valid means, such as when using the API. It only protects the file from reading if someone were to circumvent the S3 data center or something like that.
If you need to protect the file, such that it must be decrypted when downloaded, then you need to encrypt it client-side, before uploading it to S3.
You can use any client-side encryption scheme you deem worthy: AES256, etc. But S3 won't do it for you.
Comment: Thanks for the clarification. I uploaded a file onto S3 using a key I just made, downloaded it, and was able to view it. Is this normal? Did S3 decrypt it before it sent me the file for downloading?
Comment: If you encrypt it before uploading, then YOU must decrypt it after downloading it. S3 will not do it for you. If you are using S3 server-side encryption, then S3 will decrypt the file before it sends you the data. You can actually do both: client-side encryption, and server-side encryption. S3 will still decrypt the server-side encryption for you before giving the data, but you'll need to further decrypt the client-side yourself.
Answer: That is server side, means it will be encrypted on the server (in the data center so  the can't see it), but if anyone having the authority to get the object, they can see.
What you might be looking for is Client Side Encryption. You can you pythons this library as example. Just encrypt using that, then send it off to s3.


Mori's "projective manifolds with ample tangent bundles", Proposition 3

Question: See http://www.jstor.org/stable/1971241?seq=6#page_scan_tab_contents, pages 597 and 598.
At the bottom of page 597, we get the following diagram:
$\begin{array}{ccccccccc}
A/I & \xrightarrow{nat.} & A/(I+M^n) \\
  & {\alpha}\searrow & \uparrow nat. \\
 &  & A/(MI+M^n+(r_1,...,r_a))
\end{array}$
where the $r_i$ are in $I+M^n$. $A$ is a formal power series ring over $k$ and $M$ its maximal ideal. $I \subset M^2, I\cap M^n = M(I\cap M^{n-1}) \subset MI$ (for some n, following from the Artin-Rees lemma). I am not sure how much context is required, so for now I will refer to the link for more. Do feel free to ask.
The crucial claim, on which the entire argument seems to rely, is that "since $I \subset M^2$, $\alpha$ is surjective by the above diagram." The following part of the proof is then a mere formality.
Why is $\alpha$ surjective? This seems not at all as obvious as the statement of the claim makes it sound. I believe thus that I am completely missing something critical.
For what it is worth, I am not yet familiar enough with obstruction theory. Maybe this is where the crux lies (see the linked paper, on the same page)? If so, I would appreciate some pointers on where to educate myself about this.
Comment: Is $$\alpha$ some lift of $A$-modules, making the diagram commutative?
Comment: Yes. It come from an extension of scheme morphisms obtained in the paragraph above.
Comment: Do you know Nakayama's lemma?
Comment: Yes. Not yet seeing how to apply it though. Let me take a look...
Comment: I don't see it, especially what the fact $I \subset M^2$ has to do with it. Note that we do not know that the $r_i$ generate $I$; in fact this is the goal of the proof.
Answer: So finally here it is. Let $B:= (MI+M^n+(r_1+\cdots +r_a))$ and write $I_B$ for $IB$. For $a \in B, \sigma\circ\pi(a) = a+\bar a,$where $\bar a \in I_B$, $\pi$ is the natural map from $B$ to $B/I_B = A/(I+M^n)$, and $\sigma$ is a section from $B/I_B$ to $B$ obtained by restricting $A/I\xrightarrow{\alpha}B$ to $A/(I+M^n)$.
Now let $a,b \in \mathfrak m_B \subset B$. Then $\sigma\circ\pi(ab) \in ab + \mathfrak m_BI_B +I_B^2.$ In particular, $I_B\subset \mathfrak m_B^2 \subset \mathfrak m_BI_B$. Now, at this point one could invoke Nakayama's lemma to point out that $I_B = 0$, but the containment itself is actually enough for us to see that $\alpha$ is surjective ($MI=0$ in $B$), and $I$ is generated by at most $a$ elements.
Note that in the proof we can actually save us some hassle by not using "$+M^n$".

Mori's “projective manifolds with ample tangent bundles”, Proposition 3


Django filter in ModelForm with specific models

Question: class Report(models.Model):
    # ....
    product = models.ForeignKey(Product)

class Product(models.Model):
    name = models.CharField(max_length=50)

class Item(models.Model):
    box = models.ForeignKey(BoxInTransport)
    product = models.ForeignKey(Product)

class BoxInTransport(models.Model):
    transport = models.ForeignKey(Transport)
    box = models.ForeignKey(Box)

This is - in short - the structure of models.
And I have a view which lets me create new report:
class ReportCreateView(CreateView):
    model = Report
    form_class = ReportForm

    def get_form_kwargs(self):
        # updating to get argument from url
        kwargs = super(DifferenceCreateView, self).get_form_kwargs()
        kwargs.update(self.kwargs)
        return kwargs

and the form:
class ReportForm(ModelForm):
    class Meta:
        model = Report
        fields = [
            'product'
        ]

    def __init__(self, box_nr=None, *args, **kwargs):
        super(ReportForm, self).__init__(*args, **kwargs)

        self.fields['product'].queryset = ???

How can I get only these products which belong to a specific box? To be more clear:
Only products which:
Item.objects.filter(box__box__box_code=box_nr)

Now I get all Items which I need, but I need to pass self.fields['products']  to only product form with this new Items queryset.
Can you help me?
EDIT
I've tried something like this:
 def __init__(self, box_nr=None, *args, **kwargs):
    super(ReportForm, self).__init__(*args, **kwargs)
    queryset = Item.objects.filter(
        box__box__box_code=boxno
    )
    none_queryset = Product.objects.none()
    list_or_products = [p.product for p in queryset]
    product_queryset = list(chain(none_queryset, list_or_products))
    self.fields['product'].queryset = product_queryset

But, first - it looks little ugly :), second - it doesn't work:
AttributeError: 'list' object has no attribute 'all'

Comment: Your table structure doesn't make much sense. Why is it that `Item` has a ForeignKey to `BoxInTransit` **and** `BoxInTransit` has a foreignkey to `Item`?
Answer: Your __init__ could look something like this:
def __init__(self, box_nr=None, *args, **kwargs):
    super(ReportForm, self).__init__(*args, **kwargs)

    qs = Product.objects.filter(item__box__box__box_code=box_nr)
    self.fields['product'].queryset = qs

Basically, you need a reverse lookup on Product to Item. You can read the relevant documentation here
Note that: item__box__box__box_code=box_nr is based on my understanding of your models. item__box does the reverse lookup. Rest might need some tweaking based on your model definitions.
Comment: I added releated_name to product filed in Item model. And then: qs = Product.objects.filter(item__box__box__box_code=box_nr). But this gave me an error: Related Field got invalid lookup: box
Comment: Then use the related name you used in the reverse lookup.
Comment: I added related_name = 'item' :)
Comment: This is what do you mean?
Comment: sure, Your reverse relationship would have been `item` anyways.