a += b not the same as a = a + b

Question:
Possible Duplicate:
Why does += behave unexpectedly on lists?

I found an interesting "feature" of the python language today, that gave me much grief.
>>> a = [1, 2, 3]
>>> b = "lol"
>>> a = a + b
TypeError: can only concatenate list (not "str") to list
>>> a += b
>>> a
[1, 2, 3, 'l', 'o', 'l']

How is that? I thought the two were meant to be equivalent! Even worse, this is the code that I had a hell of a time debugging
>>> a = [1, 2, 3]
>>> b = {'omg': 'noob', 'wtf' : 'bbq'}
>>> a = a + b
TypeError: can only concatenate list (not "dict") to list
>>> a += b
>>> a
[1, 2, 3, 'omg', 'wtf']

WTF! I had lists and dicts within my code, and was wondering how the hell I ended up appending the keys of my dict onto a list without ever calling .keys(). As it turns out, this is how.
I thought the two statements were meant to be equivalent. Even ignoring that, I can kind of understand the way you append strings onto lists (since strings are just character arrays) but dictionaries? Maybe if it appended a list of (key, value) tuples, but grabbing only the keys to add to the list seems completely arbitrary.
Does anyone know the logic behind this?
Comment: If it's in every python tutorial, I have not seen it, and i've been working with python for the last year, written a Compiler and a Website in it and have spent what must be far too much time reading up random blurb about the features and deficiencies of python. I honestly never read this, or expected this behavior. I do not think "Mutable Sequence" is an obvious place to look for the fact that += is a separate operator from +, and in skimming the page again i did not see it at all. Searching "+=" gave me nothing useful. I don't think this behavior is as obvious as you think!
Comment: This question was closed as a duplicate, but I'm not sure it is - the answer may be the same, but the question seems different.
Comment: Wow, this behaviour just cost me multiple hours debugging. Good to know, but now I'm left with the question: Why? Why on all the earth would python do that?
Comment: This question has been asked other times too, even in the last few days, in other forms.
Answer: This is and always has been a problem with mutability in general, and operator overloading specifically.  C++ is no better.
The expression a + b computes a new list from the objects bound to a and b, which are not modified.  When you assign this back to a, you change the binding of one variable to point to the new value.  It is expected that + is symmetrical, so you can't add a dict and a list.
The statement a += b modifies the existing list bound to a.  Since it does not change the object identity, the changes are visible to all bindings to the object represented by a.  The operator += is obviously not symmetrical, it is equivalent to list.extend, which iterates over the second operand.  For dictionaries, this means listing the keys.
Discussion:
If an object doesn't implement +=, then Python will translate it into an equivalent statement using + and =.  So the two are sometimes equivalent, depending on the type of the objects involved.
The benefit of a += that mutates the referand (as opposed to the operand value, which is a reference) is that the implementation can be more efficient without a corresponding increase in implementation complexity.
In other languages, you might use more obvious notation.  For example, in a hypothetical version of Python with no operator overloading, you might see:
a = concat(a, b)

versus
a.extend(a, b)

The operator notation is really just shorthand for these.
Bonus:
Try it with other iterables too.
>>> a = [1,2,3]
>>> b = "abc"
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> a += b
>>> a
[1, 2, 3, 'a', 'b', 'c']

It's useful to be able to do this, because you can append a generator to a list with += and get the generator contents.  It's unfortunate that it breaks compatibility with +, but oh well.
Comment: Here's another related [pitfall](http://zephyrfalcon.org/labs/python_pitfalls.html): `t = ([],); t[0] += [2, 3]`. The second statement will raise an exception, but afterwards, `t` is `([2, 3],)` even so.
Comment: I don't know what you mean by "other iterables", this was the first example in his question?
Comment: C++ absolutely is better. In C++, if `x` is of a mutable type that supports `+` (such as `std::string`) then `x += expr` always has the same meaning as `x = x + expr`, except that it may be more efficient. Of course you can overload `+=` in your own classes to do anything, but none of the standard library types behave in the crazy way that Python's do.
Comment: @benrg: It is absolutely incorrect to say that in C++, `x += y` always has the same meaning as `x = x + y`.
Comment: I gave an example where it has the same meaning; can you give an example where it has a different meaning?
Comment: They are separately defined, you are free to define them how you wish. Just like Python. In Python, they are also separate operators, which can both be independently defined how you wish.
Comment: @benrg: This is not the right place for an extended discussion about C++, however.
Comment: @benrg: In the standard library, the `std::atomic` type has `+=` defined, but not `+`.
Answer: The reason behind this is because the python lists (a in your case) implement the __iadd__ method, which in turns calls the __iter__ method on the passed parameter.
The following code snippet illustrates this better:
class MyDict(dict):
    def __iter__(self):
        print "__iter__ was called"
        return super(MyDict, self).__iter__()

class MyList(list):
    def __iadd__(self, other):
        print "__iadd__ was called"
        return super(MyList, self).__iadd__(other)

a = MyList(['a', 'b', 'c'])
b = MyDict((('d1', 1), ('d2', 2), ('d3', 3)))

a += b

print a

The result is:
__iadd__ was called
__iter__ was called
['a', 'b', 'c', 'd2', 'd3', 'd1']

The python interpreter checks if an object implements the __iadd__ operation (+=) and only if it doesn't it will emulate it by doing a add operation followed by an assignment.

a += b not the same as a = a + b


Best place to include javascript in a field formatter?

Question: I've created a custom field formatter using hook_field_formatter_info() and implemented it using hook_field_formatter_view().
My formatter requires additional javascript though and at the moment I'm including it in hook_field_formatter_view() but I have a feeling there's gotta be a better place to do this.
However there is no hook_field_formatter_preprocess() (there is a formatter_prepare_view() though but it doesnt't seem right)
Any ideas?
Answer: Adding the JavaScript in hook_field_formatter_view() works just fine. Just also be sure to use #attached and not drupal_add_js() since that way your file is included in the render cache.
<code>function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    $element[$delta] = // Blah blah blah add output for each $items in $element as a render array.
  }

  // Add the JavaScript file.
  $element['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/mymodule.field.js;

  return $element;
}
</code>
Comment: Since I was calling a theme function in the formatter_view() anyway I just moved the include js part to hook_preprocess_hook(), this is great know to know though!
Comment: can we add css also in the same way?  `$element['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/mymodule.field.css;`


Consider $(a_n+b_n\sqrt2)=(1+\sqrt2)^n$, prove these statements

Question: We define the sequences $a_n$ and $b_n$ as $(a_n+b_n\sqrt2)=(1+\sqrt2)^n$. The exercise has those:
a) Calculate the limit as n tends to infinity of $a_n/b_n$.
b) Calculate $S_1=\sum_{i=1}^{n}(1+\sqrt2)^i$, $S_2=\sum_{i=1}^{n}a_i$, $S_3=\sum_{i=1}^{n}b_i$ for any $n\in \mathbb{N}$ and find the limit as $n$ tends to infinity of $\frac{S_2}{S_3}$
c) Prove that there are unique $c,d\in\mathbb{Z}$ such that $a_{n+2}= ca_{n+1} +da_{n}$ and $b_{n+2}= cb_{n+1} +db_{n}$ for any $n\in \mathbb{N}$.
I am having a lot of trouble dealing with those, some help?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: Hint : multiplication by $1 + \sqrt{2}$ is a linear transformation on $\mathbb{Q}(\sqrt(2))$ as a vector space over $\mathbb{Q}$. Find its matrix representation.
Comment: [A closely related thread](https://math.stackexchange.com/q/1869954/11619). Many of the same calculations have been carried out there, but not all. I'm not gonna call it a duplicate, as there are differences in focus. Would not be kosher for me to vote that way anyway, as I happened to answer the other one. However, see Zev Chonoles's answer for the recurrence formulas.
Comment: Thanks, for the comments!! For the last part of the exercise I saw really usefull the comment of Sawarnik on the thread u linked.
Answer: Since $\{a_n\},\{b_n\}$ are increasing, you can prove that
$$\lim_{n\to\infty}a_n=\lim_{n\to\infty}b_n=\infty. $$
From $a_n^2-2b_n^2=(-1)^n$, you have
$$ \bigg(\frac{a_n}{b_n}\bigg)^2=2-\frac{(-1)^n}{b_n^2}$$
which implies
$$ \lim_{n\to\infty}\bigg(\frac{a_n}{b_n}\bigg)^2=2$$
or
$$ \lim_{n\to\infty}\frac{a_n}{b_n}=\sqrt2.$$
So c) is done.
Clearly
$$ S_1=\sum_{i=1}^n(a_i+b_i\sqrt2)=S_2+S_3\sqrt2=\frac{\sqrt2}2(1+\sqrt2)((1+\sqrt2)^n-1).\tag1$$
It is easy to see
$$ S_2-S_3\sqrt2=-\frac{\sqrt2}2(1-\sqrt2)((1-\sqrt2)^n-1).\tag2$$
From (1) and (2), you have
\begin{eqnarray}
S_2=\frac{\sqrt2}4\bigg[(1+\sqrt2)((1+\sqrt2)^n-1)-(1-\sqrt2)((1-\sqrt2)^n-1)\bigg]\\
S_3=\frac{1}4\bigg[(1+\sqrt2)((1+\sqrt2)^n-1)+(1-\sqrt2)((1-\sqrt2)^n-1)\bigg]
\end{eqnarray}
and hence
$$ \lim_{n\to\infty}\frac{S_2}{S_3}=\lim_{n\to\infty}\frac{\sqrt2\bigg[(1+\sqrt2)((1+\sqrt2)^n-1)-(1-\sqrt2)((1-\sqrt2)^n-1)\bigg]}{(1+\sqrt2)((1+\sqrt2)^n-1)+(1-\sqrt2)((1-\sqrt2)^n-1)}=\sqrt2. $$
So d) is done. It should be easy to get e).
Comment: You are right. I changed it.
Comment: Great answer, thank you so much. However, am I mistaking something or the expressions of $S_2$ and $S_3$ should be $S_2=\frac{\sqrt2}4\bigg[(1+\sqrt2)((1+\sqrt2)^n-1)-(1-\sqrt2)((1-\sqrt2)^n-1)\bigg]$ and $S_3=\frac{1}4\bigg[(1+\sqrt2)((1+\sqrt2)^n-1)+(1-\sqrt2)((1-\sqrt2)^n-1)\bigg]$.


Prove that f(x) is not continuous and differentiable at any point. Find Riemann sums.

Question: I would like some feedback and help on the following homework    problem for Real Analysis.
Consider the function f : $\mathbb{R}$ → $\mathbb{R}$ given by
$$
f(x) =
\begin{cases}
\lfloor x\rfloor, & x\ \text{is rational},\\
\lfloor x\rfloor+3, & x\ \text{is irrational}
\end{cases}
$$
where $\lfloor x\rfloor$ is the greatest integer less than or equal to x.

Prove that $f(x)$ is not continuous at any point.
Prove that $f$ is not differentiable at any point.
Consider an arbitrary partition P = $\{x_0, x_1, x_2, \cdots, x_n$}$ of $[1, 2]$.
a) Find $U(f, P)$ and $L(f, P)$.
b) Find $U(f)$ and $L(f)$.
c) Prove that f is not integrable on $[1, 2]$.

For #1, I let $c\in\mathbb{R}$ and found the limit of the sequence of rationals $s_n$ converging to c and that equals to $\lfloor c\rfloor$. Then the limit of the sequence of irrationals $t_n$ converging to c and got $\lfloor c\rfloor+3$. Now for f to be continuous at c, the two limits must be the same, but clearly $\lfloor x\rfloor \neq \lfloor x\rfloor + 3$. Therefore, $f$ is not continuous at any point.
For #2 & 3 I'm stuck on.

How do I show the limits do not exist?
Is it correct if I say "by definition, f is not continuous at any point so it's not differentiable at any point"?
How do I find the upper & lower Riemann sums for #3 if I don't have values to plug in? What would $\Delta x_i$ be?

Any help is appreciated. Thank you so much!
Comment: That's a strange symbol for a floor function.
Comment: For #1, how do you know there's a sequence of rationals converging to $x$? (*I* know, but can *you* prove the existence of such a sequence?)
Comment: For #2, if it is not continuous, then it cannot be differentiable.
Comment: Your answer to #3a may depend on the actual $x_i$s.
Comment: @JohnHughes the function shows that when x is rational it equals to |x|. So I let sn be the sequence of rationals that converges to c. How should I show it?
Comment: "I let $s_n$ be the sequence of rational that converges to $c$." My question is "How do you know there *is* such a sequence. Your saying "the" sequence suggests to me that you don't know the answer to this; you probably should figure that out before attempting this more sophisticated question.
Comment: "That by definition it cannot be differentiable..." That's not what DHMO said at all. In fact, it's really by a (smallish) theorem that it cannot be differentiable; once again, that theorem is something you should understand before trying to move on to harder problems like this one.
Answer: For 2, you want to show that
\begin{align*}
\lim_{h\rightarrow0}\frac{f(x+h)-f(x)}{h}
\end{align*}
doesn't exist for any $x\in\mathbb{R}$.
The easiest way of doing this is by considering the sequence $(a_n) = \sqrt{2}/n$. Then this is a sequence which is irrational at every point and converges to zero. Thus if $\lim_{h\rightarrow0}\frac{f(x+h)-f(x)}{h}$ exists, it must be equal to:
\begin{align*}
\lim_{n\rightarrow\infty}\frac{f(x+a_n)-f(x)}{a_n}
\end{align*}
For any rational $x$, this limit does not exist, as it tends to $3/0$.
Similarly for irrational $x$, you must must use a sequence of numbers converging to zero so that $x+a_n$ is always rational. This is a bit more abstract.
Choose $x$ irrational. Consider a monotone decreasing sequence $(x_n)$ tending to zero but equal to zero for any $n$ (e.g. $1/n$). Then $x < x+x_n$ for each $n$. Hence for each $n$ you can find a rational number $y_n$ so that $x < y_n < x+x_n$. Now the sequence $(b_n) = (y_n-x)$ is also converging to zero, and has the property that $f(x+b_n)$ is rational, while $f(x)$ is irrational, for your given $x$.
Now you can use a similar argument as the first case to show that the limit as $h$ tends to zero of $\frac{f(x+h)-f(x)}{h}$ does not exist.
For 3: First let's think about the definitions.
$U(f, P)$ is the upper sum for this partition, so it's defined to be the sum of all $\sup\{f(x):x\in[x_i, x_{i+1}]\}(x_{i+1}-x_i)$. This is essentially "giving you the volume of the box" above the graph. Because there is an irrational number between any two distinct real numbers, you know that $\sup\{f(x):x\in[x_i, x_{i+1}]\}$ must be $|x|+3 = 4$, regardless of $x_i$ or $x_{i+1}$. Then you get
\begin{align*}
\sum_{i=0}^{n-1}4(x_{i+1}-x_i) = 4(x_n-x_0) = 4
\end{align*}
Similarly you can show that $L(f, P) = 1$.
For part (b), can you see that the partition didn't have any effect on the result for (a)? This means you can prove that as the partition gets arbitrarily fine, your upper and lower sums will still be 4 and 1.
Finally this results tells you that $U(f) \neq L(f)$, so it's not Riemann integrable.


Ask for Integer as input and quit if q but if any other letter try again

Question: I am working on a program that will ask users for an integer and then another and put them as graph points. It will then tell them the distance between them. The user must input an integer or press "Q" to exit. If it is anything else (not an integer or the letter "Q"), it will tell them that is incorrect and to please try again. I thought this is how I could accomplish that but it returns the error cannot find symbol. Help is appreciated greatly!
import java.util.Scanner;

public class PointCheck{

   public static void main(String[] args){

      try {

         System.out.println("Welcome");
         System.out.println("To quit at anytime please type \"Q\". Enter point:");

         char Q = 'Q';
         char q = 'q';
         Scanner scan = new Scanner (System.in);
          input = scan.next();

         while (input.hasNext()) {
            if (input.hasNextInt()) {
               System.out.println("Int input");
            }
            else if (input.equals("Q")) {
               System.out.println("Exiting");

            }
            /*else {
               System.out.println("You did not enter a valid value. Please enter a number or \"Q\" to quit.");
            }*/

         }

      }

      catch(Exception e){
         System.out.println("Exiting Program.");

      }

   }

}

If I don't comment out the last else statement it just defaults to that and loops my error message forever.
Comment: At the line `input = scan.next()` input doesn't have a type declared. Also after this point you're trying to use `input` instead of `scan` as the `Scanner`.
Comment: you havn't declared input , and if you define it as String than hasnext and hasintnext not gonna work with it
Answer: I have made some modification of your code, Hope it helps :)
public class PointCheck {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {

        System.out.println("Welcome");
        System.out.println("To quit at anytime please type \"Q\". Enter point:");
        Scanner scan = new Scanner(System.in);

        while (scan.hasNext()) {
            if (scan.hasNextInt()) {
                System.out.println("Int input" + scan.nextInt());
            } else {
                String input = scan.next();
                if (input.equalsIgnoreCase("Q")){
                    System.out.println("Exiting");
                    break;

                }else {
                    System.out.println("You did not enter a valid value. Please enter a number or \"Q\" to quit.");
                }
            }

        }

    } catch (Exception e) {
        System.out.println("Exiting Program.");

    }
}

}

Comment: This was very helpful. Thank you! I realized what I was doing wrong :)
Answer: You can try this...
The input will take only integers, if you enter anything other than an Integer, it will throw an exception and move to catch block where the program will terminate.
import java.util.Scanner;

public class demo {
    public static void main(String[] args) {
        System.out.println("Welcome");
        System.out.println("Press any key to exit.. Enter point:");
        Scanner scanner= new Scanner(System.in);

        while (true){
            try {
                int number = scanner.nextInt();
                System.out.println(number);
            }
            catch (Exception e){
                System.exit(0);
            }
        }
    }
}

Comment: The OP doesn't want the app to terminate. Please read the post.
Answer: Something like this may be to your liking. Read the comments in code:
System.out.println("Welcome");
Scanner scanner= new Scanner(System.in);
int number = 0;
while (true){
    System.out.println("Enter point (q to quit): ");
    String strg = scanner.nextLine();
    // Get out of loop if q or Q or quit,
    // or QUIT, or Quit, etc is entered.
    // providing the input actually contains
    // something.
    if (!strg.equals("") && strg.toLowerCase().charAt(0) == 'q') {
        break;
    }
    // Use the String.matches() method with regex to
    // determine if an integer number was supplied.
    if (!strg.matches("\\d+")) {
        System.err.println("Invalid Entry - Integer values only! Try again.\n");
        continue;   // Start loop from beginning.
    }
    // Convert string number to Integer.
    number = Integer.parseInt(strg);
    break;  // Get outta loop
}
String msg = "The number entered is: " + number;
if (number == 0) { msg = "Nothing Entered!"; }
System.out.println(msg);


Change Tab bar selected tab colour in Android

Question: I am using TabHost for tab bar. Here's the code that adds the tabs:
// Create  Intents to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Tab1.class);

spec = tabHost.newTabSpec("First").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);

//Add intent to tab
tabHost.addTab(spec);

/************* TAB2 ************/
intent = new Intent().setClass(this, Tab2.class);
spec = tabHost.newTabSpec("Second").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);
tabHost.addTab(spec);

/************* TAB3 ************/
intent = new Intent().setClass(this, Tab3.class);
spec = tabHost.newTabSpec("Third").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);
tabHost.addTab(spec);

intent = new Intent().setClass(this, Tab4.class);
spec = tabHost.newTabSpec("Fourth").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);
tabHost.addTab(spec);

tabHost.getTabWidget().setLeftStripDrawable(color.black);
tabHost.getTabWidget().setRightStripDrawable(color.black);
tabHost.getTabWidget().setStripEnabled(false);

tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().setDividerDrawable(null);

The selected tab is showing a blue underline, and I want to change its colour. How can I do this?
Comment: did you tried with `drawable` selector
Comment: Could you show us the `transaction_refno` drawables?
Answer: Instead of using the R.drawable.transaction_refno, you can use a drawable that uses a selector to show a different drawable depending on the state. You could write this in your drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tab_selected"
          android:state_selected="true"/>
    <item android:drawable="@drawable/tab_unselected"/>
</selector>

And create the tab_selected and tab_unselected drawables with each design. For more information on how to use TabHost, you can see the Android docs or check this walkthrough.


Mongoose findByIdAndUpdate not pulling

Question: I am trying to pull an object from a subdocument in a mongodb. The structure is as follows (from db.users.find().pretty()):
{
"_id" : ObjectId("56a660b42819b770b89950bd"),
"userName" : "someGuy",
"itemCollection" : [
    {
        "item_name" : "item1",
        "_id" : ObjectId("56a661232819b770b89950be")
    }
],
"__v" : 13
}

This code:
var userID = req.user._id;
var transactionID = req.body._id;
console.log('userID: '+userID);
console.log('transactionID: '+transactionID);
User.findByIdAndUpdate(
    userID,
    {$pull: {'itemCollection': {'_id': transactionID}}},{new: true}, function(err, model){
    if(err){
        console.log('ERROR: ' + err);
    }
    console.log(model);
});

Gets me the following output:
> userID: 56a660b42819b770b89950bd
> transactionID: 56a661232819b770b89950be
> { itemCollection:
    [ { item_name: 'item1',
    _id: 56a661232819b770b89950be } ],
__v: 13,
userName: 'someGuy',
_id: 56a660b42819b770b89950bd }

So nothing seems to have happened. I've tried every variation on stack overflow that I could find but it never deletes it. Does anyone see what is wrong?
Answer: You need to convert your _ids from string to an ObjectID type:

var mongoose = require('mongoose');
var userID = mongoose.mongo.ObjectID(req.user._id);

Comment: omg thank you so much! I must be stupid as this was never specifically mentioned and I never though of this. Ofcourse it is logical in the end...

Mongoose findByIdAndUpdate not pulling


Dealing with ties, weights and voting in kNN

Question: I am programming a kNN algorithm and would like to know the following:
Tie-breaks:

What happens if there is no clear winner in the majority voting? E.g. all k nearest neighbors are from different classes, or for k=4 there are 2 neighbors from class A and 2 neighbors from class B?
What happens if it is not possible to determine exactly k nearest neighbors because there are more neighbors which have the same distance? E.g. for the list of distances <code>(x1;2), (x2;3.5), (x3;4.8), (x4;4.8), (x5;4.8), (x6;9.2)</code> it would not be possible to determine the k=3 or k=4 nearest neighbors, because the 3rd to 5th neighbors all have same distance.

Weights:

I read it is good to weight the k-nearest neighbors before selecting the winning class. How does that work? I.e. how are the neighbors weighted and how is then the class determined?

Majority vote alternatives:

Are there other rules/strategies to determine the winning class other than majority vote?
Answer: When doing kNN you need to keep one thing in mind, namely that it's not a strictly, mathematically derived algorithm, but rather a simple classifier / regressor based on one intuition - the underlying function doesn't change much when the arguments don't change much. Or in other words the underlying function is locally near-constant. With this assumption, you can estimate the value of underlying function in any given point, by a (possibly weighted) mean of the values of nearest k points.
Keeping this in mind, you can realize there is no clear imperative on what to do when there is no clear winner in majority voting. You can either always use an odd k, or use some injective weighting.
In the case of neighbours 3 to 5 being at the same distance from the point of interest, you can either use only two, or use all 5. Again, keep in mind kNN is not some algorithm derived from complex mathematical analysis, but just a simple intuition. It's up to you how you want to deal with those special cases.
When it comes to weighting, you base your algorithm on the intuition that function doesn't change much when arguments don't change much. So you want to give bigger weights to points that are closer to point of interest. A good weighting would be for example $\frac{1}{||x-y||^2}$, or any other that is relatively big when distance is small, and relatively small when distance between points is big (so probably an inverse of some continuous metric function).
There has also been a nice paper by Samory Kpotufe and  Abdeslam  Boularias this year on NIPS touching on the issue of finding the right weighting. Their general intuition, is that the underlying function varies differently in different directions (i.e., its different partial derivatives are of different magnitude), hence it would be wise to in some sense change the metrics / weighting according to this intuition. They claim this trick generally improves performance of kNN and kernel regression, and I think they even have some theoretical results to back up this claim (although I'm not sure what do those theoretical results actually claim, I didn't have time to go through the whole paper yet). The paper can be downloaded for free from their sites, or after Googling  "Gradient Weights help Nonparametric Regressors". Their research is directed towards regression, but I guess it applies to classification to some extent as well.
Now, you will probably want to know how you can find the right k, metric, weighting, action to perform when there are draws and so on. The sad thing is, that it's basically hard to arrive at the right hyperparameters after some deep thinking, you will probably need to test different bunches of hyperparameters and see which ones work well on some validation set. If you have some computational resources, and want to arrive at the right parameters automatically at a good set of hyperparameters, there is a recent idea (that I like very much) to use Gaussian processes for derivative-free optimization in that setting.
Let me elaborate - finding the set of hyperparameters (i.e., that minimize error on validation data), can be viewed as an optimization problem. Unfortunately, in this setting we can't get the gradient of the function we try to optimize (which is what we usually want to do, to perform gradient descent or some more advanced methods). Gaussian processes can be used in this setting, for finding sets of hyperparameters, that have big chances, to perform better than the best ones we have found up to the point. Hence you can iteratively run the algorithm with some set of hyperparameters, then ask the Gaussian process for which ones would be best to try next, try those ones, and so on.
For details, look for paper "Practical Bayesian Optimization of Machine Learning Algorithms" by Jasper Snoek, Hugo Larochelle and Ryan P Adams (also to be found on either their websites or via Google).
Comment: Warning: optimising hyperparameters to have best accuracy on validation set is a straight way to overfitted oblivion. You want nested CV.
Comment: One quick note that "an odd k" won't necessarily solve the tie problem...eg k= 3 when classifying three groups. Besides that I agree.  Nice explanation.
Answer: The ideal way to break a tie for a k nearest neighbor in my view would be to decrease k by 1 until you have broken the tie. This will always work regardless of the vote weighting scheme, since a tie is impossible when k = 1. If you were to increase k, pending your weighting scheme and number of categories, you would not be able to guarantee a tie break.
Comment: why tie is impossible when k=1, what if there are two neighbors belong to different classes with the same distance, how do you determine the nearest neighbor with k=1?
Comment: -1 because this is manifestly incorrect
Answer: About this tie part, the best baseline idea for ties is usually random breaking, so selecting random class of all winning the voting and randomly selecting a subset of tied objects large enough to fill k.
Such a solution stresses the fact that those are pathological cases that simply don't provide enough information to make a decision in kNN regime. BTW if they are common to your data, maybe you should try some more differentiating distance?
Answer: One possible way is to have the algorithm automatically increase or decrease k until you get a clear winner.


Find the probability distribution function of $Y_(n)$ = max($Y_1, Y_2, . . . , Y_n$).

Question: Let $Y_1, Y_2, . . . , Y_n$ be independent random variables, each with a beta distribution, with $α = β = 2$. Find
a. the probability distribution function of $Y_(n)$ = max($Y_1, Y_2, . . . , Y_n$).
Could anyone help get me started on this?
Comment: Hint: The event $\{\max_i Y_i \leq \alpha\}$ occurs if and only if $\cap_{i=1}^n \{Y_i \leq \alpha\]$ occurs.
Comment: Please use `Y_{(n)}`, not `Y_(n)`.
Answer: Hint:
For i.i.d variables, $P(X_{(n)}<t)=(P(X<t))^{n}$.
Comment: So, we can integrate f(y) for beta distribtion when $ α=β=2$ and raise it to the power of n?
Comment: Yes you can; but I should ask: What does this imply for the pdf of $X_{(n)}$?
Comment: we can find $f_u (t) = n[F_y(t)] ^{n-1} f_y(t) $ right?
Comment: Yes. Now you on the right track.
Comment: let $U = Y_{(n)}$ Is $F_u (t) = [3y^2 - 2y^3]^n$?
Comment: Sorry but I have to sleep now. Good luck!


If $\sin\alpha\cos\beta=-0.5,$ then find the range of values of $\cos\alpha\sin\beta.$

Question:
If $\sin\alpha\cos\beta=-0.5,$ then find the range of values of $\cos\alpha\sin\beta.$

My Attempt:
$$-1\le\sin(\alpha+\beta)\le1\\-1\le\sin\alpha\cos\beta+\cos\alpha\sin\beta\le1\\-1\le-0.5+\cos\alpha\sin\beta\le1\\-0.5\le\cos\alpha\sin\beta\le1$$
The answer given is $[-0.5,0.5]$
Can you please confirm?
Comment: $\cos \alpha \sin\beta$ cannot be greater than $0.5$, or $\sin(\alpha -\beta)$ will be less than $-1$. You need to do $\sin(\alpha -\beta)$ also.
Answer: You have proved correctly that $\cos\alpha\sin\beta\geqslant-\frac12$. And now you can do this:\begin{align}\sin(\alpha-\beta)\geqslant-1&\iff\sin\alpha\cos\beta-\cos\alpha\sin\beta\geqslant-1\\&\iff-\frac12-\cos\alpha\sin\beta\geqslant-1\\&\iff-\cos\alpha\sin\beta\geqslant-\frac12\\&\iff\cos\alpha\sin\beta\leqslant\frac12.\end{align}
Comment: This only shows that $[-1/2, 1/2]$ is a *superset* of the range of $\cos \alpha \sin \beta$ though.
Answer: To show that the range of $\cos \alpha \sin \beta$ is $[-1/2, 1/2]$, namely that
$$
S = \{ \cos \alpha \sin \beta \mid \alpha, \beta \in \mathbb{R}, \sin \alpha \cos \beta = -1/2 \} = [-1/2, 1/2],
$$
it is not only necessary to show that
$$
\cos \alpha \sin \beta = -1/2 \implies -1/2 \le \sin \alpha \cos \beta \le 1/2
$$
for all $\alpha, \beta \in \mathbb{R}$,
as shown in José Carlos Santos's answer,
which shows that $S \subseteq [-1/2, 1/2]$,
but also that, for all $z \in [-1/2, 1/2]$, there exists a pair $\alpha, \beta$ such that
$$
{\cos \alpha \sin \beta = -1/2} \quad \text{and} \quad
{\sin \alpha \cos \beta = z},
$$
which shows that $S \supseteq [-1/2, 1/2]$.
To show this, fix $z \in [-1/2, 1/2]$.  We would like to find $\alpha, \beta \in \mathbb{R}$ such that
$$
\sin (\alpha + \beta) = \sin \alpha \cos \beta + \cos \alpha \sin \beta = z - 1/2
$$
and
$$
\sin (\alpha - \beta) = \sin \alpha \cos \beta - \cos \alpha \sin \beta = z + 1/2.
$$
We can always pick $x, y \in \mathbb{R}$ such that $\sin x = z - 1/2$ and $\sin y = z + 1/2$ since $\{z - 1/2, z + 1/2\} \subset [-1, 1]$.  Then,
$$
\alpha = \frac{x + y}{2} \quad \text{and} \quad
\beta  = \frac{x - y}{2}
$$
satisfy the constraints.


numbers that are squares of integers

Question: Even and square numbers
The data.txt file is located in the following lines of 1000 numbers from the range [0.999999].
(a) to the a.txt file, enter the number of even numbers in the data.txt file in the following form: "Even numbers are [number of numbers]" //ivedoneit
(b) to the b.txt file, copy all numbers from the file data.txt, in which the digit of unity is equal to 7 or 0//ivedoneit
(c) to the c.txt file, copy all numbers that are squares of integers, eg this number is the number 225, because
225 = 15**2
I've done already
def main():

    infile = open('dane.txt','r')

    evenTotal = 0
    oddTotal = 0

    line = infile.readline()

    while line != '':
        if int(line) % 10 == 0 and int(line) % 7 == 0:
            evenTotal += int(line)
            even = open('a.txt', 'w')

            even.write("wszystkie liczby jednosci ")
            even.write(str(evenTotal))

        else:
            oddTotal += int(line)
        line = infile.readline()
    print('The total for the even numbers is',evenTotal)
    print('The total for the odd numbers is',oddTotal)

    infile.close()

    print('All done!')

main()

its good for (b) for (a) I have only to change for
if int(line) % 2 == 0:

and it works but I completely don't know how to do (c).
Comment: So are you just asking how to check if a number is a perfect square?
Comment: Yes i want to check if a number is a perfect square
Answer: There are a finite number of squares of integers in between 999999. You can put together a set of all integers in between 0 and 999999, then for each line check if the line's number is in this set.
Comment: i tried sth like this but it dont work if((int)sqrt(line)==sqrt(line))
Answer: Assisted from Python: Check if a number is a perfect square
You should run:
if int(math.sqrt(int(line))+.5) ** 2 == int(line):

Comment: "TypeError: must be real number, not str"
Comment: still sth is wrong. its compiling but nothing is going on.. :(

numbers that are squares of integers


Percentage evaulation Queestion from GRE

Question: A question from GRE book says:

A candidate who gets 30 percent marks in an examination fails by 30 marks,but another candidate who gets 42 percent marks get 42 more marks than necessary for passing.Find the maximum number of marks and total necessary for passing.

I started with it by :
Let passing marks =x
Then for Student1; (x-30)
Student 2;(x+42)
But what should i equate it to get them  compared and find 'x' and then total marks.
Answer: Hint: First find the number of points that corresponds to $1\%$.
Comment: More clearly pls
Comment: @JavedIqbal Ask a more clear question. What do you not understand?
Comment: What do you mean by :First find the number of points that corresponds to 1%.
Comment: Calculate how many points is 1% of the maximum.
Comment: Not able to get through :-(
Comment: @JavedIqbal: Another hint: how many more points did the first candidate get than the second candidate? How many % of the full score that is?
Answer: Let Maximum marks be $x$, and Passing marks $y$
Then according to first condition
$$x\times \frac{30}{100}=y-30\tag{1}$$
According to second condition
$$x\times \frac{42}{100}=y+42\tag{2}$$
Solving $(1)$ & $(2)$
yields $$x=600, y=210$$
So, Maximum marks $=600$, Marks requied for passing$=210$


How long do servers usually last?

Question: I'm trying to estimate ROI for a new server and how long it will most likely be in service. Are there any average numbers for how long you can expect a server to last that's in 24/7 use?
In other words, is it likely to find 10-year old server from 2010 in today's racks? How about servers from 2005? I'd love to get an idea for how long a server will most likely be in use.
By the way, this is meant irrespective of growing or changing application needs. I'm talking only about the hardware.
Comment: possible duplicate of [Whats the average lifespan of a server?](http://serverfault.com/questions/153025/whats-the-average-lifespan-of-a-server)
Comment: This question is off-topic under current topicality rules.
Answer: Servers are generally built with fairly high quality components, especially from big brand names.
In my experience they can easily run for 5 years easily before becoming unreliable. (replacing the disks in the raid array along the way).
However, they may not be economical in that respect. The capacity/power of new machines keeps rising dramatically, while your overhead costs (human and power) remain expensive. At some point the raw capacity becomes just not worth it.
Comment: +1 for not focusing on the hardware. A decent server will ither fail fast (bad hardware) or last way longer than 5 years, ignoring discs which are hot swappable. The main reason really IS the age capacity. I recently replaced 3 machines 4 ýears olf with one rnuning virtualization - and that one still now has 24gb free memory (32 gb instead of 12). The power / space savings pretty much pay for the hardware.
Comment: That matches with my experience, although while I expect an average usable life of 5 years, for accounting purposes I use a figure of 4 years to be obn the safe side.
Comment: same here.  i DO have 6-7 y/o machines running; but usually consider them to be disposable after 3-4 years.  If it's going to be dedicated to a client that asks about 'his' hardware, i offer hardware replacement every 3 years.
Comment: +1, for reasons already listed. Most server we replace every 3 to 4 years (same for desktops and notebooks). I've got one at home though that's 9 years old and still kicking; had one 12 years old that just died (too hard to find replacement parts).
Comment: Bigger data centers turn the machines off once they're of the lease contract (most have an replacement plan or when the financial write-off of the equipment is expired.
Answer: Its not likely to find a 10 year old server in the racks unless it has been re-purposed, or isn't replaceable.  If nothing else it becomes difficult to find replacement parts.  For production use I usually schedule replacement every five years or so.  If the budget doesn't allow for purchase of development hardware, they may end up being recycled as development machines.
Server grade hardware is likely to run more or less forever except for moving parts.  Support, power requirements, and physical size to performance become the significant factors.
I believe our tax rules allow for a full write-off over three years (actually four reporting years).  From a technical standpoint anything you can buy is likely already obsolete.  From an accounting standpoint, if it still does the job it isn't obsolete.  The performance/cost ratio is continuing to fall and may make earlier replacement a good option.
Answer: Generally, if you're buying a server from one of the big vendors the service-contract for it will be pretty cheap until it turns 5 years old. At that point, if you can even get one, it'll be VERY expensive. For our hardware vendor the 1 year service-contract cost at Year 6 is about 50% the cost of a new server. This is how they encourage regular hardware replacement. You are factoring in the service-contract in your ROI calculations, right?
Once a server turns 5 around here it tends to get relegated to test/dev/low-impact roles and we keep a grave-yard of similar machines for parts if it comes to it. Those of us who keep this hardware running frown very discouragingly when entities ask to use old stuff that we have 'just laying around'.
My oldest monster right now is an ancient HP LH3, a 12 year old server, that is performing a single task: monitoring our datacenter UPS internals. The next oldest is a 9 year old that's due to be replaced in the next 3 months. Neither of these have service-contracts, and if they die we will sigh deeply but won't be otherwise inconvenienced.
Answer: This can't be said as confirm it is totally depends on how servers has been used and what was the use of server. What application installed on server. How much load was server having.
All these calulation matters regarding server performance.
Answer: The answers to date are good, I just like sharing stories:
I have seen servers last over 10 years. When I was at a $BIGPHARMA in 2005, I performed decommissions and retirements in the datacenters. I retired a handful of old HPUX cabinets, did some SGI IRIX machines (Indys, I think), some Netware boxes that had to be near 10 years, and at least two Sun SPARCstations. One pizza box, one lunchbox, and I think they were both running DNS servers.
Answer: 50,000 Power On Hours is a magic number.  That works out to about 5.7 years.  The number of issues we see with solid state components at and beyond that point is drastically higher regardless of the kind of server.
Answer: We used to plan financially to depreciate machines after 3 years. At which point they were classed as essentially worthless.
We used to plan to run the hardware for about 4 years, and the machines were often decommissioned at around 5 years old. At this point they were moved to non-production.
At 3-4 years, the machines were well used. We'd buy new kit, but until it had been running for 6 months we wouldn't dream of moving them into production.
Andrew

How long do servers usually last?


SPF and OpenDMARC not working in Postfix

Question: I am working on implementing SPF and OpenDMARC/DKIM to my mail servers.
Currently I have two mail servers in different subnets, each with separate DNS server and domain name. They can exchange emails successfully.
I set up SPF with pypolicyd-spf, DMARC with OpenDMARC and DKIM with OpenDKIM.
DKIM works flawlessly, but I have some issues with DMARC and SPF, probably they are related to my topography (a graph of it is placed below).
I have users made on each mail server and I exchange mails between them via Squirrelmail.
How to make SPF and DMARC work? In my email headers I get:
Received-SPF: None (mailfrom) identity=mailfrom; client-ip=192.168.22.132
Authentication-Results: OpenDKIM; dmarc=none (p=none dis=none) header.from=another.com

I think there is something wrong with that localhost IP in logs but I have no idea what causes it:
policyd-spf[2183]: prepend X-Comment: SPF check N/A for local connections - client-ip=127.0.0.1; helo=[192.168.22.128]; email@example.com; receiver=<UNKNOWN>
postfix/smtpd[2177]: D5DA9C0F5F38: client=localhost[127.0.0.1]

my postconf -n output:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd
$daemon_directory/$process_name $process_id & sleep 5
home_mailbox = Maildir/
html_directory = no
inet_interfaces = all
inet_protocols = ipv4
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
milter_default_action = accept
mydestination = $myhostname, localhost.$mydomain, localhost
mydomain = $myhostname
myhostname = example.com
mynetworks = 127.0.0.0/8, 192.168.22.0/24
myorigin = $myhostname
newaliases_path = /usr/bin/newaliases.postfix
non_smtpd_milters = $smtpd_milters
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
sample_directory = /usr/share/doc/postfix-2.10.1/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtpd_milters = inet:127.0.0.1:8891, inet:127.0.0.1:8893
smtpd_recipient_restrictions = check_policy_service unix:private/policy-spf, permit_mynetworks,
reject_unauth_destination
unknown_local_recipient_reject_code = 550

Network graph:

I can provide any additional info if needed.
Of course all entries in DNS are made.
example.com.     IN      TXT     "v=spf1 mx ~all"
default._domainkey      IN      TXT     ( "v=DKIM1; k=rsa; "
          "p=XXXkeyXXX" )  ; ----- DKIM key default for example.com
_dmarc.example.com.       IN      TXT      "v=DMARC1; p=none; pct=100"

policyd-spf logs:
policyd-spf[2681]: Read line: "request=smtpd_access_policy"
policyd-spf[2681]: Read line: "protocol_state=RCPT"
policyd-spf[2681]: Read line: "protocol_name=ESMTP"
policyd-spf[2681]: Read line: "client_address=192.168.22.132"
policyd-spf[2681]: Read line: "client_name=gateway"
policyd-spf[2681]: Read line: "reverse_client_name=gateway"
policyd-spf[2681]: Read line: "helo_name=example.com"
policyd-spf[2681]: Read line: "email@example.com"
policyd-spf[2681]: Read line: "firstname.lastname@example.com"
policyd-spf[2681]: Read line: "recipient_count=0"
policyd-spf[2681]: Read line: "queue_id="
policyd-spf[2681]: Read line: "instance=a73.5fe8c4e7.510b9.0"
policyd-spf[2681]: Read line: "size=935"
policyd-spf[2681]: Read line: "etrn_domain="
policyd-spf[2681]: Read line: "stress="
policyd-spf[2681]: Read line: "sasl_method="
policyd-spf[2681]: Read line: "sasl_username="
policyd-spf[2681]: Read line: "sasl_sender="
policyd-spf[2681]: Read line: "ccert_subject="
policyd-spf[2681]: Read line: "ccert_issuer="
policyd-spf[2681]: Read line: "ccert_fingerprint="
policyd-spf[2681]: Read line: "ccert_pubkey_fingerprint="
policyd-spf[2681]: Read line: "encryption_protocol="
policyd-spf[2681]: Read line: "encryption_cipher="
policyd-spf[2681]: Read line: "encryption_keysize=0"
policyd-spf[2681]: Read line: ""
policyd-spf[2681]: Found the end of entry
policyd-spf[2681]: Config: {'Whitelist_Lookup_Time': 10, 'skip_addresses': '127.0.0.0/8,::ffff:127.0.0.0/104,::1', 'Reason_Message': 'Message {rejectdefer} due to: {spf}. Please see {url}', 'PermError_reject': 'False', 'Header_Type': 'SPF', 'TestOnly': 0, 'SPF_Enhanced_Status_Codes': 'Yes', 'TempError_Defer': 'False', 'Lookup_Time': 20, 'debugLevel': 4, 'Authserv_Id': 'centos2.another.agh.edu.pl', 'Mail_From_reject': 'Fail', 'Hide_Receiver': 'Yes', 'HELO_reject': 'Fail', 'Void_Limit': 2, 'Mock': False}
Dec 27 12:31:19 centos2 policyd-spf[2681]: Cached data for this instance: []
Dec 27 12:31:19 centos2 policyd-spf[2681]: skip_addresses enabled.
Dec 27 12:31:29 centos2 policyd-spf[2681]: spfcheck: pyspf result: "['None', '', 'helo']"
Dec 27 12:31:29 centos2 policyd-spf[2681]: None; identity=no SPF record; client-ip=192.168.22.132; helo=example.com; firstname.lastname@example.com; receiver=<UNKNOWN>
Dec 27 12:31:29 centos2 policyd-spf[2681]: spfcheck: pyspf result: "['None', '', 'mailfrom']"
Dec 27 12:31:29 centos2 policyd-spf[2681]: None; identity=mailfrom; client-ip=192.168.22.132; helo=example.com; firstname.lastname@example.com; receiver=<UNKNOWN>
Dec 27 12:31:29 centos2 policyd-spf[2681]: not peruser
Dec 27 12:31:29 centos2 policyd-spf[2681]: Action: prepend: Text: Received-SPF: None (mailfrom) identity=mailfrom; client-ip=192.168.22.132; helo=example.com; email@example.com; receiver=<UNKNOWN>  Reject action: 550 5.7.23

Comment: What are your SPF & DMARC records (in the DNS zones for example.com and the other domain)?
Comment: Your edit doesn't answer my question. Your headers suggest you don't have SPF and that your DMARC policy is `p=none`, so you can't just say your DNS is ok.
Comment: It's important to understand that DMARC *uses* SPF and DKIM authentication results. So you need to have a component that inserts an `Authentication-Results: yourserver.com; spf=…` header that OpenDMARC can then consume.
Comment: Sorry, I have added my DNS records for SPF, DKIM and DMARC. From what I have know, p=none means that DMARC does nothing to the mails even if they do not passed authentication, so that is probably not a cause of my problem
Comment: The problem is with my policyd-spf. I have added policyd-spf logs with debug_level=4 to my question. I can see that "client_name" and "reverse_client_name" value is "gateway" and "client_address" is an IP address of my gateway. Should it be like this or something is wrong?
Comment: It turned out that when sending from centos1 to centos2, sender's IP is somehow lost in router and the receiver acts as if the mail was sent from his gateway address. Is there any way of changing this bahavior?
Answer: After a few days of struggling with SPF by pypolicyd-spf, I have finally get to know what is wrong.
My topology included 2 DNS servers and my /etc/resolv.conf files on mail servers had both DNS servers.
OpenDMARC SPF worked like a charm and responded to the changes of spf records on both DNS, but pyspf did not.
The answer is: pypolicyd-spf does not support two dns in resolv.conf.
A simple workaround is to make two zones in one DNS server. Then suddenly pyspf starts working.


Explicitly instantiating a class template with a list of parameters

Question: I am trying to instantiate a class template with a whole bunch of different combinations of template parameters which will be decided by some runtime information: https://github.com/ITKTools/ITKTools/blob/newpixeltypeselector/src/binarythinning/binarythinning.cxx . This system works fine (lines 169 - 190), but it is quite verbose. And this is only 2 and 3 dimensions, what if I wanted 2 - 10? This would be pages of code!
Is there anyway to reduce this to say "instantiate all pairs of [these types] and [these dimensions]" or something like that?
I've seen something like this in Boost, but using Boost is unfortunately not an option for this project.
Any pointers?
Thanks!
David
Comment: If you've seen it in Boost, then go read the Boost source code. That should explain fairly well how to do it.
Comment: Haha "read the Boost source code" is not really an answer that will help anyone but elite programmers.
Comment: hah, I was about to give you an example of doing this using Boost when I noticed that.  Oh well.  Why do you want to reinvent the wheel?
Comment: Googling for "typelist" should give some reasonable starting points. Loki also includes this kind of capability, and is a lot smaller (if rather more brain-bending) than Boost.
Comment: I think you can do this (or at least the dimensions part) with Boost.PP. And using Boost.PP is an option for almost *any* project since you'd only have to include the Boost.PP headers, and that's all of it. And since it only requires the preprocessor, compiler compatibility is not an issue (though preprocessor compatibility may be an issue :)).
Answer: I guess the consensus is "use Boost."


SpeechRecognitionEngine.InstalledRecognizers() returns null within Unity

Question: I am trying to use the speech recognition system from the .NET 3.0 framework within Unity. I therefore have imported the System.Speech.dll, from .NET 3.0 since higher version did not work, into the assets folder together with its dependencies. I know that what I am trying to do might not work because Unity uses .NET 2.0, but I still want to give it a try. It all seems to work and I can run the game fine, but when I run it I get the error:
<code> NullReferenceException: Object reference not set to an instance of an object
 System.Speech.Internal.ObjectTokens.RegistryDataKey.HKEYfromRegKey (Microsoft.Win32.RegistryKey regKey)
 System.Speech.Internal.ObjectTokens.RegistryDataKey.RootHKEYFromRegPath (System.String rootPath)
 System.Speech.Internal.ObjectTokens.RegistryDataKey.Open (System.String registryPath, Boolean fCreateIfNotExist)
 System.Speech.Internal.ObjectTokens.ObjectTokenCategory.Create (System.String sCategoryId)
 System.Speech.Recognition.SpeechRecognitionEngine.InstalledRecognizers ()
 VoiceCommandListener.Start () (at Assets/Scripts/VoiceCommandListener.cs:14)
</code>
The line of code is:
<code> SpeechRecognitionEngine speechRecognitionEngine = new SpeechRecognitionEngine(SpeechRecognitionEngine.InstalledRecognizers()[0]);
</code>
When I run the same line of code outside of Unity it works fine and just grabs the default and first recognizer, but somehow it doesn't work within Unity.
I have tried switching between using .NET 2.0 instead of .NET 2.0 subset, switching to Microsoft.Speech.Recognition and importing the Microsoft.Speech.dll didn't work either and gives the same type of error.
I also tried running the following code block instead:
<code> SpeechRecognitionEngine speechRecognitionEngine = null;
 foreach (RecognizerInfo info in SpeechRecognitionEngine.InstalledRecognizers()) {
     if (info.Culture.Equals(requiredCulture) && info.Id == requiredId ) {
         speechRecognitionEngine = new SpeechRecognitionEngine(info);
         break;
     }
 }
</code>
This gives the same result and this time again at the line of code which uses "SpeechRecognitionEngine.InstalledRecognizers()".
Does anybody know why it does not return anything?
Switching to Microsoft.Speech.Recognition and importing the Microsoft.Speech.dll didn't work either and gives the same type of error.
Thanks in advance.
Ron
Comment: Unity uses Mono instead of .NET. For information on how Mono compares to .NET for Unity, see: http://docs.unity3d.com/410/Documentation/ScriptReference/MonoCompatibility.html
Answer: I am running into the same issue, but what seems to be the case is that the Microsoft.Win32.RegistryKey class in the shipped Mono mscorlib is not fully compatible with the Microsoft version.
Having a look with ILSpy in the System.Speech dll it shows the method in which the null reference occurs tries to obtain the non-public 'hkey' field of the passed RegistryKey instance using reflection. This field is not available in the mscorlib shipped with Unity.
Answer: As user3071284 pointed out, MS .NET and Mono are different in their requirements, and unity basically only allows .NET from a Microsoft .NET versions perspective. Even tho' it is running a higher .NET version from Mono's perspective.
This topic has been covered in details on the Unity Forums, I took a stab at it a few years ago, and came up with this. https://www.youtube.com/watch?v=CuLwwcekoi8
I no longer have the source code for that project, but it essentially used the UDP network protocol to communicate with a backend service running speech recognition on a higher .NET version, one thing you could do is look at UnityBridge
Which essentially does the same thing, just makes it a bit more user-friendly. You can take a look at the manual.


Can't update form field via ajax on submit

Question: I have two entity types -- video and video progress.
I've got a form on video nodes with a field that is populated with the id of a video progress entity that references the current node. If this field is empty when the form is submitted, then I am generating a new video progress entity in the submit handler, and am trying to populate my form field value with this new entity id. This form is hidden from the user and is updated dynamically as the user watches a video via jQuery.
My issue is that no matter what I try, I cannot get the submit or ajax callbacks to rebuild my field. Here are the relevant portions of my code.
function video_progress_tracking_form($form, &$form_state) {
  // $progress_id is already set

  $form['progress_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Video progress entity id'),
    '#default_value' => $progress_id,
    '#element_validate' => array('element_validate_integer_positive'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#ajax' => array(
      'callback' => 'video_progress_tracking_form_ajax_handler',
      'effect' => 'fade',
    ),
  );

  return $form;
}

function video_progress_tracking_form_submit($form, &$form_state){
  if(empty($form_state['progress_id'])) {
    // If a video progress entity doesn't exist, we need to create one
    $entity_type = 'video_progress';
    $entity = entity_create($entity_type, array('type' => 'video_progress'));
    $wrapper = entity_metadata_wrapper($entity_type, $entity);
    $wrapper->save();

    // Pass our new values into the form for further updating
    $form_state['values']['progress_id'] = $wrapper->id->value();
  }
}

function video_progress_tracking_form_ajax_handler(&$form, &$form_state) {
  return $form['progress_id'];
}

I have also tried, among other things:

Setting a #value when initially building the form on $form['progress_id'] with a ternary operator so that if there is a form_state value for the field then that is set
Setting $form_state['rebuild'] = TRUE in both callbacks
Returning the entire form instead of just this single field
Answer: $form['progress_id'] = array(
        '#type' => 'textfield',
        '#title' => t('Video progress entity id'),
        '#default_value' => $progress_id,
        '#element_validate' => array('element_validate_integer_positive'),
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#ajax' => array(
          'callback' => 'video_progress_tracking_form_ajax_handler',
          'effect' => 'fade',
        ),
      );

by
 $form['progress_id'] = array(
    '#prefix' => '
',
    '#suffix' => '
',

    '#type' => 'textfield',
    '#title' => t('Video progress entity id'),
    '#default_value' => $progress_id,
    '#element_validate' => array('element_validate_integer_positive'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#ajax' => array(

      'callback' => 'video_progress_tracking_form_ajax_handler',
      'wrapper' => 'my-div-ajax',
      'effect' => 'fade',
    ),
  );

Answer: You haven't told the form API where to render the content you're returning in the AJAX callback.
That takes the form of a prefix/suffix on the element itself, with a predictable HTML ID:
$html_id = drupal_html_id('foo');
$form['progress_id'] = array(
  '#type' => 'textfield',
  '#title' => t('Video progress entity id'),
  '#default_value' => $progress_id,
  '#element_validate' => array('element_validate_integer_positive'),
  '#prefix' => '
',
  '#suffix' => '
',
);

And providing the AJAX-ified element with the ID of the wrapping HTML:
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'video_progress_tracking_form_ajax_handler',
    'effect' => 'fade',
    'wrapper' => $html_id,
  ),
);

You will need to add/keep $form_state['rebuild'] = TRUE; in the submit handler (not the AJAX callback). To isolate that functionality you may wish to add a specific #submit handler array to your submit button.
Comment: Can you think of why it still wouldn't be working? I've added the prefix and suffix to my field, the wrapper to #ajax, and `$form_state['rebuild'] = TRUE` to the submit function, but the field is remaining empty after submit. I've verified that `$form_state['values']['progress_id']` is set in my AJAX callback prior to `return $form['progress_id']`.
Comment: It also doesn't seem to make a difference whether I designate `$form_state['rebuild'] = TRUE` in the default callback or within a secondary callback (if that matters).
Comment: It might come down to where you're getting `$progress_id` from in the form builder. That should be coming from `$form_state['values']['progress_id']` if it's set, is that what you've got? You have a small (unrelated) bug in the submit handler BTW, you should be testing `$form_state['values']['progress_id']` rather than `$form_state['progress_id']`.
Comment: Ah, got it. I forgot to move some logic into an else condition so `$progress_id` was getting reset before it hit my field -- gah! Thanks! Good catch on the bug -- it's actually commented already on my end to make sure my entities were generated.


Get Sha256 public key from certificate

Question: Currently, am working on client server application(Chat) am implementing  security for server and clients, few of the client is written in java SMACK library, they are using TLS Pining for JAVA it needs sha2 hash [https://github.com/Flowdalic/java-pinning][1]
Server is implemented using C#, I have certificate on server side how can I get the sha2 public key with below format from the certificate, below is my code.
cer =new X509Certificate2(ConfigurationManager.AppSettings["CertificateName"],"123456");

string hellow= cer.GetCertHashString(); //it will return sha1 hash

what I need is the below format and sha2-256 key from the certificate
SHA2-256 key

83:F9:17:1E:06:A3:13:11:88:89:F7:D7:93:02:BD:1B:7A:20:42:EE:0C:FD:02:9A:BF:8D:D0:6F:FA:6C:D9:D3
Answer: I have found the solution for my question, let me share.
If you want to get certificate's SHA256 thumbprint, you have to do some manual work. Built-in Thumbprint property is SHA1 only.
Yo have to use a SHA256 class and compute hash over certificate's content:
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace MyNamespace {
    class MyClass {
        public static String GetSha2Thumbprint(X509Certificate2 cert) {
            Byte[] hashBytes;
            using (var hasher = new SHA256Managed()) {
                hashBytes = hasher.ComputeHash(cert.RawData);
            }
            return BitConverter.ToString(hashBytes).Replace("-", ":");
        }
    }
}

Get Sha256 public key from certificate


Probability adjustments

Question: Apologies in advance if the answer to this question seems obvious to some of the readers but I am confused as to how I should proceed when interpreting the following data.
I have a sample of 5000 students (Male (M) / Female (F)) and I have calculated the probabilities of students passing or failing Test 2 given how they performed in Test 1 (Pass / Fail denoted as subscripts in the tables below).  The number of occurrences is also included as "frequency"
TABLE 1 - In row 1, I randomly select either Male or Female / Pass or Fail Test 1 and the resulting probability of passing or failing Test 2 is shown.  In row 2, I select another candidate and add it to the pre-existing condition in row 1.  I continue this sequence adding onto already previous results up to row 5.
TABLE 2 - I follow the same random selection and the first 2 rows yield the same result as Table 1 giving the same probability of students passing test 2.  However conditions diverge in row 3, row 4, row 5, yielding different probabilities.
My question I guess is whether there is a method to intutitively understand the data or some methodology to adjust / standardize the probabilities to reflect that differing frequencies and the addition of conditions to the data set thus making some probabilites more significant than others.
Thank you for your help.
Answer: Instead of the tables you could do a logistic regression where the dependent variable is binary (pass/fail on test 2).  The predictor variables would be gender and outcome on test 1.  The model will estimate the probability of success on test 2 given the predictor values.  If you get additional data you can incorporate it and get new estimates. Initially you should check the goodness of fit of the model to make sure that the estimates are reasonable.
Comment: Michael, initially I thought I´d have to apply some sort of statistic and find some threshold value to make sense of the probabilities but your answer has directed towards logistic/probit regressions.  I very much appreciate your guidance as using this type of regression seems more intuitive and is precisely what I was looking for.  Thanks for the help.

Probability adjustments


how to prevent a theme from using templates of a sub themes (placed inside the parent theme dir)?

Question: my folder structure looks something like this:
 themes
└─  foo
   ├─  bar
   │  ├─  templates
   │  │  └─  node.html.twig
   │  └─  bar.info.yml
   ├─  templates
   │  └─  page.html.twig
   ├─  foo.info.yml
   └─  foo.libraries.yml

now I run a multisite. one site is using the foo theme and the other uses bar.
The site using the foo theme also invokes the template
/theme/foo/var/templates/node.html.twig

Why is that so?
I thought the foo theme only invokes templates inside its own templates folder? I expected this to be the point of the templates folder. Is that assumption wrong?
can I prevent this behavior without moving the subtheme somewhere else?
Answer: Themes are not allowed to be placed inside one another, as oppose to modules. Even though it works, there are undesired side effects.
Answer: This directory structure is shows one single theme called foo. The sub-directory bar has no meaning at all for Drupal, it is below /themes/fooand as such part of foo.
Your node file has to go into /themes/bar/templates/OPTIONAL/SUBDIR/DOES/NOT/MATTER/node.html.twig
Every theme, even subthemes, has to go in it's own /theme-directory. Please red read the docs for sub-themes.
Comment: How and where do the docs answer the question?
Comment: The very first words on the sub-themes docs page are _"Sub-themes are just like any other theme"_. As your main theme `foo` already has a correct file and folder structure, it seems you already know how to create a theme. Do the same with the sub-theme, but add the `basetheme`key in the YAML


jQuery-UI Sortable and string replace issue

Question: Consider the following code:
$(document).ready(function () {
    $("tbody").sortable({
        handle: 'td:first',
        opacity: 0.75,
        helper: function (e, ui) {
            ui.children().each(function () {
                $(this).width($(this).width());
            });
            return ui;
        },
        stop: function (event, ui) {
            alert("reorder triggered");
            // Re-order items based on position in table
            $(".dragablePager").each(function (index) {

                $(this).find("input").each(function () {
                    alert(index);
                    alert("old name: " + this.name);
                    oldname = this.name;
                    newname = oldname.replace(/\d+/, index);
                    this.name = newname;
                    alert("new name: " + this.name);
                    alert(newname);
                });
            });
        }
    });
});

The part of the form I am dealing with looks something like this:

            <input type="text" name="pagers[0][CellEmail]" value="REDACTED">

            <input type="text" name="pagers[0][Message]" value="test 1">

            <input type="text" name="pagers[1][CellEmail]" value="REDACTED">

            <input type="text" name="pagers[1][Message]" value="sdfdsfdf">

            <input type="text" name="pagers[2][CellEmail]" value="REDACTED">

            <input type="text" name="pagers[2][Message]" value="3247678">

What I am tying to do is change the indexes of the input elements based on their order in the table, after the user is done dragging. The problem is that for some reason the very simple RegEx that I have tested using a RegEx tester refuses to work. oldname and newname are always the same.
I am going nuts; what the hell am I doing wrong?
EDIT: I am getting this output in my console for the code posted in the first comment:
0
old name: pagers[1][CellEmail]
new name: pagers[1][CellEmail]
0
old name: pagers[1][Message]
new name: pagers[1][Message]
1
old name: pagers[2][CellEmail]
new name: pagers[2][CellEmail]
1
old name: pagers[2][Message]
new name: pagers[2][Message]
2
old name: pagers[0][CellEmail]
new name: pagers[0][CellEmail]
2
old name: pagers[0][Message]
new name: pagers[0][Message]

Here is the code from that comment (nearly identical to my original):
$(document).ready(function() {
  $("tbody").sortable({
    handle: 'td:first',
    opacity: 0.75,
    helper: function(e, ui) {
      ui.children().each(function() {
        $(this).width($(this).width());
      });
      return ui;
    },
    stop: function(event, ui) {
      console.log("reorder triggered");
      // Re-order items based on position in table
      $(".dragablePager").each(function(index) {

        $(this).find("input").each(function() {
          console.log(index);
          console.log("old name: " + this.name);
          oldname = this.name;
          newname = oldname.replace(/\d+/, index);
          console.log("new name: " + newname);
          this.name = newname;
        });
      });
    }
  });
});

How can this possibly happen? Clearly something is wrong to get output like this.
Comment: [Working fine](https://jsfiddle.net/c5zk24qa/)
Comment: This fiddle works, but I am telling you it is NOT working on my actual page. also, why the downvotes? I am having a legitimate problem, If it "just worked" I wouldn't have posted here.
Comment: What can we do if it doesn't work in your page..? You have to give us the code required to reproduce the issue. Which you haven't. Try posting a [mcve]
Comment: I posted because I didn't know if it was just me; how would I have known that? Someone made it clear it wasn't. I elaborated. Don't see how that is in any way unreasonable.
Comment: It is unreasonable because you posted working code and told us it doesn't work. What are we supposed to do with working code..? You should have made sure this code reproduces the problem before posting it. If it doesn't, think why it happens just for you, and provide relevant information. which is not there in question.
Answer: Ok I figured it out. It was kind of dumb. I am creating the JS in a string in Perl, and I neglected to escape the \ in the regex. It should have been:
oldname.replace(/\\d+/, index);

Simply because it was in a heredoc.


Publicar app ionic browser

Question: Foi desenvolvido um app em ionic 2 aqui na empresa que eu trabalho, porém, um dos clientes que está utilizando, gostaria de utilizar ele no desktop (via browser).
Como e quais arquivos preciso utilizar para publicar esse app na internet?
Comment: Olá, tive o mesmo problema com ionic 1, consegui publicar e vou tentar lhe ajudar... Na estrutura do projeto existe uma pasta equivalente a www do ionic 1?
Comment: @GabrielSouza, sim, tenho essa pasta....
Comment: vou responder me baseando em ionic1
Answer: Caso não estiver usando nenhum plug-in Cordova não existe nenhum problema(pode usar o iis para publicar como um site normal), basta mover o conteúdo da pasta www(Pasta do ionic 1 use a equivalente para o ionic 2)para o seu servidor.
Observações:
O navegador deve estar atualizado.
O ionic não foi destinado a este uso.
Resposta baseada em ionic1.
Espero que de certo, se tiver duvidas pode solicitar meu email!!
Comment: Eu tenho um servidor nGinx, funcionou perfeitamente :D Obrigado @gabriel.souza

Publicar app ionic browser


Ground floor flat and electronic drum kit: is noise better isolated on the ground floor?

Question: I am looking for a new flat in my city and I want to take my electronic drum kit into considerations when choosing the flat.
I was wondering if going for a ground floor flat would solve the problem of vibrations from the drum kit traveling through the walls? Surely I would have one fewer neighbor to deal with, but do vibrations attenuate if they travel to the side neighbors? Do the top neighbors hear anything at all?
The flat is a new building, although I can't find info about the material or the thickness of it. My drumset is a Millenium MPS-850 E-Drum Set.
Comment: On the ground floor, you're definitely better off for having no downstairs neighbors, but transmission to upstairs and side neighbors will really depend on the type of construction, which even for new buildings varies considerably around the world and even within one region.  Concrete and concrete masonry units are *probably* the least likely to allow transmission.  In my part of the world, these would be common choices for fire-resistant partitions between units of a new building.
Comment: Are we talking about an e-drum that you're using with headphones, so it's just the sound made by the physical motions? I've got to assume that ground floor would be best, since I'm guessing that's mainly about the pedals, and mainly about physical transmission through the floor, not through the air.
Comment: If it's any indication, I live in Western Europe and it looks like the material used is concrete. Does it matter how thick the wall is? I will be using the e-drum with headphones. From what I understand, it does seem that most of the disturbance comes from me hitting the foot pedal and possibly the rest of the kit to a lesser extent. I didn't have a vibration dampener platform though.
Answer: Using electronic drums with headphones is about as quiet as drum practicing can be. That doesn't mean it's always quiet enough for every environment, it just means it can't be much quieter.
One of the biggest problems that still remains with an electronic drum kit is that the action of the kick pedal on the floor can make a surprising amount of noise in the space below the floor. This means that getting a basement apartment in a building is very helpful in avoiding disturbing your neighbors.
The second biggest problem of electronic drums is the sticks on the pads still make some noise. Much quieter than real drums, but potentially loud enough to bother others. In general, the construction of the floor does not make much of a difference in terms of the loudness of sound of the sticks hitting the pads. Most of that sound is transmitted through the air.
If you can find an apartment that is a basement apartment and is at the corner of the building, that would be your best bet. Set up the kit in the place of the apartment closest to the corner of the building, farthest from the next door apartments. Close all interior doors in the apartment to reduce sound transmission from room to room. After you move in, try practicing on something like a Saturday afternoon. If you're social, meet your neighbors and ask them if they can hear it and/or what times and days would be least bothersome to them for you to make a moderate amount of noise.
That's about the best you can do.
Neighbors to the sides and above will be something to be sensitive about. With upper neighbors, the weight of flooring materials may quiet things down a lot more than the walls to the sides. If the building is composed of concrete decks for each floor, then the upstairs neighbors will probably be unaware of your playing electronic drums. Safer to not assume, though.
Comment: Support this. There is a simple test the TO can perform. Stomp heavily, or better use some suitable device, which won't damage the floor. Either you hear the problems immediately or from reports.
Comment: On a concrete slab with headphones it's *probably* fine. Anywhere else, welcome to the club where even your own family members hate you now. - I've an E kit in an attic atm; the kick pedal (*me*) makes the lights in the whole house flicker. -  "ask them if they can hear it" -um, they can hear it.... if they can't hear it then you don't have it sounding like an acoustic does. The best thing you can do is rent a space to do it in. - My Geo E-snare came with a rubber ring for the rim; ate through that on day one; sounds much better w/o it. Meaning: *loud* ;) .... and the fact that that's *real*.


Symbolic Links to Variables

Question: I'm working on a program where I would like to report the status of specific variables from time to time, however, I don't necessarily know which variables I'll need apriori. Other programs I have worked on (in C++) use a registration system where the variables of interest are registered with a central output processor once, then when program status needs to be reported, a central module gathers the data from the output variables and writes to an output file. So, the program flow would be something like this.
Example MyModule.py
from OutputProcessor import OutputProcessor

class MyClass():

    def __init__(self):
        op = OutputProcessor()

        # variable I want to report
        self.foo = None

        # register with output processor
        op.register_output_variable(self.foo, "Foo")

    def calc_foo(self, bar, rand):
        self.foo = bar ** rand

Example OutputProcessor.py
class OutputProcessor(object):
    # list or dict object containing the name and link information to variables of interest
    output_vars_data = []

    def __init__(self):
        pass

    def register_output_variable(self, var, name):
        OutputProcessor.output_vars_data.append({"link address": id(var), "name": name})

    def report_output(self):
        for data in OutputProcessor.output_vars_data:
            self.write_to_output_file(data)

    def write_to_output_file(self, data):
        # write all of the data to the output file here
        pass

Example Main.py
import random

from MyClass import MyClass
from OutputProcessor import OutputProcessor as OP

if __name__ == "__main__":

    cls_instance = MyClass()

    for i in range(100):
        cls_instance.calc_foo(i, random.randint(1, 10))
        OP().report_output()

My first question: is this even possible, or practicable? Second, if so, how would I go about doing this? There are going to be some nuances to deal with, like how to handle multiple instances of the same class reporting the same variable, but that seems like a small issue. Is there a way to implement this so that I'm always getting the current value of the variable, and not just an old copy of it?
Any thoughts, or suggestions?
Comment: You are defining calc_foo as a method of a class, not pure function. You cannot call it like that. But you can define it as `@staticmethod` and use it like `MyClass.calc_foo()`.
Comment: "from MyClass import calc_foo" this is not possible to import method
Comment: @PM2Ring yes, thank you. I hope it is clearer now. In essence, I would like to be able to register any arbitrary member variable with my register_var function, then report the status of those variables at any time during the program run.
Comment: It's not easy to do this sort of thing in Python, as Mad Physicist explains. A Python variable isn't like a C++ variable, the data model is quite different. You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder.
Comment: Python works by reference, *always*. This can still have problems when you use immutable classes. Take a look at attrgetter in the operator module.
Comment: Please take a look at the docs on [Python classes](https://docs.python.org/3/tutorial/classes.html), although not totally foreign, they don't work like C++ classes always. Certainly not superficially.
Answer: Aside from the scoping issues in your code, there is really one issue to keep in mind. Python does everything by binding a name to a reference. You are interested in getting the value assigned to a name, not to the reference it may have been bound to at registration time. This is sort of like a pointer-to-a-pointer in C and C++.
To keep track of arbitrary names, you need to keep track of their enclosing namespace as well. That way you can use the universal function getattr to fetch the latest value of your name. A namespace can be any instance (modules and classes are instances too).
Your registration method needs to keep track of the object containing the name of interest, the name itself, and the key you want to display it as:
op.register_output_variable(self, 'foo', "Foo")

The manager class can store the values in a dictionary. Instead of a nested dictionary, I'd recommend using a tuple or collections.namedtuple to hold the "pointer":
def register_output_variable(self, inst, attr, key):
    self.output_vars_data[key] = (inst, attr)

When you output the variables, do something like
for key, spec in self.output_vars_data.items():
    print(key, '=', getattr(*spec))

What this does is provide you with a way to reference object attributes by name instead of reference. If you set x.a = 1, register x.a, then do  x.a += 1, you'd want to get 2 as your value. The important thing to remember is that x.a will be bound to a different reference because integers are immutable in Python. You completely bypass this by registering x as the namespace, and 'a' as the name.
You can generalize further by adding a method to register indexable elements, like the elements of a list and values of a dictionary. You would register the instance and index/key instead of instance and attribute name. Take a look at operator.attrgetter and operator.itemgetter for more ideas.
This is just a broad suggestion. It does not address the inconsistent mess of static, class and instance namespaces you are using.
Comment: Thank you for your comments and suggestions. I will do some more prototyping on this based on what you have given. Currently, I do not think I will need to register elements in lists or dictionaries.

I obviously "don't know what I don't know" regarding the scoping issues. Having very little formal CS or programming training myself, I'd appreciate any suggestions on how to make my example better, so I can better understand how it should be done.

Symbolic Links to Variables


How to unify a sigma in a sigma to one sigma?

Question: For example lets say you want to express ABC (with ABC being matrices).
With A being m x r, B being n x r and C being r x z.
I want to express this with a sigma notation so I know:
$(ABC)_{ij}$ = $\sum_{k=1}^r (AB)_{ik}C_{kj}$
=> $\sum_{k=1}^r \sum_{l=1}^n A_{il}B_{lk}C_{kj}$
Now if I want to bring this together it will become $\sum_{k=1,l=1}$
but to what? What will be above the sigma sign? Will it be till
Answer: There's no really good way to notate that as a single summation. If you completely insist, you could write it as
$$ \sum_{(k,l)\in\{1,\ldots r\}\times\{1,\ldots,n\}} A_{il}B_{lk}C_{kj} $$
but it would be hard to say that makes the whole thing more readable than the double sum.
Answer: You could write
$$\sum_{k=1}^r\sum_{l=1}^nA_{il}B_{lk}C_{kj}=\sum_{k,l=1}^{k=r,l=n}A_{il}B_{lk}C_{kj}=\sum_{k,l=1}^{r,n}A_{il}B_{lk}C_{kj}=\sum_{k,l}A_{il}B_{lk}C_{kj}$$
but for clarity, it is better to write the double sum once before reducing it. Let it also be mentioned that such informal notation is more often used when the upper limits are equal, i.e., $r=n$.
If $r=n$, you could drop the sigmas altogether with Einstein's summation convention:
$$\sum_{k=1}^r\sum_{l=1}^nA_{il}B_{lk}C_{kj}\equiv A_{il}B_{lk}C_{kj}.$$


Relation between solutions of two sums

Question: I would like to show that the solutions $x$ to the following equation
$$
\sum_{n=1}^N {A_n \over x-r_n} = 0
$$
are $\textit{not}$ also solutions to the equation
$$
\sum_{n=1}^N {A_n \over (x-r_n)^2} = 0
$$
for $A_n$ satisfying $\sum_{n=1}^N A_n =0$ (the $A_n$ are not all zero, and $N\geq 3$). Is this true in general? My approach for trying to solve this has been to assume that there $\textit{is}$ such a solution $x$ and try to obtain a contradiction. For example, if there were such an $x$, then we would have
$$
\sum_{n=1}^N {A_n \over (x-r_n)^2} = 0 = \sum_{n=1}^N {A_n \over x-r_n}
$$
$$\Rightarrow \sum_{n=1}^N {A_n \over x-r_n} \left({1+r_n - x \over x-r_n}  \right) = 0
$$
but I'm not really sure where to go from here. Thanks!
Answer: We have
$$
\sum_{n=1}^N {A_n \over x-r_n}  = \sum_{n=1}^N {A_n \over (x-r_n)^2} (x - r_n) = x \sum_{n=1}^N {A_n \over (x-r_n)^2} + \sum_{n=1}^N {A_n r_n \over (x-r_n)^2}
$$
 If x solves both equations, then the first term is zero, and we have
$$
\sum_{n=1}^N {A_n r_n \over (x-r_n)^2} =0
$$
However, this is a different equation from
$$
\sum_{n=1}^N {A_n \over (x-r_n)^2} =0
$$
unless we have special cases that the coefficients $A_n$ and $A_n r_n$ are all proportional to each other.
So other then in these cases, the two equations have exactly the same structure, but with different coefficients, so  they won't have the same solution. This establishes the contradiction.
Comment: Great, thank you for this clear and concise answer!
Answer: This is false in general.
Counterexample:
Take $$f(x)=\frac{1}{(x-1)} + \frac{1}{(x-2)}+\frac{1}{(x-3)}= 0$$
Notice that $\lim_{x \rightarrow 1^-}f(x)=-\infty$ and $\lim_{x \rightarrow 1^+}f(x)=\infty$. By Intermediate Value Theorem, we get that a root lies between $1$ and $2$.
Similarly, a root lies between $2$ and $3$.
Note that when $x<1$, we get no real root as
$$f(x)=\frac{1}{(x-1)} + \frac{1}{(x-2)}+\frac{1}{(x-3)} < 0 $$
Similarly, when $x>3$, we get no real root.
But on the other hand,
$$g(x)=\frac{1}{(x-1)^2} + \frac{1}{(x-2)^2}+\frac{1}{(x-3)^2} > 0$$
So, it has no real roots.
Comment: This is a nice, explicit example - thanks Roby5!
Answer: Since
$$
f(x) = \sum\limits_{0\, \le \,k\, \le \,n} {{{A_{\,n} } \over {\left( {x - r_{\,n} } \right)}}} \quad  \Rightarrow \quad {d \over {dx}}f(x) =  - \sum\limits_{0\, \le \,k\, \le \,n} {{{A_{\,n} } \over {\left( {x - r_{\,n} } \right)^{\,2} }}}
$$
then $x_s$ will be a solution of both only if it is a zero with multiplicity $\geq 2$
of the resulting rational function.

Relation between solutions of two sums


How to concatenate pairs of row elements into a new column in a pandas dataframe?

Question: I have this DataFrame where the columns are coordinates (e.g. x1,y1,x2,y2...). The coordinate columns start from the 8th column (the previous ones are irrelevant for the question)
I have a larger example sample here, but here's a sample:
start_column = 8
df = pd.DataFrame(columns = ['x1','y1','x2','y2'],
                 data = [(0,0,1,0),(0,1,2,3),(-1,-2,None,None)])
for i in range(7):
    df.insert(0,'c'+str(7-i),'x')
df

I want to create a new column in the DataFrame as a list of xy pairs, as in:  df["coordinates"]=[[x1,y1],[x2,y2],[x3,y3]....]
What I've tried so far:
for row in df.iterrows():
   for i in range(1,total_count_of_xy_rows):
      df["coordinates"]=
             df[["x{}".format(i),"y{}".format(i)]].values.tolist()
   print(df)

Is there a better way to do this?
Comment: What is your code doing differently than expected?
Comment: how does your df look like?
Comment: I have added the dataframe snapshot
Comment: I need to add one more column in the df which can contains the list of the row [[x1,y1],[x2,y2]....]
Comment: And I am unable to count the number of x and y columns containing the data . Because some rows has x y upto 60 measn x60 and y60 and some row having the data upto x25 y25 hence the other are showing NAN .
Comment: A dataframe snapshot is no good. Since your problem is not related to reading from the Excel file, you should provide a sample dataframe (even small), as either a generating code (like I added in edit) or a copy-paste. To learn more, please visit: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples
Answer: You can create the new column by .apply-ing a custom list comprehension function across the different rows:
start_column = 8
coordinates_list = list(zip(df.columns[(start_column-1):-1:2],df.columns[start_column::2]))
df['coordinates'] = df.apply(lambda row: [(row[x], row[y])
                                          for x,y in coordinates_list if not any((pd.isna(row[x]), pd.isna(row[y])))], axis=1)

Using this example input, with the coordinate columns starting from the 8th column, as you stated in a comment:
df = pd.DataFrame(columns = ['x1','y1','x2','y2'],
                 data = [(0,0,1,0),(0,1,2,3),(-1,-2,None,None)])
for i in range(start_column-1):
    df.insert(0,'c'+str(start_column-1-i),'x')
df

    c1  c2  c3  c4  c5  c6  c7  x1  y1  x2  y2
0   x   x   x   x   x   x   x   0   0   1.0 0.0
1   x   x   x   x   x   x   x   0   1   2.0 3.0
2   x   x   x   x   x   x   x   -1  -2  NaN NaN

This will produce this output:
c1  c2  c3  c4  c5  c6  c7  x1  y1  x2  y2  coordinates
0   x   x   x   x   x   x   x   0   0   1.0 0.0 [(0, 0), (1.0, 0.0)]
1   x   x   x   x   x   x   x   0   1   2.0 3.0 [(0, 1), (2.0, 3.0)]
2   x   x   x   x   x   x   x   -1  -2  NaN NaN [(-1, -2)]

This deals with the unequal number of coordinates in each row. Hope that helps!
Comment: I need to start the list zip from the 8th column means from x and y are starting from 8th column . How to for this ?
Comment: Please assist, I am unable to provide the above conditon where x y are starting from the 8 th column number
Comment: I've edited your question again to include this new condition, and my answer to accommodate it. In the future, please make sure that your answer includes all the information needed to answer the question. I've edited your question to make sure the example data includes this new condition.
Comment: Related to this answer I have posted one question kindly suggest for the issue
https://stackoverflow.com/questions/58109579/how-to-create-the-subcolumns-in-the-dataframe-and-add-the-data-using-pandas-in-p?noredirect=1#comment102609387_58109579
Comment: Kindly suggest for the issue posted at
https://stackoverflow.com/questions/58112213/how-to-read-the-sublist-from-the-main-list-and-add-the-sublist-in-the-another-da


Pass info to multiple viewControllers via iCarousel

Question: I'm trying to implement an iCarousel that will pass information on to two other view controllers when an image is chosen.  While the iCarousel loads perfectly and transitions to the next VC, the information is not displayed on the new VC.
The approach I chose was to create an NSObject file. I can't simply pass the info from VC to VC since I have several VC's that need the information and I'd prefer not to create a singleton or use AppDelegate if possible.
FYI: I do have a tap gesture recognizer added on top of the UIView that acts as the segue to the next VC if that makes any difference.
I've tried every possible tutorial out there and can't seem to figure out my problem. I just need to display a text label and a picture, which should really be pretty easy. Can someone take a quick glance at my code to see what I'm doing wrong?
My NSObject File:
<code>#import <Foundation/Foundation.h>
@interface Stop : NSObject

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *image;
@end
</code>
First ViewController.h (with iCarousel on it):
<code>#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "iCarousel.h"
#import "DirectionsViewController.h"
#import "Stop.h"

@interface StopsMenuViewController : UIViewController <iCarouselDataSource, iCarouselDelegate>

@property (strong, nonatomic) IBOutlet iCarousel *carousel;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;

//Title
@property (nonatomic, strong) NSArray *stopTitles;
@property (nonatomic, strong) NSString *stopChosen;

//Image
@property (nonatomic, strong) NSArray *stopImages;
@property (nonatomic, strong) NSString *imageChosen;
@end
</code>
First ViewController.m:
<code>#import "StopsMenuViewController.h"

@interface StopsMenuViewController () {
NSMutableArray *allInfo; }
@end

@implementation StopsMenuViewController
@synthesize titleLabel, carousel, stopImages, stopTitles, stopChosen, imageChosen;

- (void)awakeFromNib {
NSString *myPlist = [[NSBundle mainBundle] pathForResource:@"Chinatown" ofType:@"plist"];
NSDictionary *rootDictionary = [[NSDictionary alloc] initWithContentsOfFile:myPlist];

self.stopImages = [rootDictionary objectForKey:@"StopImages"];
self.stopTitles = [rootDictionary objectForKey:@"StopTitles"];
}

- (void)carouselDidScroll:(iCarousel *)carousel {
[titleLabel setText:[NSString stringWithFormat:@"%@", [self.stopTitles
objectAtIndex:self.carousel.currentItemIndex]]];
}

- (void)dealloc {
self.carousel.delegate = nil;
self.carousel.dataSource = nil;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"toDirections"])
{
DirectionsViewController *dvc = [segue destinationViewController];
int itemId = [self.carousel currentItemIndex];
NSIndexPath *path = [NSIndexPath indexPathForRow:itemId inSection:0];

Stop *current = [allInfo objectAtIndex:path.row];
[dvc setPassInfo:current];
}
}

- (void)viewDidLoad {
[super viewDidLoad];
self.carousel.type = iCarouselTypeCoverFlow2;

allInfo = [[NSMutableArray alloc] init];

Stop *info = [[Stop alloc] init];
stopChosen = [NSString stringWithFormat:@"%@", [self.stopTitles objectAtIndex:self.carousel.currentItemIndex]];
[info setTitle:stopChosen];
[allInfo addObject:info];

info = [[Stop alloc] init];
self.imageChosen = [NSString stringWithFormat:@"%@", [self.stopImages
objectAtIndex:self.carousel.currentItemIndex]];
[info setTitle:self.imageChosen];
[allInfo addObject:info];
}

- (void)viewDidUnload
{
[super viewDidUnload];
self.carousel = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}

- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel {
return [self.stopImages count];
}

- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel {
return 4;
}

- (UIView *)carousel:(iCarousel *)_carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {
if (view == nil)
{
view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self.stopImages objectAtIndex:index]]];
}
return view;
}

- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
DirectionsViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"dvc"];
[self.navigationController pushViewController:dvc animated:YES];
}
@end
</code>
Second ViewController.h:
<code>#import <UIKit/UIKit.h>
#import "Stop.h"

@interface DirectionsViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) IBOutlet UIImageView *imageBox;

@property (nonatomic, strong) Stop *PassInfo;
@property (nonatomic, strong) NSString *stopTitle;
@property (nonatomic, strong) NSString *myStopTitle;
@end
</code>
Second ViewController.m:
<code>#import "DirectionsViewController.h"

@interface DirectionsViewController ()
@end

 @implementation DirectionsViewController
 @synthesize PassInfo;

- (void)viewDidLoad {
[super viewDidLoad];

[self.titleLabel setText:[PassInfo title]];

UIImage *image = [UIImage imageNamed:[PassInfo image]];
[self.imageBox setImage:image];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
</code>
Answer: Instead of
<code>- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
  DirectionsViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"dvc"];
  [self.navigationController pushViewController:dvc animated:YES];
}
</code>
Use
<code>- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
  [self performSegueWithIdentifier:@"toDirections" sender:self];
}
</code>
In your code, you're instantiating the second view controller and presenting it, which is not the same as performing a segue. Therefore the method <code>- prepareForSegue:sender:</code> will not be invoked.
Comment: If the answer helped you, please mark it as correct but clicking on the checkmark next to it ;)


How do you solve this equation: $10 = 2^x + x$?

Question: Is it possible to solve this equation?
\begin{align}
a &= b^x + x \\
a-x &= b^x \\
\log_b(a-x) &= x
\end{align}
If $a$ and $b$ are known, how do you find $x$?
Comment: Not actually a solution but notice that $f(x)=10-x$ is strictly decreasing, $g(x)=2^{x}$ strictly increasing and $f(2)>g(2)$ and $f(3)$. I'm really not sure if there is an exact solution.
Comment: Numerical methods will work because the right hand side of your initial equation is increasing (assuming $b \gt 1$)
Answer: As noted in the comments, since the function is monotonically increasing, there is only one real solution. To find the solution for say $10-2^x-x=0$, you can use Newton's method to iterate:
$$x_{n+1} = x_n-\frac{10 - 2^x - x}{2^x\ln 2-1}$$
Alternatively, you could use the Lambert $W$ function to write the solution as:
$$x = 10 -\frac{W(2^{10} \ln(2))}{\ln(2)}$$
To get to this, use the definition:
$$x = W(x)\exp(W(x))$$
And define $y= 10-x$, and use $W(y)$.