ASP.NET can't cache null value

Question: Can anyone explain why you cannot insert a null object into the ASP.NET cache?
string exampleItem = null;

HttpRuntime.Cache.Insert("EXAMPLE_KEY",
                        exampleItem,
                        Nothing,
                        DateTime.Now.AddHours(1),
                        System.Web.Caching.Cache.NoSlidingExpiration);

The exception error message states that the "value" object cannot be null. In my application there are valid reasons why we whould want to store a null value in the cache.
Answer: Underlying Cache is likely a Hashtable or Dictionary<string, object>, whose getters do not differentiate between no value at that key, or a null value at that key.
Hashtable table = new Hashtable();
object x = table["foo"];
table.Add("foo", null);
object y = table["foo"];
Console.WriteLine(x == y); // prints 'True'

Consider a using placeholder "null" item, similar to DbNull.Value.
Comment: Dictionary *does* differentiate between null and no value.  Getting the value for a key that doesn't exist throws a KeyNotFoundException, and storing a null value is valid.
Comment: Late to the party, but just for information, it seems that the MemoryCache communicates a missing key by returning 'null'.
So if it allows inserting null values, it will not know the difference between the two.
Comment: Ah.  I only tested Hashtable.  Somewhat more evidence that Cache is based on Hashtable, with a pre-insert check.
Answer: As a possible alternative or work-around, you can instead store an object rather than your value. For instance (this assumes your value is a string, but it could be generic)
public class CacheItemWrapper
{
    public string Value { get; set; }
}

...
cache.Insert(cacheKey, new CacheItemWrapper { Value = null }, ...);

That way you are never inserting null. To get the value back, you just extract it from the wrapper:
var val = cache.Get(cacheKey);
if (val != null) return val.Value;

(This is all off the top of my head, so apologies for any silly typos.)
Comment: I've used a similar pattern but just used a Tuple for my wrapper; that way I can have it cache multiple types of items as specified and don't have to worry about the object itself barfing on the null insert into the cache
Comment: This works great with my existing caching mechanism with little modification thanks.
Comment: That's a nice workaround. Another decent option is using Null Object Pattern as described here http://stackoverflow.com/a/9820884/1302581.
Answer: To clarify Michael Petrotta's accepted answer a bit (too long for a comment, I'm afraid), the concrete implementations of CacheInternal (CacheSingle and CacheMultiple, the latter of which merely manages multiple instances of the former), which is what's utilized internally by the public Cache type to support its Get, Add, Insert, etc. methods, do rely on a HashTable for storage.  However, there's never any question of whether there is or isn't a value for a particular key in the HashTable, because the native (cached) values aren't stored in the HashTable directly.  Instead, the HashTable is filled with unique CacheEntry objects that wrap the cached keys and values (CacheEntry actually derives from CacheKey, adding an Object-based Value property, among other things; the non-null value requirement can be found in its constructor).
Based on my reading of the code, there's no obvious technical reason for the authors to have required a non-null CacheEntry.Value, except that the public Cache object doesn't expose a Contains- or Exists-type method, and of course doesn't expose the internal underlying CacheEntry objects, it only returns the CacheEntry values.  So, as per Michael's answer, without forcing values to be non-null it isn't possible for Cache object users to know whether a particular key value exists.  It's also possible, but would require more code reading to know for sure, that the rather complex approach taken internally to manage cached object dependencies, expirations, events, and in-place updates of HashTable entries might rely, in some way, on the values being non-null.

ASP.NET can't cache null value


Is zookeeper used only for kafka if others then can some one give realtime example?

Question: While I am creating cluster setup for kafka I came to know zookeeper quorum set up  is needed for coordination between kafka brokers.
Are there any other scenarios where we use zookeeper other than only for kafka setup in real time?
Comment: Does this answer your question? [Real World Use of Zookeeper](https://stackoverflow.com/questions/1479442/real-world-use-of-zookeeper)
Answer: This link lists many applications and organisations using ZooKeeper
https://zookeeper.apache.org/doc/r3.6.2/zookeeperUseCases.html
ZooKeeper is used with many Apache projects and is a distributed coordination service used to manage a large set of hosts. In simple terms, Zookeeper allows workers to get on with their jobs and handles all the other complexities i.e. if a leader goes down, alerting the workers, electing a new leader etc.


Why is that only one element triggers the action even though I used .each?

Question: I'm using this to take the value of an input and put it into another one at the end of the page:
jQuery( document ).ready(function() {
  jQuery('.free-lesson input[type="text"]').each(function () {
    jQuery(".free-lesson input[type='submit']").click(function(e) {
      e.preventDefault();
      var freeLessonContent = jQuery(this).val();
      jQuery("#mce-EMAIL").val(freeLessonContent);
    });
  });
});

there are many .free-lesson divs but strangely only the last one works (the others don't put any value to the input in the form.
How to fix this?
This is the site: http://www.chineselearnonline.com/amember/signup40.php
Comment: Why do you need here `.each`? If you want it to be related to `jQuery(this).val();` then you are doing it slightly wrong. `this` in that scope is not related to `this` of `.each`
Answer: You don't need to add the foreach in there. The this you reference in the foreach is not th element you need. Try this out.
jQuery('.free-lesson-form [type="submit"]').click(function(e){
  e.preventDefault();
  jQuery('#mce-EMAIL').val(jQuery(this).prev().val()); //find the element previous to the one that was clicked.
  //You may also want to use .parent() and find the input as this is more reliable if you move the markup around
});

What I've done here is to bind to the click event of all submits inside the free-lesson-form div. And then capture the value of the text input that is next to the button that was clicked. Tried this out on your site and it works for the current markup.


Least prime of the form $38^n+31$

Question: I search the least n such that
$$38^n+31$$
is prime.
I checked the $n$ upto $3000$ and found none, so the least prime of that form must have more than $4000$ digits. I am content with a probable prime, it need not be a proven prime.
Comment: If $n$ is odd, then $3 \vert (38^n+31)$. If $n$ is of the form $4k+2$, then $5 \vert (38^n+31)$. The only case to be proved is $38^{4k}+31$ is not a prime.
Comment: Are you trying to crack some secret key? What got you interested in these numbers?
Comment: @lhf Yes, for multiple of $4$, interestingly the prime factors get larger if $n \neq 12k+4$. If $n=12k+4$, then $7$ divides $38^n+31$. Hence, the only $n$'s that needs to be checked are $n=12k$ and $n=12k+8$.
Comment: If my idle-time computer calculation is correct, the expression is not prime for $n<185000$.
Comment: Obviously, since nothing is lesser than $-\infty$, and since $39^{-\infty}+31=0+31=31$ is prime, this is then "*the least n such that $39^n+31$ is prime*". :-)
Comment: No, @TonyK, that's a joke. :-)
Comment: Just to clarify : I only search this prime for curiousity. And public keys work with factorizations. (before someone draws wrong conclusions)
Comment: @Peter [I can't](http://www.sans.org/reading-room/whitepapers/vpns/prime-numbers-public-key-cryptography-969) tell you, this is [classified](http://www.livinginternet.com/i/is_crypt_pkc_work.htm).
Comment: No prime for $185,000\leq n\leq 200,000$.
Comment: I have compiled a list of all prime numbers < $100000$ which can sometimes divide $38^n+31$.  Basically, the same thing @user17762 did in his comment above for $3$ and $5$, I did for a lot more primes.  Here is the [data](https://github.com/PhiNotPi/Primes/blob/master/ListOfDivisors) on GitHub.
Comment: @Alessandro I have calculated that $38^{12*131701}+31$ is divisible by $16596077$.
Comment: @user17762, for $n=4$ the smallest factor is 7, for $n=8$ it is 577. Doesn't seem straightforward.
Comment: The following Mathematica code--Simplify[PrimeQ[38^n + 31], n \\[Element] Integers && n >= 1]--gives False.
Comment: @StellaBiderman My search went up to $220,000$ for now, without finding a prime (usual disclaimer about correctness of the computations applies, of course).
Comment: @julien what has searching a prime to do with cracking a key ?
Comment: Just in case it's worth noting: carrying out @user17762's logic, we get the precise result that $s=38^k+31$ has no prime factors smaller than 47 iff $k=0$ or $8$ mod $12$.

We can exclude all primes less than 70 quite easily too, by excluding $k=34$ mod $46$ and $k=2$ mod $58$.
Comment: A slight addition to my last comment: if we only allow $k=0$ or $8$ mod $12$, and exclude $k=34$ mod $46$, $k=2$ mod $58$, and $k=18$ mod $70$, the resulting $s=38^k+31$ has no prime factors less than $103$.
Comment: @Lucian: That's gibberish.
Comment: I arrived at n=4000 (about 6300 digits)
Comment: Peter, do you mean $38^{4000}+31$ is prime, or that you have not found primes that far up?
Comment: Alas, it is no prime.
Comment: n=5000, still no primes.
Comment: $38\equiv-1\mod3$, and $31\equiv1\mod3$.
Comment: This is like a Mersenne prime. Try a multiple of 131701.
Comment: If for some integer $a$, $a | (38^n + 31)$, then $38^n + 2^5 \equiv 1 \pmod a$. By Euler's Theorem, $38^n + 2^5$ can then be written (modulo $a$) as an integer power $k^{\phi(a)}$ for some $k$ coprime to $a$. Perhaps this might be useful!
Comment: @WangiPaPa: Wolfram alpha says "unknown" when asked if $38^{12*131701}+31$ is prime while it has no problem handling bigger exponents (which, as far as I have tested are composite), I'm afraid this number is too big to be checked on a normal computer though so I don't really know if this can be helpful
Comment: Sure, I'll get right to that. Does anybody have a super computer I can borrow?
Comment: @Peter: Have you thought about cross-posting this on *MathOverflow* ?
Comment: similar question just asked. I'm not learned enough to comment on comparable difficulty of the two.
http://math.stackexchange.com/questions/760966/is-324455n-ever-prime
Comment: We have that $47\mid (38^{4k}+31)$ when $k=20 \mod 46$.
Comment: I generalized and computerized the approach I was taking in the above comments and found out that if $n$ is of the form $36k+8$ then $577\mid 38^n+31$. The next 'most common' prime divisor I found is $93377$ which albeit the $n$ have a closed form they are not nearly as nice and there are two distinct linear sequences for the $n$.
Comment: @PhiNotPi how did you generate that table on github? I came up with a way to generate $k$s that we don't need to test but instead of working with one equivalence class I was working with often a couple mod $p-1$. Going back and checking what I had with yours was the same, but yours is much more compact and with a different modulus.
Comment: @Bryan I used Mathematica.  Here is [the code](https://github.com/PhiNotPi/Primes/blob/master/ListOfDivisorsCode).
Comment: Are you familiar with http://www.seventeenorbust.com ? It might give you some idea of how hard these problems are.
Comment: @PeterKošinár Did you use the PFGW ("PrimeForm with George Woltman's library") software for that?
Comment: @JeppeStigNielsen Indeed, I used OpenPFGW (which is based on the original PFGW).
Comment: Very late to this, but note that one way of showing non-primality for numbers of this form can be to exhibit them as the values of a linear recurrence relation with constant coefficients and exhibit divisibility properties of the values of the recurrence relation; see e.g. https://math.stackexchange.com/questions/1090319/is-f-n2-28-always-a-composite-number/1090340#1090340 for an example of a similar approach.
Comment: Compare this question to the [same question for](https://math.stackexchange.com/questions/760966/) $$455^{4k}+324$$ [(follow link)](https://math.stackexchange.com/questions/760966/) In that case, because $324$ is four times a perfect fourth power, the answer is different because an Aurifeuillean factorization arises for every exponent $4k$.
Comment: @Peter I think that they are all composites.
Answer: This is not a proof, but does not conveniently fit into a comment.
I'll take into account that $n=4k$ is required, otherwise $38^n+31$ will be divisible by $3$ or $5$ as pointed in the comments.
Now, if we treat the primes as "pseudorandom" in the sense that any large number $n$ has a likelihood $1/\ln(n)$ of being prime (which is the prime number density for large $n$), the expected number of primes for $n=4,8,\ldots,4N$ will increase with $N$ as
$$
\sum_{k=1}^N\frac{1}{\ln(38^{4k}+31)}
\approx\frac{\ln N+\gamma}{4\ln 38}
\text{ where }\gamma=0.57721566\ldots
$$
and for the expected number of primes to exceed 1, you'll need $N$ in the order of 1,200,000.
Of course, you could get lucky and find it at much lower $n$, but a priori I don't see any particular reason why it should be...or shouldn't.
Basically, in general for numbers $a^n+b$, the first prime will usually come fairly early, otherwise often very late (or not at all if $a$ and $b$ have a common factor).
Of course, this argument depends on assuming "pseudorandom" behaviour of the primes, and so cannot be turned into a formal proof. However, it might perhaps be possible to say something about the distribution of $n$ values giving the first prime over different pairs $(a,b)$.
Comment: A slight refinement of your heuristic:  Notice that $38^{4k} + 31$ cannot be divisible by 2, 3, 5, or 31.  If we're given a "random" number $N$ not divisible by these four primes, then its likelihood of being prime increases to $\frac 21 \frac 32 \frac 54 \frac{31}{30} \frac{1}{\ln N} = \frac{31}{8 \ln N}$.  This adjustment would suggest that the first such prime should occur around $k = 24$, the second around $k = 1000$, the third around $k = 40000$, the fourth around $k = 1900000$, etc.
Comment: Also, a value of $n$ over $11030099$ would represent the largest known prime number. Based on your formula above, this gives an expected number of primes still just slightly over $1$.
Answer: Primality of numbers of the form $a^n+b$ is a very hard problem in general. For instance, existence of primes of the form $4294967296^n+1=(2^{32})^n+1$ is an old open problem in number theory (wiki), although it is also easy to show that this can be a prime only for $n$ of a special form (powers of $2$). Your problem $2085136^n+31=(38^4)^n+31$ does not seem much easier.
In other words, a theory-based answer to your problem is very unlikely in the near future. For a practice-based answer you will probably need to use some distributed computing project for searching for prime numbers like PrimeGrid, which has found most of the known large primes of the form $ab^n+c$.
Answer: This should be a comment for @Einar Rødland, but it's too long so I'm making it an answer.
Your argument gives a heuristic that there should be infinitely many primes of this form, but I'm not sure I believe it and here's why:
You are only taking into account the first two "bad" arithmetic sequences when you restrict to looking at things divisible by 4.  In fact we have infinitely many "bad" arithmetic sequences we need to throw out.
If we try the same argument for numbers of the form $2^n + 1$ and we throw out $n \equiv 1 \mod 2$ and $n \equiv 2 \mod 4$ as they will all be divisible by 3 or 5, then running your argument would tell us to expect infinitely many primes of this form. However if we throw out all the "bad" arithmetic sequences (which in this case are much easier to classify) then we only are left with $n = 2^k$, taking this into account your heuristic gives finite expectation.
These two problems don't seem that different to me on the surface, and without a better understanding of the higher order "bad" arithmetic sequences, it's not clear to me what the right heuristic should be.
Comment: This is one of the reasons it is a heuristic argument. In some cases when this type of arguments are formalised, we talk of the _generic case_ which e.g. could be that it would work for "most" expressions of the form $a^n+b$. (In algebraic geometry, "generic" means that the cases are parametrised by some space and the counter-examples are a subspace of lower dimension.) The case $a^n+1$ fails because $a^q+1|a^{qr}+1$ for any odd $r$, and so requires $n=2^k$ for $a^n+1$ to be prime.
Answer: In general, is there any prime of the form $\frac{ab^n+c}{\gcd(a+c,b-1)}$ with integer $n\ge1$, for fixed integers $a\ge1$, $b\ge2$, $c\ne0$, $\gcd(a,c)=1$, $\gcd(b,c)=1$? It is unknown whether this problem is solvable, e.g. let $a=4$, $b=72$, $c=-1$, the smallest prime of the form $\frac{4\cdot72^n-1}{\gcd(4+1,72-1)}$ with $n\ge1$ is at $n=1119849$
If we want to solve this problem, we must for every such $(a,b,c)$ integer triple, either find a prime of this form or prove that there is no prime of this form, e.g.:
$(a,b,c) = (78557,2,1)$, in which all numbers are divisible by at least one of $3, 5, 7, 13, 19, 37, 73$
$(a,b,c) = (11047,3,1)$, in which all numbers are divisible by at least one of $2, 5, 7, 13, 73$
$(a,b,c) = (47,8,1)$, in which all numbers are divisible by at least one of $3, 5, 13$
$(a,b,c) = (334,10,-1)$, in which all numbers are divisible by at least one of $3, 7, 13, 37$
$(a,b,c) = (9,4,-1)$, in which all numbers factored as difference of squares
$(a,b,c) = (1,8,1)$, in which all numbers factored as sum of cubes
$(a,b,c) = (25,12,-1)$, in which even $n$ factored as difference of squares and odd $n$ is divisible by $13$
$(a,b,c) = (64,936,-1)$, in which even $n$ factored as difference of squares and $n$ divisible by $3$ factored as difference of cubes and other $n$ divisible by either $37$ or $109$, etc.

Least prime of the form $38^n+31$


Does the Thread still exist if the JVM crashes?

Question: I was asked this question during an interview, does anybody know?
Comment: If I was asked that in an interview, I'd ask them to clarify what they meant ...
Comment: Green threads, POSIX threads, or JVM-implementation specific Thread objects?  Reminds me of, "What is the air-speed velocity of an unladen swallow?"  Not every interview question is meant to be answered literally, vague questions are prompts to see if you'll ask the right follow up questions.
Comment: What thread? What do you mean by "crashed"?
Comment: In what would the thread be running?
Comment: @Edwin Buck Is there any way that a thread created by a process survives longer than the creating process? I'd be quite surprised by that (but who knows, maybe some strange corner case in the posix standard?) and if not there's no way for a thread created by the JVM to survive after it crashes. Now the JVM can create a new process and spawn threads there, but then the thread wasn't created by the JVM..
Comment: @Voo, I think you misunderstand.  From the context of the question, it sounds like this is an interview question that shouldn't be answered directly without further clarification.  Is the Thread in question across a java RMI connection?  If so, the JVM might crash but the remote object (a thread?) might live.  That's just a guess, in reality you need to ask a lot of questions to get a what the interviewer was looking for.
Answer: If JVM exits as a result of crash the thread will not exist anymore. If crash is some kind of out of memory or similar error, it may or may not exist depending on specific circumstances.
Answer: If a thread is running the JVM has not crashed.
However, sometimes people incorrectly describe any exception being throw as a crash. If this is what the interviewer meant, I would say the thread is still running because the exception was caught and not rethrown.
Answer: If the process that contains the JVM is closed, all its threads are closed as well. This is taken care of at the OS level, when the OS cleans up all the memory allocated to a given process.
I mention the process-level closure to distinguish it from other weird, unknown states that the JVM might happen into that leaves it running, but in an unknown state (maybe it's not actually doing anything, for example).
Similarly, if you kill the process, all the child threads will close, regardless of their type (daemon / non-daemon).
Answer: Imagine you're the JVM.   You walk out on to the road, not really looking where you are going and you have a fatal accident.  An instant before the unfortunate happens, you had 30 things on your mind.  Imagine those things on your mind as "threads"
When you're being swept up from the road, do you think you'll still be conscious and have all of those things on your mind?
Answer: An execution instance of the JVM is a process.
Threads are a part of a process.
If the process is dead, everything that was a part of it is dead.
So, when your JVM crashes or has been terminated forcefully, all the threads created by it stop executing as well.
Moreover, the JVM terminates automatically when the only threads running inside it are daemon threads.


Investigating limit of theta like series

Question: Let $v>0$. I want to prove
$$\lim_{t \to \infty} \sum_{a \in \mathbb Z} \sum_{b=1}^\infty \exp \left(-v(a/t+bt)^2\right) = 0.$$
It looks quite similar to the theta function
$$\theta(z) = \sum_{n \in \mathbb Z }e^{\pi i n^2 z}$$
which is defined on the upper half plane and obeys the transformation law
$$\theta\left(- \frac{1}{z}\right) = \sqrt{ \frac{z}{i} } \theta(z).$$
Maybe my original series can somehow be decomposed into a product of two such theta series and then we can use
$$\lim_{t \to \infty} \theta(it)=1$$
and $|\theta(it)-1| < C e^{-\pi t}$.
Comment: since everything is positive, it looks like replacing sums with integrals should be a pretty good idea
Answer: Note that for any $c > 0$ and $a_0 \in \mathbb{R}$, if $\{a_0\} = a_0 - \lfloor a_0 \rfloor$ denotes the fractional part of $a_0$, then
\begin{align*}
\sum_{a\in\mathbb{Z}} e^{-c (a - a_0)^2}
&= \sum_{a\in\mathbb{Z}} e^{-c (a - \{a_0\})^2}
= \left(\sum_{a\in\mathbb{Z}} e^{-c (a - \{a_0\})^2} \right)^{\frac{1}{2}}\left(\sum_{a\in\mathbb{Z}} e^{-c (a + \{a_0\})^2} \right)^{\frac{1}{2}} \\
&\stackrel{\text{(C–S)}}{\geq} \sum_{a\in\mathbb{Z}} e^{-c(a^2 + \{a_0\}^2)}
\geq \sum_{a\in\mathbb{Z}} e^{-c(a^2+1)}.
\end{align*}
Note that this lower bound does not depend on $a_0$. Therefore,
\begin{align*}
\sum_{a\in\mathbb{Z}}\sum_{b=1}^{\infty} e^{-v(a/t + bt)^2}
= \sum_{b=1}^{\infty} \sum_{a\in\mathbb{Z}}e^{-(v/t^2)(a + bt^2)^2}
\geq \sum_{b=1}^{\infty} e^{-(v/t^2)(a^2+1)}
= \infty.
\end{align*}
and the limit as $t\to\infty$ also diverges to $\infty$.


Avoid decimal part in python

Question: Is there a way in Python to avoid the decimal part of number result when it is zero?
When a = 12 and b = 2 I want:
print(a/b)

to print:
6   # not 6.0

and if a = 13 and b = 2
6.5 # not 6

in a generic way.
Comment: Possible duplicate of [Formatting floats in Python without superfluous zeros](https://stackoverflow.com/questions/2440692/formatting-floats-in-python-without-superfluous-zeros)
Answer: You can use floor division if b divides a without remainder and normal division else:
data = [ (12,2),(13,2)]

for a,b in data:
    print(f"{a} / {b} = ",  a // b if (a//b == a/b) else a / b)

Output:
12 / 2 = 6
13 / 2 = 6.5

This is a ternary coditional statement (more: Does Python have a ternary conditional operator?) and it evaluates a//b == a/b.
a//b is floordiv and a/b is normal div, they are only ever equal if b divides a without remainder (more: What is the difference between '/' and '//' when used for division?)
Answer: You can use the int()/ round() methods. All one would have to do is
print(int(a/b))

Comment: but i dont want to check for every result if it has decimals or if it doesnt have(.0).

Avoid decimal part in python


Can i change about:config in mozilla via javascript?

Question: Hello I am developing a HTML 5 game and in Chrome the animations looks great but in firefox not! I was searching over the internet and i found a solution that i need to change some settings in about:config and they are:
webgl.force-enabled=true
webgl.msaa-force=true
layers.acceleration.force-enabled=true
gfx.direct2d.force-enabled=true
stagefright.force-enabled=true

I change those setting manually and the animations looks great in Firefox. Now my question is how can I do that using javascript? Is it possible?
Comment: Hopefully not !
Comment: Nope, would'nt that be great for all the webs delinquents if they could just change the browser settings as they pleased!
Comment: Why the down vote and vote to close? This is a legit question, written clearly with some research shown on the matter. It is a constructive question. While you may not want browsers to implement the behavior asked for, it's certainly a legit question.
Comment: @tkone the meaning of my comment is: if there is a way for a website to modify `about:config` globally, then it's an enormous security threat.
Comment: At least not from an arbitrary website.
Comment: @JanDvorak that's a quite unconstructive comment. As shown in the answers there ARE solutions to this issue (extensions). While you might not want someone to do it, this does NOT serve as a honest comment or response to the question at hand.
Comment: @JanDvorak But the question being asked is not about security or anything, but rather how would someone be able to modify it. There is a way (writing an extension) which would satisfy the OP's question AND your security concerns. Always assume that unless specifically stated, all solutions to the issue are open to the OP.
Comment: @tkone I also (incorrectly?) assumed that installing an extension/plugin was not an option. Note the answer doesn't (and shouldn't) work from a web page.
Comment: @JanDvorak why make that assumption? There's nothing stated in the original question which would lead me to believe that the OP is not interested in anyway that this can be accomplished. Your comment could have been used to help further clarify the OPs intent as to how they were wanting to accomplish this goal.
Answer: A discussion in the MozillaZine forum suggests creating a bookmarklet as follows (instructions and code copied from there):

Make a file in your Firefox installation folder, under the res directory, called for example 'proxy.htm', and put this in it:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <title>Proxy Toggle</title>

   Please wait...

Then make a bookmarklet to toggle the state of the proxy pref, and put this as the location:
javascript: void(window.open('resource:///res/proxy.htm'));

See: http://forums.mozillazine.org/viewtopic.php?f=7&t=87755
Comment: @WladimirPalant bad advice, however answers the question. the question was not "is this a good idea" but rather "how can i do this." making a remark about it being bad advice is good. down voting (in favor of your answer) is sort of petty. answering the question is important; even giving advice is important. but down voting a legitimate answer that honestly solves the issue being asked seems a little odd.
Comment: Thank you for an answer that actually attempts to help the OP out with their issue.
Comment: @tkone Unfortunately it wasn't an actual answer before my edit. Link-only answers are frequently deleted from StackOverflow, because the links can break and the answer becomes useless. We're encouraged to edit those answers to add quotes the relevant parts from the link, or flag them as not an answer.
Comment: @liquidboy don't forget to accept the answer if you find it satisfactory. Note the empty checkmark beside the answer.
Comment: Nifty trick but I still have to downvote it because it is a horribly bad advise in the context of this question (see my answer).
Comment: @tkone: Welcome to Stack Overflow, the place where a good answer is supposed to point out the misconceptions that the question is based on. Giving people a footgun and playing innocent after that doesn't help anybody.
Comment: @WladimirPalant Welcome to Stack Overflow where knowledge is apparently used as a lever to make those who don't have it feel less than those who do have it, and any attempt that can be made to ridicule someone must be attempted lest the OP start to feel, in some way shape or form, adequate.
Answer: You should not change these settings - not on your computer and especially not on computers of other people. These settings will be enabled anyway, assuming that the hardware and drivers are capable of handling them. The force-enabled settings are for testing only, switching them on is likely to cause instability (Firefox crashes, graphics driver crashes).
Most likely reason why Firefox didn't enable hardware acceleration automatically in your case are outdated drivers - you should install current drivers for your graphics card and recommend other people to do the same.


What is the difference between sudo apt-get install and sudo apt install

Question: I installed many packages from sudo apt-get install but when I typed  sudo apt --help it gave a direct option of doing installation by sudo apt install [package name]... So, what is the difference between the two ? are there any issues if I don't use 'get' along with 'apt'.
Comment: Possible duplicate of [What is the difference between apt and apt-get?](http://askubuntu.com/questions/445384/what-is-the-difference-between-apt-and-apt-get)
Answer: Not much. apt is a new command that supposed to merge several functions from apt-get and apt-cache into one command. It's still a little rough around the edges but here's the command listing from --help:
Basic commands:
 list - list packages based on package names
 search - search in package descriptions
 show - show package details

 update - update list of available packages

 install - install packages
 remove  - remove packages

 upgrade - upgrade the system by installing/upgrading packages
 full-upgrade - upgrade the system by removing/installing/upgrading packages

 edit-sources - edit the source information file

The equivalent functions are designed to work in similar ways but it's not a proxy command (it's not calling the old ones - it's a new interface directly onto the Apt libraries) so there may be some edge-case changes.
There are also some obvious omissions (download, policy, etc) that power-users will miss and there are a whole raft of undocumented commands (purge still works but I can't find anything on it).
16.04 Update: A lot of the omissions have now been included but aren't yet documented, nor do they have Bash-completions. It's a shame it's taking this long to implement functionality that already exists in the codebase but oh well. My advice is that if you're used to an apt-{get,cache} command, try it on apt. It might work.

There's also a DIFFERENCES TO APT-GET(8) section in the man apt page that's interesting:
   The apt command is meant to be pleasant for end users and does
   not need to be backward compatible like apt-get(8). Therefore
   some options are different:

   ·   The option DPkgPM::Progress-Fancy is enabled.

   ·   The option APT::Color is enabled.

   ·   A new list command is available similar to dpkg --list.

   ·   The option upgrade has --with-new-pkgs enabled by default.

And if you want Bash-completions, I've had an attempt as writing a completions file for it already. These are included with later Ubuntu installs.
Comment: How about `aptitude`?
Comment: That's from a completely different codebase. Functionally it will also automatically autoremove after doing package operations.


line number while querying with linq

Question: I am using a stream reader to read a text file and then using Linq for retrieving the information
String fileContent = prodFileStreamReader.ReadToEnd();

 var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
                    where !String.IsNullOrEmpty(con)
                    select new BaseSegment
                    {
                      dataID = con.Substring(0, con.IndexOf('#')),
                      dataElms = con.Split('#').ToArray(),
                      dataCon = con,
           lineNumber =
                    };

I would also like to get the line number. I tried using Index but I was not able to. How to query to get the index and assign it to lineNumber?
Comment: Could you post some example input files? It could provide much more efficient code if we had a better idea of what it looks like.
Answer: Try using the select that projects index into each item, as given in this msdn article: http://msdn.microsoft.com/en-us/library/bb534869.aspx
In your case something like this (not tested):
var mydata = fileContent.Split('$')
             .Select(x => x.Trim())
             .Where(con => !String.IsNullOrEmpty(con))
             .Select((con, index) => new
                             {
                                 dataID = con.Substring(0, con.IndexOf('#')),
                                 dataElms = con.Split('#').ToArray(),
                                 dataCon = con,
                                 lineNumber = index
                             });

Answer: For starters, I would not read the file in as a big string.  Use methods that could process it in small chunks.  Use File.ReadLines() for example to read through the file line by line.  It will be easier to get line numbers this way and much more efficient than reading it all at once only to split it up again.
const string filePath = ...;
var myData =
    from pair in File.ReadLines(filePath)
                     .Select((LineNumber, Line) => new { LineNumber, Line })
    where ...
    select new BaseSegment
    {
        ...
        Line = pair.Line,
        LineNumber = pair.LineNumber,
    };

p.s., You should stick to the usual C# naming conventions.  Public properties of your classes should use PascalCasing, not camelCasing and should not be abbreviated.
The code you use to process the content looks awkward.  It could probably be improved if I knew what the files looked like.  I'll leave that out until you could show us how it is.
Answer: How about this?
var animalList = from a in animals
                         select new { Animal = a, Index = animals.IndexOf(a) };

or in your case...
Index = fileContent.IndexOf(con)

Comment: that won't work if there are two equal lines in filecontent.split('$')
Comment: in that case, number the lines first with a select at the start such as .Select(...).Split(the rest of your query).
Answer: if this whole data is going in myData then you can use the index directly from the myData.
Answer: Try This:
String fileContent = prodFileStreamReader.ReadToEnd();

 var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
                    where !String.IsNullOrEmpty(con)
                    select new BaseSegment
                    {
                      dataID = con.Substring(0, con.IndexOf('#')),
                      dataElms = con.Split('#').ToArray(),
                      dataCon = con,
           lineNumber = Array.IndexOf(fileContent.Split('$').Select(x => x.Trim(),con)
                    };

Array.IndexOf(yourArrey,the string you looking for); -> will return the index in the arrey.

Answer: you can try something like this
long index = 0;
var xElementsAndNodes = from xmlElement in elementsColl
select new
{
  Index = index += 1,
  ....
}

line number while querying with linq


Django set ImageView of User Profile

Question: So i've been working on a project for a while, in which I use the Django default User Instance but with additional attributes, which are stored in a "Profile"-Model. So right now i have an assigned company, and an Profile-Image for the user in the Profile Model.
Now i have a detailview to edit the user's attributes (firstname, username, email, etc.). i used generic.DetailView for this View. But this is only working for the Attributes in the User-Model from Django. How can I also change Attributes in the Profile Model when editing the User?
This is my Edit-View:
class ProfileUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    fields = ['username', 'email', 'first_name', 'last_name']
    template_name = 'inventory/edit_forms/update_profile.html'
    success_url = '/profile'
    login_url = '/accounts/login'
    redirect_field_name = 'redirect_to'

    def form_valid(self, form):
        profile = Profile.objects.get(user=self.request.user)
        profile.img = self.request.POST.get('profile_img')
        profile.save()

    return super().form_valid(form)

    def get_object(self):
        return User.objects.get(pk = self.request.user.id)

This is my HTML:
<form class="edit_object" action="" method="post" enctype='multipart/form-data' class="form-group">

          Profile Image
          <input name="profile_img" type="file" accept="image/png, image/gif, image/jpeg">

        {% csrf_token %}
        {{form|crispy}}
        <input type="submit" value="Submit" class="btn action_btn">
</form>

As you see i already tried using a external Input field and setting the image like that. But after submitting, the img attribute in the Profile-Model is just set null and I don't know why.
What did I miss?
Comment: can you post your form
Comment: Which form? Everything happens in the class based view
Answer: if you want to go this way use request. FILES

Django set ImageView of User Profile


Not enough gold to buy items in LoD?

Question: I have the max amount of gold for my level--2.5 million in my trunk and 860,000 on me.  But the armor I wanted to buy from Larzuk was over 4 million.
If the max gold I can possibly have is about 3.4 million how can I buy armor that costs over 4 million?
Comment: I'm curious and want ask what item costs that much.
Comment: I'm not sure why you would want to BUY things in D2. The loot you find is way nicer than that bought at vendors.
Comment: Well, two things.  I haven't found that items dropped are as high in defense as the items I find at vendors (the armor defense was much higher than anything I've ever found), and I'm assuming that there must be a way to buy these items or they wouldn't be for sale.
Comment: Yeah, it's been a long time since I played diablo. Are you level 99? If so I guess your only option are those items below.
Comment: It was godly sacred armor.
Answer: There are two items that can reduce vendor prices:

Gheed's Fortune
Edge Runeword

Together they can reduce vendor prices by up to 30%
Comment: @James that is correct.  Physical damage reduction will reduce damage from physical attacks.  Elemental resistance will reduce damage.  But armor is purely for avoiding hits.
Comment: Thanks.  I assume there's no normal way to have enough gold to afford these items then.  Seems strange to sell them at prices that exceed the possible amount of gold one could have.
Comment: If this merchant happens to be in Act II, don't forget to kill Radamant.
Comment: @Ian Larzuk's in act 5, but good point getting the act 2 discount.
Comment: @JamesWinter yeah, seems kind of game breaking but they probably didn't expect you to try and buy 4 million gold armor. To be honest, don't put too much emphasis on defense as in the long run an extra 1000 or so armor won't make much of a difference - since defense only reduces the % chance of being hit, you're better off investing in damage reduction items or life leech if you have a melee character.
Comment: That's interesting--so better defense just decreases the % chance of being hit, but doesn't decrease the damage done when hit?

Not enough gold to buy items in LoD?


Find all integer solutions to $15x + 12y + 30z = 24$

Question: This problem is from Burton pg. 44. The hint given is this:

Put $y = 3s-5t$ and $z = -s + 2t$

First Question
Why does this hint work? How did it come to be? It doesn't seem to stem from the euclidean algorithm or from $\gcd (12, 30)$.
Second Question
Even so, how does one proceed? Using the given substitution doesn't appear to give integer solutions, at least according to what I have done (which is probably, most definitely not the right approach). I went from $3x + 2s - 8t = 8$ to try and substitute something for $x,s$ which led to $x = 1 +2f \: \:, \: y= -1 + 3f \: \:$ ($f$ is any integer). But this leads to $t$ having a fractional value.
Any help is greatly appreciated.
Comment: You can start by dividing both sides by $3$, giving $5x+4y+10z=8$.
Comment: @KennyLau of course I had already done that. Just didn't include it in my question.
Comment: The $t$ should cancel out after substitution and you will be left with $5x+2s=8$.
Comment: A way to solve the equation can be given as follows (although this is not what you wanted but you may get some idea as to why the substitution works). Observe that,  $$5(x+2z)=4(2-y)\implies y=2-5t \ ,\  x+2z=4t$$where $t\in\mathbb{Z}$. Consequently we have, $$(x,y,z)=(4t-2z,2-5t,z)$$ where $t,z\in\mathbb{Z}$.
Answer: The hint reduces the equation to
$$
5x+2s=8
$$
which can be solved using the Euclidean algorithm, or noticing that $x=0$ and $s=4$ is a particular solution. Then we get that $x=2u$ and $s=4-5u$ is the general solution.
There are other reductions. I think the following is just as simple and maybe a bit more intuitive.

Factoring $3$ out of the equation gives
$$
5x+4y+10z=8
$$
If we set $w=x+2z$, all we really need to solve is
$$
5w+4y=8
$$
One solution is $w=0$ and $y=2$, which means the general solution is
$$
w=4t\qquad\text{and}\qquad y=2-5t
$$
Therefore, we get the general solution to the original equation to be
$$
x=4t-2z\qquad\text{and}\qquad y=2-5t
$$
Answer: The hint looks arbitrary to me. That's not how I would attack this problem.
After $$ 5x + 4y + 10z = 8$$ I would take advantage of "$5$" and "$10$" like so: reducing modulo $5$, it must be true that $ 4y \equiv 8 \mod 5$, or $ y \equiv 2 \mod 5$. Write $y = 2 + 5k$, substitute in the original equation, divide by $5$, and that gives you $x$ in terms of $k$ and $z$. Then $k$ and $z$ are free parameters (they can be any integers), and you have $x$ and $y$ expressed in terms of these parameters (and $z$, of course, is itself).
Comment: How does this answer the questions?
Comment: @user170039 - Fair question.  It doesn't, other than the first sentence: the hint seems arbitrary to me. I meant the rest of my Answer to show what hint I would give. My hint would be: write $y = 2 + 5k$; first, show that $y$ MUST be of this form.
Answer: Let $ux+vy+wz=c$, with $u,v,w,c\in \mathbb{Z}$ a general such equation, to be solved in integers. Suppose that $uvw\not =0$ to simplify.
1) Put $v=dv_1$, $w=dw_1$, with $v_1$ and $w_1$ coprime.
2) Find $v_2,w_2\in \mathbb{Z}$ such that $w_2v_1-v_2w_1=1$ (they exists by Bezout).
3) Put $u_1y+w_1z=s$, $v_2y+w_2z=t$. Then we can solve this system, obtaining $y=a_1s+b_1t$, $z=a_2s+b_2t$, with $a_1,a_2,b_1,b_2\in \mathbb{Z}$. For all $s,t\in \mathbb{Z}$, we have $y,z\in \mathbb{Z}$.
4) Replace: of course, we get that $ux+ds=c$, and it is easy to finish (and to see if such solutions exists).


How to disable a button with a certain value using jquery

Question: How are the buttons disabled from a specific list of values, in my situation?
I tried to do it like this:

    var pls = [[45], [1]];
    for(var el in pls){
        $.each($('.seat'), function(){
            var attr_el = $(this).attr("value");
            if(attr_el == el){
                $(this).prop("disabled",true);
            };
        });
    };
.seat{
  background-color: green;
}

<button class="seat" value="1"> </button>
<button class="seat" value="45"> </button>
<button class="seat" value="100"> </button>

But only the 1 button is disabled, not the 45 button.
Comment: Typo?  `$each.(` looks like it should be `$.each(` instead.
Comment: `el` is an array, `attr_el` is a string. They can never be equal. Why is `pls` a 2-dimension array?
Comment: I can't imagine any reason why you couldn't transfer `[45, 1]` using JSON.
Comment: thanks for your comment, but it didn't help :)
Comment: Can you provide more information about the error?  Which specific line of code does it reference?  Can you replicate the error with a [mcve] as a [runnable code snippet](https://meta.stackoverflow.com/q/358992/328193)?
Comment: It looks like each element of `pls` is itself an array.  Does `if($(this).attr("value") == el[0]){` help?
Comment: @Егор: Regarding the update... (1) Please clean up the post, the runnable snippet is malformed.  (2) The updated code still has the same typo.  (3) When I correct that typo, I no longer get that error.  Please take some time to debug and confirm, and to specify exactly what you're asking about.
Comment: @David: yes, but disablid is only 1 item, but not all of the list
Comment: @Егор: *"yes, but"* - Then [your previous comment](https://stackoverflow.com/questions/77841230/how-to-disable-a-button-with-a-certain-value-using-jquery-in-django?noredirect=1#comment137229147_77841230) was a lie?  Please be clear about the specific problem you are observing and the specific question you are asking.  Your code had a typo.  That typo produced a syntax error.  After several tries, you have corrected that typo. Now the code no longer produces that syntax error. The question above is asking about that syntax error.  Which has already been answered. Please clarify in the question.
Comment: Thank you, David, and I'm sorry. I'm a new user and I'm just learning. I've read the guidelines for writing questions, but it's hard to ask a good question the first time.
Comment: The question already has close-votes from the original typo, but now is also a duplicate of: [Difference between ( for... in ) and ( for... of ) statements?](https://stackoverflow.com/questions/29285897/difference-between-for-in-and-for-of-statements)  You're just using the wrong loop iteration, referencing array indexes instead of array values.
Comment: @Barmar: `pls` is two-dimensional, because this is the only way I was able to transfer the data I needed using json. This was described in the question earlier, but the editor changed my question to make it more readable.
Comment: @Barmar: I could explain, but this is a separate topic for discussion :)
Answer: To solve the problem, I changed for...in on for...of, to take not indexes, but array values. Since we are working with an array inside an array, el is also an array with one element. So, we change el to el[0] to take the first (and only) argument.

    var pls = [[45], [1]];
    for(var el of pls){
        $.each($('.seat'), function(){
            var attr_el = $(this).attr("value");
            if(attr_el == el[0]){
                $(this).prop("disabled",true);
            };
        });
    };
.seat{
  background-color: green;
}

<button class="seat" value="1"> </button>
<button class="seat" value="45"> </button>
<button class="seat" value="100"> </button>
Comment: Is this the answer? If so, please add a comment explaining how you fixed the issue.  If not, please remove it and add the correct code snippet to the question instead (using the edit functionality)
Answer: No need to loop over the elements, you can use an attribute selector.

var pls = [
  [45],
  [1]
];
$.each(pls, (i, [el]) =>
  $(`.seat[value=${el}]`).prop('disabled', true)
);
.seat {
  background-color: green;
}

.seat:disabled {
  background-color: grey;
}

<button class="seat" value="1"> </button>
<button class="seat" value="45"> </button>
<button class="seat" value="100"> </button>

I used destructuring in the callback argument list to extract the first element of each nested array in pls.


Custom Hardware

Question: I am in the process of redesigning my EE seniro design project (Digital Car Instrument Cluster) and would like to port the system from a custom light weight ubuntu to a android based system.  I was wondering can we install android onto a small atom based motherboard and if so does anyone know how we can writer driver to communicate with our usb datalogging hardware.
Comment: I would say it would be possible, they have compiled android for x86 processors. beyond that, i cant help. this would probably be better asked on http://superuser.com/ - maybe check out http://www.androidx86.org/
Answer: Besides androidx86, you'll likely to need something like ioio, which is to get adopted to android 2.3 as the reference hardware interface for Microcontrollers.

Custom Hardware


Are there any blacksmiths or enchanters for hire?

Question: My current character in Skyrim has got essentially zero Smithing and Enchanting skill. It would still be great to be able to upgrade or enchant items, or even create some items, like dragon armour. In particular, I would really like to upgrade some magical daggers I use but I can't because I don't have the right perk. Non-enchanted daggers I can at least upgrade a little bit.
I haven't found anyone who can smith or enchant on demand, but are there any such characters in Skyrim anywhere? It's a big world and I could have missed them. I wouldn't mind paying handsomely for such items (e.g. it would make sense that I wouldn't be able to sell it for more than I paid for it).
If the answer is negative (boo) then are there any mods that provide this mechanic?
Note that I'm not sure if mods go against the 'no game recommendations' rule. If so, I (or you!) can edit my question to remove this.
Comment: I am on my fifth playthrough and haven't found a single NPC who will enchant or smith gear for you.  The closest is the guy in Winterhold College whom you have the dialog option to ask "Can you enchant something for me?".  However, he basically tells you to go suck an egg.
Answer: Actually there is something very similar to this in the form of certain followers. Some followers can TRAIN you in said skills, and then you can open their inventory (since they are your follower) and take you money back. Rinse, and repeat. I'm on my lunchbreak at this moment, and havent the time to look them up but I will include them in my answer as soon as I get off work.
You can find the followers yourself at the Wiki.
Comment: This is... _sort of_ useful, but not quite what I'm looking for. It's not that I can't be bothered to level the skills up, it's just that I'd rather have that experience and perks go elsewhere and use my ridiculous amounts of (mostly stolen) gold for something useful rather than hoarding it like a very small dragon.
Comment: Well if I train to improve skills then that'll cause me to level up,gain perks, etc, right? I know I can save the perks for later but I could spend that same time levelling up, say, light armour or archery
Comment: @alex I dont think it levels you up.
Answer: No, there are no items or characters that allow you to smith gear you do not have perks for. If you wish, you can add the relevant perks free of charge by looking up the perk code and adding it with the console like this:
help "daedric smithing" 4

This will output a list of all things in the game that have "daedric smithing" in the name, look for the 8-number ID (In this case, the ID is 000CB413), then
player.addperk <ID>

Comment: I wasn't looking for items - rather NPCs that can do my smithing for me. Still, it doesn't sound like that is available either. This may be my best bet (or just, you know, live in smithing ignorance...).
Comment: I chose this as it provides a direct (if negative) answer while also suggesting a workaround. @Ender's answer also provides a decent workaround, though his is more time-consuming to do.
Answer: While it's true you can't hire an npc to create an item for you(smithing) or improve an item for you(smithing or enchanting), there are merchant trainers. In vanilla Skyrim, there are several smiths you can pay for training and then sell them stuff to get your gold back. These include Gorza in Markarth(common trainer up to level 50), Balimund in Riften(expert up to level 75) and Eorlund in Whiterun(master up to level 90). The Dawnguard adds Galmar(master at Fort Dawnguard) and incidentally Sorine is a master archery trainer and merchant(same location). That isn't so relevant but it adds to getting free training with Faendal at the start of the game and with members of the circle once you are harbinger. If you have high alchemy skill and perks, it helps to sell potions and poisons to merchant trainers to get your money back.
For Enchanting, only Sergius Turrianus of the College(expert) and Hamal in the Markarth Temple of Dibella(master) are enchanting trainers in vanilla Skyrim, but neither one is a merchant(and Hamal requires a potentially dangerous quest be completed before becoming available). If you have the Dragonborn DLC, Neloth at Tel Mithryn on Solstheim is a master enchanting trainer and a merchant. On a side note, his apprentice Talvas is a master conjuration trainer and merchant who can also be your follower as well.
With patch 1.9, you can make any level 100 skill legendary, resetting the skill to 15 and refunding the perk points you spent in it. You can level the skill again for more xp to raise your character level, get more perks and more attribute increases. A skill can be made legendary as much as you want, removing the previous level cap of 81 and allowing you to get all perks in every tree if you want to. The easiest without exploits are either Alteration(telekinesis fast travel between Riften and Markarth) or Illusion(cast Harmony in a crowded place like the Riften market during the day. May help to be thane wherever you try this so guards don't get on your case). Both methods benefit from having a set of gear making spells free to cast(totally doable with 100 enchanting, relevant perks and grand soul gems). You can even freely cast 2 spell schools with one set of gear with the level 100 enchanting perk Extra Effect. Hope this helps.


Arrangement of musicians into distinct bands - combinatorics solution?

Question: Real life problem.
I have 8 different musical instruments and 14 players of each instrument. There will be 9 sessions where the players are placed into 14 bands (each band has 1 of each instrument). So if each instrumentalist was labeled 1-14 for their respective instrument, the first session could be band 1: all instrument 1s, band 2 all instrument 2s etc.
Is it possible for each band in each session to be unique? I.e. Trumpet 1 doesn't play with clarinet 1 more than once (and doesn't play with any other instrumental person from other instruments more than once). I am able to brute force this with 3 or 4 sessions but past that it gets difficult.
While I have a math degree and took some combinatorics classes, I am definitely not an expert. I think this might fall under Combinatorial Design but  I am not really sure.
Answer: Yes, you can set this up and solve as an integer program. If I'm understanding your requirements correctly, it could be something like the following. (Then this could be solved using a variety of optimization software. E.g., SCIP in python)
Sets:
$S$ Set of sessions
$B$ Set of bands in each session
$P$ Set of people
$I$ Set of instruments
Parameters:
$c_{pi} \in \{0,1\}$ if person $p$ plays instrument $i$, $0$ otherwise
Variables:
$X_{psb} \in \{0,1\}$ if person $p$ plays in band $b$ in session $s$
$Y_{pp'sb} \in \{0,1\}$ if person $p$ plays with person $p'$ in band $b$ in session $s$
Formulation:
min $0$
subject to:
$ \sum_{p \in P} c_{pi}X_{psb} = 1, \forall s \in S, b\in B, i \in I$
$ Y_{pp'sb} \geq X_{psb} + X_{p'sb} - 1, \forall p \in P, p' \in P \setminus \{p\}, s \in S, b\in B$
$ \sum_{s\in S}\sum_{b \in B} Y_{pp'sb} \leq 1, \forall p \in P, p' \in P \setminus \{p\},$
I believe you're looking for any feasible solution that satisfies your constraints - so the objective doesn't matter. The first constraint set requires there to be exactly 1 instrument of each type in each band. The second constraint set assigns an indicator variable if a person has been assigned to the same band as another person in the same session. The third constraint set only allows you to assign 2 people to the same band once.
Comment: Re-reading the original question - are you trying to make assignments or are you wondering if it is possible or not? If It's the former, an optimization approach will work for you. If the latter - you could use an optimization approach (if there's a feasible solution it means it's possible; infeasible means it's not), though there may be alternate ways to check that than setting up a model.
Comment: I am trying to actually make the assignments. At the end of the day, if you pick any player, say Trumpet 12, he/she shouldn't be matched with the same player from any other instrument more than once in all 9 sessions.
Comment: Great - I think an integer program such as above will work for you. If you have trouble implementing, let me know.
Comment: I've been thinking about this some more - if you adjusted the variable $Y_{pp'sb}$ to be $Y_{pp's}$ instead, the program would be substantially smaller. Constraint set 2 would stay the same, and for constraint set 3, you would remove the summation over $B$. Also I'm not sure how computational you are, but an easier(?) option than Python might be Open Solver (https://opensolver.org/) for Excel. It's an add-in that allows you to solve moderate size integer programs. Solver Studio - another Excel add-in (https://solverstudio.org/) can handle larger ones.
Comment: I am not familiar with any of the computational programs unfortunately. I downloaded scip today and played around with it but couldn't figure out how to do much. I do appreciate you help this far though.


How avoid the use of switch cases (with dll functions) c#

Question: I use a DLL to communicate with a bootloader through a Microchip and I use many functions of the dll.
Swicht(DLL Function)
case: Readbyte
    MC2211.readbyte(intptr DeviceHabdle, unit number Of Bytes, ref Data)
case : Writebyte
    MC2211.readbyte(intptr DeviceHabdle, unit number Of Bytes, ref Data)

But this kind of structure goes against the open close principle.
Comment: And what is your question?
Comment: Could you edit your question to address the concrete way in which you would like the open-close principle to be fulfilled by your code? In particular, I'd be interested to know who is expected or supposed to "modify" your code (presumably by adding more DLL functions) while it remains "closed" (i.e. presumably without recompiling your assembly). Do you somehow want to load the list of available functions in the DLL at runtime or anything like that?
Comment: By the way, your `Writebyte` case invokes something called `readbyte` - intentional or a typo?
Answer: Using Strategy Pattern
interface IMC2211Command
{
    void Run( object[] args );
}

class ReadByteCmd : IMC2211Command
{
    public void Run( object[] args )
    {
        // read bytes
    }
}

class WriteByteCmd : IMC2211Command
{
    public void Run( object[] args )
    {
        // write bytes
    }
}

How to use:
IMC2211Command cmd = new WriteByteCmd();
cmd.Run( args );

It will make all your command is adding codes rather than changing existing switch cases.


Finding $x$ values of $\cos 6x + 1 = \frac{3}{2} + \frac {1}{2} \cos 3x $

Question:
Solve $$\cos 6x + 1 = \frac{3}{2} + \frac {1}{2} \cos 3x $$ for $0^\circ<x<120^\circ$

I simplify it to
$$2 \cos 6x + 2 = 3 + \cos 3x $$
There is $\cos 6x $ and $\cos 3x$ how do I merge them together? To solve the equation from $0^\circ$ to $120^\circ$?
Comment: Use the double-angle identity
Comment: $x=0$ is a solution, but I think you want something more interesting.
Answer: Hint: Use the identity
$$\cos 2y=2\cos^{2}y-1$$
with $y=3x$.
Answer: Here's what I got...(EDIT: $3 \cos 3x$ is incorrect in the third line; the correct quantity is $\cos 3x$.).
$$\cos 6x + 1 = \frac {3}{2} + \frac {1}{2} \cos 3x$$
Multiplying by $2$ we get
$$2 \cos 6x + 2 = 3 + \cos 3x$$
Swapping constants and bringing over $\cos 3x$ we then get
$$2 \cos 6x - \cos 3x = 1$$
Using the double angle identity $\cos 6x = 2 \cos^2 3x - 1$ we get
$$4 \cos^2 3x - 2 -  \cos 3x = 1$$
Adding 2 to each side gives us
$$4 \cos^2 3x -  \cos 3x = 3$$
Now we can factor out $\cos 3x$ on the left to get
$$\cos 3x (4 \cos 3x - 1) = 3$$
We now have two equations.  Since $\cos 3x = 3$ has no solution, we concentrate on $4 \cos 3x - 1 = 3$; this yields
$$4 \cos 3x = 4$$ or $$\cos 3x = 1$$
Taking the inverse cosine of both sides we get
$$3x = 0 + 360\times k$$ (k in degrees)
and then dividing by 3 we get
$$x = 0 + 120 \times k$$
For the condition $x \in (0, 120)$ we arrive at the answer, $$\bbox [yellow] {x=120}$$.
CHECK: $\cos 6(120) + 1 \rightarrow 1 + 1 \rightarrow 2$ and $\frac {3}{2} + \frac {1}{2} \cos 360 \rightarrow \frac {3}{2} + \frac {1}{2} \rightarrow \frac {4}{2} \rightarrow 2 \checkmark$
Alternative answer (as suggested by Lab Bhatterchajee):
Instead of factoring out as above, substitute $u = \cos 3x$ and subtract $3$ from both sides gives us
$$4u^2 - u + 3 = 0$$
Using the quadratic equation $x = \frac {-b \pm \sqrt {b^2-4ac}}{2a}$ we have
$$u = \frac {-1 \pm \sqrt {1^2-4(4)(-3)}}{(2)(4)}$$, which leaves us with
$$u = \frac {1 \pm 7}{8}$$
Bringing back $u = \cos 3x$ we have two solutions:
$$\cos 3x = -\frac {3}{4}, 1$$
Since we are looking for values from $0$ to $120$, we discard the negative value and continue on from $\cos 3x = 1$ from before - yielding the same answer as above, avoiding an extraneous solution.
Comment: Why don't we  Use quadratic equation here?
Comment: Where did ur $3$ from $3 \cos x$ in the 3rd step come from
Comment: Lab - that works a treat and was much quicker!  I've added your suggestion to my edit.
user175089 - good catch - I've corrected it to $\cos 3x$.


Python - Simple for loop not working as expected (with requests module)

Question: I must be missing something here since the computer doesn't joke around but this simple for loop is seemingly not giving me the desired output. Below is the code which uses aztro's API to grab today's horoscope for each of 12 zodiac signs and put them all in a list.
import requests
import json

zodiacSigns = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces']

for zodiacSign in zodiacSigns:
    params = (('sign','{}'.format(zodiacSign)), ('day','today'))
    output = json.loads(requests.post('https://aztro.sameerkumar.website/', params=params).text)
    descriptions = []
    descriptions.append(output['description'])

print(descriptions)

This code outputs the horoscope for only Pisces, the last element in the list above:
["You need to take work more seriously today -- it may be that you've got an opportunity coming up that shouldn't be missed. It's easier than usual for you to make career moves, so go for it!"]

As a reference, a sample output of this aztro's API for a single zodiac sign is:
{
   "compatibility":" Virgo",
   "date_range":"Jan 20 - Feb 18",
   "current_date":"August 23, 2018",
   "description":"Today requires a willingness to go deeper than usual -- maybe to explore the nuances of your primary relationship, maybe to really get to know that one client or maybe just reading between the lines.",
   "lucky_time":" 10am",
   "lucky_number":" 13",
   "color":" Navy Blue",
   "mood":" Thoughtful"
}

The desired output would be a list of horoscopes for all 12 zodiac signs. I can't seem to catch the issue here, so I'd appreciate input from more experienced eyes. Gracias!
Comment: You define descriptions as an empty list in each iteration. Move that definition to before the loop.
Comment: In addition, you don't need `json.loads()` because requests response object has a `.json()` function.
Answer: The problem lies in the declaration of the descriptions variable, which at every iteration is initialized to be an empty list.
Just move it out from the loop, like so:
descriptions = []
for zodiacSign in zodiacSigns:
    params = (('sign','{}'.format(zodiacSign)), ('day','today'))
    output = json.loads(requests.post('https://aztro.sameerkumar.website/', params=params).text)
    descriptions.append(output['description'])

Answer: The statement descriptions = [] should be out of the for loop. If it is in the for loop, it will be initiated (erased, in this case) every iteration.
The code below should work:
import requests
import json

zodiacSigns = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces']

descriptions = []

for zodiacSign in zodiacSigns:
    params = (('sign','{}'.format(zodiacSign)), ('day','today'))
    output = json.loads(requests.post('https://aztro.sameerkumar.website/', params=params).text)
    descriptions.append(output['description'])

print(descriptions)


Is it possible to assign 1 domain to 2 different ip address (internet & intranet user)?

Question: Currently I have a domain (example : www.danra.com) and a server with 2 ip (10.x.x.x ->> private ip and 202.x.x.x ->> public ip)
And I want to differentiate DNS route according to where the users access my site (intranet or internet).
As example for intranet user, when users access www.danra.com, will be routed to ip 10.x.x.x, but when public users access it, will be routed to ip 202.x.x.x
Can I set my domain to those 2 ip on my server ?
Comment: Yes, in the intranet, you should setup an internal DNS that point to private IP. External use public DNS.
Answer: Yes. But it means you have to administrate a DNS server in your intranet.
Please refer to this : How do I setup DNS for intranet. Route your intranet request to point to private IP. This means any request to www.danra.com will not go outside your intranet, use your local DNS Server and route it to your private IP.
Meanwhile, request from external users should point to public ip, this is achievable by buying a domain and point your domain to your public IP.
Here is an example using Namecheap.
Comment: Thanks a lot, Rudy
yeah I try to call the network administrator in my office to set up DNS server in my intranet, so my expected route could be done


Ceiling Fan Replacement - Wiring Issue

Question: I am replacing a ceiling fan in one room and when I took the old one down I found 2 black wires tied together(one of which is hot), one white ground wire, one hot white wire, and one red wire, and a copper ground coming from the ceiling. I only have one switch in the room to operate the light. The fan was wired hot and turned on and off by the pull chain.
I know the red switch wire attaches to the blue wire in the new fan.
I know the two white ground wires connect
I know the green wire in the fan connects to the ground.
I cannot figure out what to do with the remaining three wires. As a side note - disconnecting the fan in here has also caused power going to the other sections of the room on this breaker loose power.
Comment: Please double check the number of wires you have. You're missing at least one bare copper wire. A picture of the box showing where the wires come out would be helpful.
Comment: I will try to get a picture. The ceiling has two black wires, two white wires, a  red wire, and a copper ground wire in the fan box. The new fan has a blue wire, a green wire, a white wire, and a black wire.
Comment: How was the old fixture wired?
Comment: unfortunately I'm not sure - my husband took it down and doesn't remember now.
Answer: Odd that you said you had a white wire that was hot. Both white wires should be neutral and have no voltage. Seems to me wires would go like this: connect all black wires together. That will run hot all the time to the fan as well as sending power downstream.   Next tie all white wires together. That will provide neutral to the fan as well as pass neutral downstream. Ideally there would be a bare copper wire coming from the hot side and another to continue downstream. The red to blue should switch the light, providing that blue is the correct one for the light.
Comment: Making assumptions about wiring can be quite dangerous, especially when you have such little information to base it on.
Comment: If she actually has a white wire that is hot (and he says he does), she CANNOT connect it to other white wires or she will trip the circuit breaker (or fuse). As @Tester101 says ...

Ceiling Fan Replacement - Wiring Issue


Is there some way that I can see performance in Ubuntu?

Question: I am a new Linux user. In Windows, I used to monitor and sometimes improve my performance by using a software called "Advanced Systemcare". Is there some kind of software like this for Ubuntu? or someway that I can monitor how the things are going?
Thank You!
Comment: BTW, Advanced SystemCare is arguably junk. MalwareBytes Anti-Malware flags it as a "potentially unwanted program" (PUP). I would recommend CCleaner instead for Windows.
Comment: I might add to @wjandrea comment that ***Advanced SystemCare*** is a free program: http://download.cnet.com/Advanced-SystemCare-Free/3000-2086_4-10407614.html and as such they *might* make their profits from the malware embedded in it.
Answer: The Windows architecture is built around a central database called "the Registry" which overtime as programs are added and deleted becomes insanely large and the system bogs down. As such every few years many users find deleting Windows and reinstalling it along with all currently used programs makes things seem 2 to 10 times faster.
Within Linux there is no Registry, and such performance penalties aren't suffered. Hence there is no need for a program like IObit Advanced Systemcare.
If your web browser slows down in Windows or in Linux (or Mac for that matter) because of too many extensions, Google and Firefox have methods of dealing with that differently.
The annoying malware pop-ups you find in Windows web browsers do not seem to occur (to me at least) with Linux web browsers. Free programs you download in Windows often come with embedded pop-up advertising malware that slows down your system. In Ubuntu almost everything is free and  designed to be downloaded via sudo apt-get install, instead of via the web browser.
Like any other system, if you have limited RAM, buying more RAM will speed up Linux. Also if you have an HDD (hard disk drive), spending $100+ on an SSD (solid state dive) will speed things up tremendously.

Your question body is primarily about speeding up the system however your question title is about monitoring system performance. To monitory the system I personally like to use conky but other people have their own preferences.
Here is what my Conky display looks like:

When the image first starts you see what operation looks like under low load. The CPU's have low percentage utilization ~6%. The CPU speed is low ~1300 Mhz.
After opening Google Chrome (with 10 tabs) CPU utilization spikes up across all 8 CPUs to ~40% and the CPU speed jumps to maximum of 3400 Mhz.
Below the CPU information the names of the 10 top CPU consuming programs (processes) appear on my Conky display. Below that are displayed the amount of RAM used (26%) and amount of disk space (really an SSD) used (73%). Below that (but cut off from this picture) it shows the amount of ISP gigabytes consumed for the month. This helps prevent over billing.
If you would like to learn more about Conky I recommend this site: Post your .conkyrc files w/ screenshots
If you are looking for off-the-shelf system performance monitoring tools in general here is one thread: What can replace system monitoring in the top Gnome Panel in Unity?
You will find other system monitoring tools recommended in Ask Ubuntu if you do a search.
Hope this helps.
Comment: I have installed conky, but, when I open it, makes my entire desktop blinks , I don't now if it is because the version tha I'm using or anyway, any sulution? But thank you anyway.
Comment: @BrunoNavarro Conky is a powerful tool and as such requires much experimentation (sometimes weeks of time) to get it right. When Ubuntu 16.04 came out I had problems and had to downgrade to Conky  version that comes with Ubuntu 14.04. Those instructions can be found here:  https://askubuntu.com/questions/831946/conky-problem-indicator/832256#832256 Others are using the new Conky without problems and can probably support you better than I on that version. In the meantime try the "simple" performance monitors on my second link. That will get you started in a few minutes.
Comment: @BrunoNavarro I just checked out the answers in the duplicate close vote. There are some really good solutions there for a beginner like yourself. After you gain experience in Linux you can install and learn Conky.
Answer: I designed and built many of the large NOCs in the Pacific Northwest so monitoring is a topic that is near and dear to my heart.
At a user level, you can open something like System Monitor which is part of the standard Ubuntu distribution.  It is very similar to the task manager in the Microsoft world.
I also always have two terminal sessions open.  One running
nice top

and one running
tail -f /var/log/syslog

You will have to restart the tail once a day when the log files get rolled.
There are a few other log files that you may find interesting depending on how paranoid you are about security.  But since your focus seems to be on performance, those three "monitors" should more than satisfy your needs.
You may also want to run Bleachbit now and then just to keep things cleaned up.  I run it right after a reboot.  Once as root (sudo) and once under my mortal user login.  Bleachbit is similar to Ccleaner in the Microsoft world.
I listed top and tailing syslog because that methodology will be available on pretty much any *NIX system you will ever use.  I've been running top and tailing syslog for at least 30 years.  It rarely takens me very long to notice when something goes awry.  Bleachbit, on the other hand, is free, easy to use, easy to install and is the tool of choice for many professional IT organizations.
Comment: BleachBit is *way overkill* on Linux, though, and should not be recommended because it can do more harm than good especially in the hands of new or less experienced users
Answer: My all-time favorite process and CPU load viewer is htop. Significantly better, more user friendly,  and more powerful than top. It can be installed via Synaptic or via apt-get. http://www.thegeekstuff.com/2011/09/linux-htop-examples/  Once you are used to htop, you'll never go back to top again.
Answer: The ubuntu command "top" is a dynamic real time view of the running tasks and system.  It can sort by CPU or memory
Comment: `top` isn't really a Ubuntu command, it's more of a Linux command. In any respect you could improve your answer with a screen shot and brief summary of keys that control the program.
Comment: @WinEunuuchs2Unix It's arguably not specifically a Linux command either ;)


What is this difference between these two 4 pole (3 phase) GFCI breakers?

Question: I'm living in France and encountered this 4 pole (3 phase) GFCI in my apartment:

My understanding is that this thing protects against a difference, between the neutral (return) and the hot (phase), that is greater than 300mA. I hear that 300mA is too high to protect a human so I wanted to swap this out for the French norm which is 30mA.
It looks like the brown wire entering into the 3rd top terminal is the phase wire coming into the house and the grey wires are just setting up two more parallel circuits. The blue wire, into the 4th top terminal is the neutral wire.
To minimize work I wanted to just swap everything in place so I bought this thing:

I hooked it up and everything works, but the TEST button does not have any effect! I'm assuming the new breaker is working and it is my understanding of the thing that is broken. Looking closer at the schematics, they are not identical. The old one seems to have the T connected to the N and L1 terminals, while the new one seems to have the T connected to the 3 and 6 terminals:

Could someone please help me understand the differences?
Is the new breaker inappropriate for my setup?
Comment: I am not sure why you would purchase a 3 phase GFCI when only a single phase is being protected. The L terminals are for line voltage , the T terminals are for the load normally. The original unit is looking for an imbalance between all 3 phases and neutral, the new one looks like it may be for phase imbalance or phase to neutral. I am not sure if this will work in single phase mode because the imbalance is being created from 3-5  and you have 1-3-5 jumped together if wired like the original.
Comment: @EdBeal The idea was to change as little as possible. I thought I could just swap things out without understanding too much about the setup. Is it true that only "a single phase is being protected" in the old setup though? I was under the impression that a load imbalance between any of the "hot" lines and the neutral line would trip the switch.
Comment: I see jumpers (or what I think are jumpers) on the old one and your comment that there was only 1 hot. All 3 phases would have to come in to the device for 3 phase to be protected. As I mentioned I don't think this model will work with single phase or 1 hot. I believe you would need 2 phases on terminals 3-5 coming in and 4-6 going out.
Comment: @EdBeal It would work - all 3 phase GFCI do also work with only 1 or 2 phases. It is just Kirchhoff's law of summing up the current. No problem if 1 or 2 phases are permanent on zero Ampere. That would also happen in a 3 phase GFCI with all devices on 1 or 2 phases switched off.
Comment: @xeeka it's not an issue of parallel paths but where the test gets its power from, if there is no differential to power the device or create an imbalance the test button won't work and that is the issue the op is asking for help with.  the test button doesn't work. Only a single phase and the others with jumpers I don't see from the simple print how it could work with a single phase.
Comment: "Is the new breaker inappropriate for my setup?" - The new breaker is appropriate except for the test function. The test could be done with a lamp >= 10Watt, where phase is connected to phase,  but Neutral is temporarily connected to Earth (instead Neutral). The GFCI must trip immediately.
Comment: @xeeka I've attached a 9Watt lamp to the 6 terminal and the ground wire. The GFCI tripped.
Comment: Then the incoming line(s) would be on the upper side of the GFCI (1,3,5,N), the downstream lines to the breakers would be 2,4,6,N. In this case, the test simulated the test functionality of the GFCI. It could be done also with a ceiling lamp with all plastic housing (for safety reasons), i.e. if only 2 lines are used by the lamp.
Comment: To get the test function, wires could be swapped: all wires of terminal no 5 would swap with all wires of the upper N terminal. And all wires of terminal 6 would swap with all wires of the lower N terminal. IMPORTANT: the label "N" must be shifted as well, and a permanent note has to be written on the GFCI: "Currently 1 phase. For 2 or 3 phases, N has to be shifted back to the right most terminals!". This is for the correct order of the  timing of the  GFCI contacts in case of more then 1 phase.
Comment: @xeeka You are saying that the device does NOT treat the N terminal any differently from the others? That would be convenient, so that I could just swap 5,6 with the N terminals!
Comment: Yes, if there is only 1 phase connected to the GFCI, it doesn't matter which terminals are used for N. But as soon as the GFCI is fed with 2 or 3 phases, N must be at the dedicated terminals labeled "N" for switching sequence reason.
Comment: For minimal switching time if only 1 phase is used, it would be optimal to use only the terminals 1,2,3,4,5,6, without N.
N is delayed if the GFCI is switching off in order to avoid the star's (which is N if 2 or 3 phases are used) voltage to get out of symmetry resulting in possible damages to devices. This would be the optimal solution for a 1 phase usage, but it involves clamping wires into 1 terminal which were separated before - not electrically separated, but the bridged GFCI served as a kind of wire terminal in that case here.
Comment: Another option is to not change the GFCI wiring (i.e. test button not working), but to have a double isolated 10 Watt- lamp (isolation symbol is 2 squares) with 3 pole plug where the 3rd pole = Earth is left free for normal use. For testing purpose, the N pole of the lamp can be temporarilly connected to the Earth pole of the plug. Phase stays unchanged. That way not only the GFCI can be tested, but the complete wiring up to the outlets, f.e. interrupted Earth between GFCI and outlet could be detected. This testing would be more comprehensive  -and can be done for each outlet.
Answer: I see what's going on here.
You have a 3-phase RCD, but  your supply is only single-phase.
Let's look closer at that picture.

The top is the line side.  The orange wire is the real incoming hot.  The grey jumpers take the hot wire over to the other 2 phases.
What this brightened picture shows clearly is that the load side of the breaker is wired as 3 phases.  The apartment wiring takes 3 conductors, one off each phase, to be distributed to various apartment loads.  So the apartment is "3-phase-ready" even if the service is not (yet) 3 phases.
This is a danger area.  Each phase could pull 40A before any breakers would trip. I doubt that gray jumper is rated for 80A.  I also doubt the orange wire is rated for 120A.  Maybe it is downline of other breakers.
Your new RCD won't trip because there's no voltage difference
And therefore no current flow.  All phase (LINE and LOAD) conductors, all 6 of them, are at the same voltage potential. As such, there is no current movement through the TEST circuit.
So the upshot is, this device's Test functionality will not work here.  If your house is grounded, you can use external GFCI testers.
30ma isn't that great for human protection anyway
It's certainly better than nothing at all, but 30ma can be lethal for humans, and will definitely stun.  That is the motivating factor behind 5 ma protection on US devices; stunned people drown or fall, so a stun is the same as a kill.  Generally Europe does RCD for parallel arc fault detection.
Comment: "This is a danger area." Normally it is no danger zone, because even old codes in Europe meant to have  - from the provider to the house circuits: main breaker/fuse --> counter --> GFCI(s) --> circuit breakers --> room outlets/apartment/heating/light circuits. In this case, there must be (most likely outside of the pictured panel) a circuit breaker or fuse with 40A per phase for that apartment.
Comment: "30ma isn't that great for human protection anyway". According IEC time-current GFCI areas, both 5mA and 30mA are in the same AC-2 area, if the shut off time is 300msec or less. In practise, a GFCI 30mA needs less then 80msec to disconnect. Do you have any statistics or sources that shows the real world differences of human protection in regions with 5mA vs. 30mA thresholds? Only few countries seem to have this low 5mA threshold, most countries have 30mA for non-wet rooms.
Comment: If @xeeka is right about switching the wires between the 5,6 terminals and the N terminals, then I could restore functionality of my test button. That would complete my understanding of this setup.
Comment: @Harper has described the setup accurately, although I'm not sure (and don't know how to test) if my apartment is receiving 3 phases or a single phase. Thanks for helping me understand the factors at play in this setup!
Comment: "This is a danger area". There is a 45A breaker at the entry of the house, so the maximum any "jumper" wire would see is 45A.  Not sure how much the wire can actually take.
Answer: Assuming there is no problem with the GFCI itself:
Most likely, the test circuit is connected to the same phase at both ends,
i.e. 4=6.
Depending on the size of the apartment and on the heating sytem (water, room), there could be only 2 different phases (or even only 1 phase) arriving at the GFCI - instead of 3.
The old test circuit produced an imbalance between a phase and Neutral, the new test circuit between two phases.
Since the old GFCI's test circuit used to work, most likely there is only 1 or 2 different phases.
Edit: The lower side (2, 4, 6, N) goes to the circuit breakers, the upper terminals are the feed-in.
Since many apartments and houses do have 3 phases - especially with electric water heaters -, the 4-pole GFCIs with 40A, 63A or more are much more common, available and sometimes even less expensive.
In that case here, a 4-pole GFCI could have been used in a system with only 1 or 2 phases, i.e. a 2 or 3 pole GFCI would have been enough.
Also some pictures of the rest of the panel/circuit breakers would help.
It could be tested via measuring the voltages between the lower poles 2-4, 2-6, 4-6 and - for redundancy - all poles against N, i.e. 2-N, 4-N, 6-N.
It is assumed that N is really N and that the yellow-green Earth is only connected to N upstream of the GFCI.
This could be tested by measuring the resistance between N and Earth downstream of the GFCI, if the GFCI is open.
For safety, power must be switched off for that last resistance measurement.
Safety procedures:

Switching off power/main switch.
Securing against accidental switching on (other persons, work in empty apartment continued at another day/by another person, small children etc.)
Testing, if all power is switched off at the working area.
Comment: Those grey wires are bridges. I think there are just 3 parallel circuits. I'm pretty sure there is just 1 phase here. I have a gas "on-demand" water heater and no serious electrical appliances in a small, very old, apartment. I think I know now that a 2 pole GFCI would have been sufficient, but there would have to be 3 wires attached to the same outgoing terminal.


Android disabled autofocus EditText in ScrollView layout

Question: in my Activity I have a scrollview layout with two EditText inside. As soon as I open the activity is focused the EditTextinstead I do not want this to happen automatically.
I found a solution in this forum but not working. I hope you can help me. thanks
<code> ScrollView view = (ScrollView)findViewById(R.id.scrollView);
view.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.requestFocusFromTouch();
        return false;
    }
});
</code>
Answer: Just add this attribute for your activity in the manifest file
    android:windowSoftInputMode="stateHidden"


django-auditlog not working for User model

Question: I am using django-auditlog for creating entries in LogEntry table. my actions for User Model are not getting logged in LogEntry table.
my User model -
class User(AbstractUser):
...
...
...

username = None

USERNAME_FIELD = 'id'
REQUIRED_FIELDS = []

objects = UserManager()

def __str__(self):
  return f"{self.email}"

...
...

auditlog.register(User)

*I have to use django-auditlog only so pls suggest accordigly
TIA
Comment: What changes to instances of your User model are you doing and how are you making them?
Comment: Instances like activating/deactivating user, updating first/last names etc.
Comment: In the admin? Have you configured the AUTH_USER_MODEL setting and registered your User model in the admin and de-registered the built-in User model?
Comment: not from the admin panel, but from api level, exactly where I need to change for registering and deregistering AUTH_USER_MODEL setting
Comment: https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#substituting-a-custom-user-model
Comment: I have registered  AUTH_USER_MODEL in core -> settings.py still no luck
Comment: Can you share your api views and serializers? Are they definitely using the correct model?
Comment: URL - /api/user/activate-deactivate
View -

class UserUpdate(RetrieveUpdateAPIView):
Comment: Can you add the code for the view to the question
Comment: I am using two different serializers with get_serializer method for partnerships and organziations , which has organziation model and partnership model used
Comment: Can you at least add the code that handles "activate-deactivate"? Does it use `User.objects.update()`?
Comment: it use User.objects.filter(id=1).update(
is_active = True/False
)
Comment: `.update()` does not trigger any signals and so is almost certainly not handled by the package, you most likely will have to log the change manually or update all the records using `save()` in a loop
Comment: I have tried to use save method by first User.objects.get(), and then updating values and then use save(), but still got no luck
Answer: I use django-auditlog version 2.1.1. In my case, I've solved it this way:
AUDITLOG_INCLUDE_TRACKING_MODELS = (
    {
        "model": "auth.User",
        "exclude_fields": ["last_login"],
    },
)

I hope that it was useful!
Answer: choose 1 models.py in any app and import user model
ex. from django.contrib.auth.models import User
then register the user to auditlog
auditlog.register(User)


background on item click listener android

Question: I have a Gridview where i have many images that I get from url. I have added all of them to an Arraylist and set the Arraylist to Gridview. I have used
 grid.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
                                           //my code here

                                     }

so, now when i click on GridView items i get a border around each grid item. can I change the color of border?
Answer: look at this example
res/drawable/border.xml
    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke android:width="2dp" android:color="@color/green"/>
    <solid android:color="@android:color/transparent"/>

res/drawable/grid_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/border" />
<item android:drawable="@android:color/transparent"/>
</selector>

now use in gridview is property  android:listSelector="@drawable/grid_item_selector"
in main.xml
        <GridView android:id="@+id/gridview"
                        android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                        android:numColumns="auto_fit"
                     android:columnWidth="90dp"
                        android:stretchMode="columnWidth"
                         android:gravity="center"
                    android:horizontalSpacing="-1px"
                        android:verticalSpacing="-1px"
                    android:drawSelectorOnTop="true"
                    android:listSelector="@drawable/grid_item_selector"/>

Answer: Yes you can. In the layout of the grid items you can set the background drawable as a Selector. http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList  You can set each state of the item (pressed, focused, default, etc.) to correspond to any color (or drawable) you want. It would be easiest for you to make the border as a custom drawable. Either a Shape or a 9-patch.
Comment: You can make your drawable look any way you want. With a border, without a border, solid color, transparent, gradient, bitmap, anything goes. Selectors basically swap the resource out with whatever you point the state to. And it's all done in XML.
Comment: Please mark my answer as correct if this solves your problem.


How to install Google input tools in Ubuntu 17.04

Question: How can I install Google input tools in Ubuntu 17.04?
Answer: You cannot install it for general use on Ubuntu, as it is only available as a general download for Windows.
If you use Chrome or Chromium for your browser, however, you can install the extension from the Chrome extensions store, to use within the browser.
There are links to install it from https://www.google.com/inputtools/try/


Trying to display text on image button

Question: I am trying to display text on button,but nothing display.
<code> LocationButton = [[UIButton alloc] init];

 UIImage * Location_buttonImages = [UIImage imageNamed:@"button~iphone.png"];

 [LocationButton setTitle:@"Loca" forState:UIControlStateNormal];
 [LocationButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

 [LocationButton setImage:Location_buttonImages forState:UIControlStateNormal];
 [LocationButton setImage:[UIImage imageNamed:
 @"button_select~iphone.png"]
 forState:UIControlStateSelected];

  LocationButton.frame =  CGRectMake(20,212,90,40);

 [LocationButton addTarget:self action:
 @selector(action:) forControlEvents:UIControlEventTouchUpInside];

  [self.view addSubview:LocationButton];
</code>
I can see the image but no text visible.Please help!
Answer: <code> [LocationButton setImage:Location_buttonImages forState:UIControlStateNormal];
 [LocationButton setImage:[UIImage imageNamed:@"button_select~iphone.png"]  forState:UIControlStateSelected];
</code>
You overlay image on Title, so that no title display. Change to setBackgroundImage:forState
<code> [LocationButton setBackgroundImage:Location_buttonImages forState:UIControlStateNormal];
 [LocationButton setBackgroundImage:[UIImage imageNamed:@"button_select~iphone.png" forState:UIControlStateSelected];
</code>

Trying to display text on image button


Jquery won't work til 2nd click

Question: I'm calling this code:
function LickEx(pickID){
    alert('yo');
    $(pickID).datepicker({
        format : "mm/dd/yyyy",
        autoclose : true
    });
}

With: onClick="LickExpDt('#example2');"
The 'alert' fires every time, but the '.datepicker' will only fire if I click on it once, click somewhere else, then click on it a 2nd time (along with the 'alert) .. then it acts like normal.
I tried wrapping the function in a  $(document).ready(function () { :
$(document).ready(function () {
    function LickEx(pickID){
        alert('yo');
        $(pickID).datepicker({
            format : "mm/dd/yyyy",
            autoclose : true
        });
    }
});

Nothing fires and I get a "Uncaught TypeError: LickEx is not a function"
I need to call LickEx this way so that I can pass the variable in as a parameter (it's the ID of the input box)
is there a way to pass a variable of the ID of input box being clicked on with this:
$(document).ready(function () {
    $([put_var_here]).datepicker({
        format : "mm/dd/yyyy",
        autoclose : true
    });
});

OR fix the original?
Comment: Possible duplicate of [Javascript action on click](http://stackoverflow.com/questions/35923682/javascript-action-on-click)
Answer: Why not just have a class on the element(s) for which you want to add the date picker functionality ?
 $('.datepicker').datepicker({

The reason it only works on the second click in your case is that you are attaching the datepicker, only when you click on that element. So it takes an additional click to see it.
Comment: Thanks, I tried it, using a class: ("class=datepicker") and $('.datepicker').datepicker({....and it wouldn't fire at all ... seeme like the datepicker script only works with id's
Comment: @Jen2020 Glad to have helped :)
Answer: The first click just binds the datepicker to the element - the second click actually activates it. That's why you don't see the calendar until that second click.
You will need to bind the element before the click.
Comment: Thing is, I'm creating a form where the user can click a button to add more of these input boxes to the page to fill out. So, I don't know how many boxes there will be, so how could I bind them? That's why I was approaching the problem the other way, trying to push the ID in as a parameter.
Comment: You can bind them as you add them to the page.
Answer: Add a # in front of ID name and . for class name.
$(document).ready(function() {
    $('#pickID').datepicker({
        format : "mm/dd/yyyy",
        autoclose : true
    });
});

Jquery won't work til 2nd click