How to use typeahead-on-select in Angular JS?

Question: I use typeahead-on-select from bootstrap Angular JS.
Now I have writtem HTML code:
<input type="text" ng-model="data.country[formData.country]" placeholder="Select country..." typeahead-on-select="onSelect($item, $model, $label)" typeahead="stuff as stuff.name for stuff in countries | filter:{name: $viewValue} | orderBy:stuff.name" aria-expanded="false" aria-owns="typeahead-16-5649">

When I enter symbol a on this input I get autocomplete unsorted result without countries are named from this symbol. What I do wrong?
Answer: When we use angular type ahead we need to use custom filter function which manipulates the list and return the suggestions based on the code written in custom filter.
typeahead="state as state.code +' - '+ state.name for state in Item|      filter:$viewValue:customFilterFunction"

Here customeFilterfunction is defined inside controller which returns the suggestion list in desired order.
$scope.customFilterFunction = function(state,value){

    return state;

}

we can write any logic and sort the suggestions as per our requirement.


Is this write to an array truly undefined behavior in C?

Question: This code writes a value through a pointer if one array is one past the end of another array.
#include <stdio.h>
#include <inttypes.h>

extern int first[], second[];

#define ADDR_AFTER(ptr) ((uintptr_t)((ptr) + 1))

int test(int *an_int) {
    *second = 1;
    if (ADDR_AFTER(first) == (uintptr_t)an_int) {
        // ubsan does not like this.
        *an_int = 2;
    }
    return *second;
}

int first[1] = {0}, second[1] = {0};

int main() {
    if (ADDR_AFTER(first) == (uintptr_t)second) {
        printf("test: %d\n", test(second));
        printf("x: %d y: %d\n", *first, *second);
    }
}

At no point do I directly compare two pointers to different objects (because I convert them to uintptr_t first). I create a pointer to one-past-the-end of an array (which is legal), but I never dereference that pointer. As far as I can tell this should either print nothing, or print:

test: 2
x: 0 y: 2

Which is printed on Clang when optimization is -O1 or lower. At -O2, however, it prints:

test: 1
x: 0 y: 2

With -O2 -fsanitize=undefined it prints the this to stdout:

test: 2
x: 0 y: 2

and the following to stderr:

runtime error: store to address 0x000000cd9efc with insufficient space for an object of type 'int'
0x000000cd9efc: note: pointer points here
  00 00 00 00 01 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00

with a reference to the assignment to an_int in test. Is this actually undefined behavior, or is this a bug in Clang?
Comment: Using the n4713 draft, the relevant part of the standard is section 8.5.10 paragraph (2.1): "If one pointer represents the address of a complete object, and another pointer represents the addressone past the last element of a different complete object,88the result of the comparison is unspecified."

but note that "unspecified" is not the same as "undefined".
Comment: This is a known compiler bug. There is an existing question on it; I will look for it. The compiler incorrectly "deduces" that when execution is inside the "then" clause of an `if (a == b)` that compares two pointers, then `a` and `b` must point to elements within the same "array" (using the definition of a "array" for the `==` operator, which treats a single object as an array of one element).
Comment: Strict aliasing doesn't apply here because `p` is a pointer to `int` that hasn't been marked `restrict`. It is therefore explicitly allowed to alias `y`.
Comment: Renaming the one variable I mentioned is indeed better but .. do you want to make it easy for people to answer it or do you want to obscure the issues? Do one better please. Give all variables proper names.
Comment: Not quite a dup but closely related: https://stackoverflow.com/questions/45966762/can-an-equality-comparison-of-unrelated-pointers-evaluate-to-true
Comment: Great job on simplifying the code. The code looks ok to me. There's no way `*an_int = 2;` is UB because `an_int` is just `second`.
Comment: fwiw, this shouldn't be `UB`; it is the normal exercising of pointer arithmetic.     You are only dealing with +1 pointers to array elements, and +1's have yet to be destroyed by standardization.  That said, the clown car is ready for another lap, so this could soon be UB.
Comment: @MichaelMorris: "If you lie to the compiler, it will get its revenge." — Henry Spencer. Not an outright lie, perhaps, just a little attempt at subterfuge. Nonetheless, the compiler is displeased with you.
Comment: I suspect this is violating the strict aliasing rule. The optimizer assumes this doesn't happen.
Comment: The fact that optimizing makes it turn ugly is a good hint. Optimizing should never change the behavior of a well behaved program.
Comment: @MichaelMorris Can you please rename your variables into something searchable so that talking about the code becomes easier? `p` ... not a good search item. Give them names ... proper ones!
Comment: Is that better?
Comment: your code is pretty convoluted. And you have different code for optimized and non-optimized which make it that much harder to follow. Right now I don't want to invest time to understand this code, but are you sure the difference you see in the optimized vs non-optimized code isn't cause because you have different code for optimized and non-optimized code via that preprocessor `#if #else`?
Comment: @bolov I've removed the check and can confirm that the issue is not caused by the `#if #else` I've also simplified the code.
Comment: @o11c Does that mean that it would be conformant for the comparison to succeed in `main` but fail in `test`?
Comment: @EricPostpischil Funny, I was converting to `uintptr_t` before the comparison specifically to avoid dealing with exactly that sort of bug.
Answer: There's nothing invalid about your code, the compiler is wrong.  If you remove the unnecessary ADDR_AFTER check in test(), the code runs as expected with no UBSan error.  If you run it with optimization enabled and without UBSan, you get the wrong output (test=1, should be 2).
Something about the ADDR_AFTER(first) == (uintptr_t)an_int code inside test() makes Clang do the wrong thing when compiling with -O2.
I tested with Apple clang version 11.0.3 (clang-1184.108.40.206) but it looks like Clang 13 and current trunk also have the bug: https://godbolt.org/z/s83ncTsbf - if you change the compiler to any version of GCC you'll see it can return 1 or 2 from main(), while Clang always returns 1 (mov eax, 1).
You should probably file a Clang bug for this.


Why do I have to wrap my Kotlin method references in closures?

Question: In kotlin, I'm trying to create a dispatch table:
class Foo {
    fun handleEvent(bytes:ByteArray) {
        // do something fun with the bytes
    }
}

class Bar {
    fun handleEvent(bytes:ByteArray) {
        // do something fun with the bytes
    }
}

foo = Foo()
bar = Bar()

val eventHandlers:HashMap<RemoteEvent, (bytes:ByteArray)->Unit> = hashMapOf(
    0x01 to foo.handleEvent,
    0x02 to bar.handleEvent)

Kotlin doesn't seem to like this, it complains in multiple ways, but the relevant one seems to be be function invocation expected.
I can fix this by wrapping those in closures:
val eventHandlers:HashMap<RemoteEvent, (bytes:ByteArray)->Unit> = hashMapOf(
    0x01 to { bytes -> foo.handleEvent(bytes) },
    0x02 to { bytes -> bar.handleEvent(bytes) })

Is there no other way? Why do I have to the method signatures, which are correct, in closures which are the same? Are closures and methods not on the same footing in Kotlin?
Answer: In Kotlin, function references are created with the :: operator (not .).
Your intended use case can easily be achieved using this:
val eventHandlers: HashMap<RemoteEvent, (bytes: ByteArray) -> Unit> = hashMapOf(
        0x01 to foo::handleEvent,
        0x02 to bar::handleEvent)
                 // ^

Function references, Kotlin docs
foo.handleEvent is interpreted as accessing the property called handleEvent (which doesn't exist.)
foo::handleEvent is a KFunction instance representing the function called handleEvent, and since this matches the lambda signature (ByteArray) -> Unit it works as expected.
Notice that this is different from e.g. C# or C++, where due to language restrictions, methods and properties/fields cannot share the same name. In these languages . is fine for method groups/function pointers because it is impossible that foo.bar would be ambiguous.
Answer: Without closures expression is evaluated (invoked) in line.
Closures generate an anonymous object with defined method (within closures) that can be invoked when needed.
Only exception is when function consuming the lambda is declared as inline in which case entire function block is injected into calling place, including the lambda (to prevent generating object).


Python dendrogram there must be a k such that (k \choose 2)=n)

Question: I've trying to make a dendrogram in Python that takes the median values of some data then allows me to calculate the Euclidean distance between the median values.
Some of my data end up as negative values so I have to get the absolute value & offset all of the medians.
It seems to work fine if I only have 3 values to compare but for some reason if I have 4, or 5 values it gives me an error of "there must be a k such that (k \choose 2)=n)" but if I have 6 values it gives me a dendrogram of the last 4 values only.
I'm using Python 3.7.1, does any one know if there is some kind of bug? Cause I can't understand my code works for 3 values, doesn't work for 4 or 5 values, & gives me dendrogram of the last 4 values if I have 6 values.
<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as shc

#Calculate the median values of each group & make an array
a=10
b=-2
c=5
d=2.1
data = np.array([a,b,c,d])

#Find the lowest value because you can't make a dendrogram with a negative number
low = np.min(data)

#Offset data by the absolute of the lowest value +1, cause a 0 value won't work on a dendrogram
offset = abs(low) + 1
offset_array = []

# v = value, add offset to all values & save as an array
for v in data:
    offset_array.append(v+offset)

#Make an array of the offset values to calculate distances
cluster = np.array(offset_array)

# Labels for each value
#headings = ['a', 'b', 'c', 'd']

df = np.array(cluster)

#Size of figure (x, y)
plt.figure(figsize=(5, 5))
ax = plt.subplot()
#Change x axis range as required
dt = 0.01
ax.semilogx(dt, np.exp(dt))
plt.title('Gram positive distance')
plt.xlabel('Euclidean distance')

dend = shc.dendrogram(shc.linkage(df, metric='euclidean'),
                      orientation='left', leaf_font_size=8, labels=headings)
</code>
Answer: I think the problem was with the linkage function. For the linkage function: "a collection of m observation vectors in n dimensions may be passed as an m by n array."
So I made a new test variable by reshaping your df array:

test = df.reshape(len(df),1)

And then passed this new variable into your dendrogram function:

dend = shc.dendrogram(shc.linkage(test, metric='euclidean'),
                        orientation='left', leaf_font_size=8, labels=headings)


I'm hearing about load sheds aka EVEMS, and the devices differ. What's that about?

Question: There seem to be devices to let you charge an EV on houses that wouldn't otherwise have the service capacity (Electric Vehicle Energy Management Systems).  Some of them slow down EV charging, but it seems like others do a hard power cut to the EV, and that doesn't seem right.
But on the other hand, would the "hard power cut" option be a way to support simpler appliances that are not EVs?
Comment: With regard to chosing an EVEMS you might want to check out the patent infringment issues that have been coming up with regards to BlackBox EVEMS new patent that was issued in Jan 2024 with priority back to 2020. It looks like a lot of the devices discusssed in this chain will be infringing on that patent and may either disappear or have to licence the patented technology from them. Something to think about before you make a purchase as no one wants to buy a device from a company that disappears in 6 months.
Comment: @Tan Can you link?  FYI "BlackBox" is one of the dumb load shed devices.  It does not talk to the car. I could see where some onboard smarts might benefit it, but such intelligence is irrelevant to the *proper, dynamically-adjusting, talking-to-the-car EVEMS* which is the bulk of the discussion here. That's safe from patent issues because it was invented by SAE in [at least the J1772-2001 standard](https://www.fveaa.org/forums/index.php?topic=857.0), with the capacity signal designed to adjust on the fly (for dynamic EVEMS!) and the rest is "obvious to any practitioner in the field".
Answer: Yes, there is an exciting new collection of products designed to help people mitigate the need for a service upgrade and support a collection of loads their house otherwise could not.  And they're not just for EVs, though EVs are making them popular.   Some of them are pretty lousy for EVs, but great for simple appliances like hot tub, water heater, dryer and many other interruptible loads.  And now, we have access to that toolkit!
But let's discuss it by way of EVs and we'll start with a look at the masterful design of EV charging, and why blunt methods are not necessary.  If you really want a hot tub, skip to the end :)
The EV's ingenious secret
SAE (Society of Automotive Engineers) is an association of automakers, not electricians, and this is their fourth major attempt at an EV charging standard.  As such - hear me on this - SAE is in this to sell cars, not service upgrades.  They are well aware a service upgrade is a deal killer for auto sales, so it was a hot agenda item to make it easy to avoid them.
That "charger thing" is not a charger at all. It's an EVSE and it has 3 jobs: a) GFCI b) remote control switch c) Tell the car how much current can be safely taken right now. And that's it!
The car is simply hard connected to 120/240V AC, and onboard the car is a massive water-cooled battery charger about the size of a suitcase. The car's onboard real charger obeys the current signal from the EVSE.
That's new. This is not your father's battery charger! So let that one sink in.
Maybe watch that video I linked.
That signal is a 1000 Hz square wave on the CP signal pin. The duty cycle (in percent) of the square wave indicates allowed amps; generally 0.6A per percent, e.g. 53% is 32A.  This is a simple signal that could be made "by a middle schooler with an Arduino".
But the design was fully approved by UL and CSA; they were "in the loop" and expected to be certifying smart EVSE's that use this signal.
On simpler wall-unit EVSEs, this amp signal is set via DIP switches (or sometimes a special WiFi network).  On portable "travel unit" EVSEs, the square wave is generated by a microchip built into the dongle plug - a 20A plug signals 16A (20A x 80%), a 30A plug signals 24A, you get the idea.
The car responds in real time to this signal.  And as you might guess, you can do some pretty slick things with it.   For instance, several EVSEs bridged together could coordinate so they don't sum to more than X amps, but if 1 car is alone, it gets the full amount.  Now we get into the various EVEMS systems.
The house has a secret, too
The secret is that even though you have a 60A, 100A or 200A service, that's there for unusual peaks.  The vast majority of the time, your house uses next to nothing. EPA's data says the average house draws 29 kWH/day or 1200 watts or 5 amps.  So if our peaks are over 100 amps, our valleys must be much lower than 5 amps for that to average out to 5 amps.  And so it is - particularly all night.  Your house has great gobs of extra capacity - the key is knowing WHEN.
Technology Connections covers this "when" problem nicely at 7:24 in their "home electrification part 1" video.
An actual EV Energy Management System
Mind you, this was all coordinated in advance among Tesla, SAE, and the standards organizations (UL, CSA, etc.)
The simplicity of the square-wave EVSE protocol makes it really easy to design energy management for EVs.  Again, "a determined middle-schooler" could get an Arduino, and attach Current Transformer sensors to the AC mains wires (commonly seen on home energy montors such as the Sense or Curb)... and the CT clamps tell you the load the house is drawing from the grid right now.  You know the service size, 100A, and the panel is rated for continuous 80% of that, so 80A.
So now you simply do a couple subtracts and set the square wave signal accordingly, and that's it. The car itself does the 'heavy lifting'. For instance if the house (other than EV) is drawing 63A right now, and has "100A service" 80A max, compute 80-63 = 17 amps. Send the "17A" square wave to the car and it immediately adjusts charge to draw 17 amps.
See how easy this is?  Like I say, this is designed to be Code legal in North America - so if the equipment is UL/CSA/ETL listed per NEC 110.2, and installed according to instructions per NEC 110.3(B), the inspector and insurer cannot object.
Readily available COTS kit right now, just off the top of my head, are the Wallbox Pulsar Plus with a particular CT monitoring unit they use... and in Europe the Myenergi Zappi with proprietary wireless CT transformer.  All this will be hard-wired "wall unit" types; having it "plug in" would be problematic. Someday they may have a way plug-in appliances can do energy management via power-line signaling; give that at least a decade.
Emporia, maker of an EVSE and a home power monitor, never safety-rated those products to be used in this safety role, but were able to retrofit the ability with a firmware update - so they say.
Or a "bang-bang" system that interrupts the signal
A simpler, dumber system could simply have a CT on the service wires as above, and when the EV load would create an overload, simply signal the EVSE to stop altogether. The EVSE then removes the square wave signal from the CP pin, and the EV stops charging.
Several EVSE's have ports which allows this, and the ClipperCreek family comes to mind, as they have ports nominally for Power Sharing but handy for this application as well.
Or it could be hacked into an EVSE not made for it, by simply adding a relay which interrupts the CP wire on the charging cord. The moment the EV sees the CP signal disappear, it will stop charging.
The EVSE will notice this change, and will be able to use its smart or networked features to let you know "oh hey, charging stopped".
The bluntest (and costliest) instrument: a Load Shed
Ridiculous for EVs, but great for hot tubs.
In this case, we're doing the above simple "bang-bang" logic, but instead of talking to the EVSE, use a rather large mechanical contactor to go "CLACK" and do a hard power cut to the EVSE.  Compared to the above solutions, this is brutish and rather unnecessary.   Since it's not doing an orderly shutdown of EV charging, I have no confidence in the long-term effect on the EV's onboard charger.  I'm not a fan, though.
These dumb "Load Shed" devices are costly, because they are handling massive currents, with large terminals, large contactor and large wiring in/out of them.   They are also interrupting a large inductive load, so it'll be hard on the contactor contacts and require an extra burly unit.  It's also going to go "CLACK!" a lot, which may be annoying.
I'm very sorry that the manufuacters of these dumb Load Shed devices have taken to marketing them as EV Energy Management Systems", when this is misleading compared to the actual EVEMS kit I mentioned above.
It's useful to know about their existence, though, in case you ever get a hot tub or other storage load like a water heater. I once proposed these to be used between a tankless water heater and heat pump "emergency heat" resistor strips - use of water would knock out the heat strips.
But for EVs, they are stupid.  They are especially stupid at $1200.   That doesn't even include an EVSE and is almost double the cost of the Wallbox Pulsar Plus with recommended CT sensor module, the top shelf solution that gives you the best of all worlds.
The secretest of secrets: Slow down.
For understandable reasons, most novice EVers are mis-educated on a notion that level 2 charging must be 40-50 amps.  This is balderdash; it's 6-7 times the speed of plain old level 1 charging, and that's bonkers overkill for daily commuting.  It's like that, because cars are supplied with a "Travel unit EVSE" intended to be kept in the trunk and used "on the road" e.g. at RV parks - and in long distance travel, yeah, you need a total fill-up overnight.
The rest of the time, you just don't need that much.
It's perfectly viable to do 240V level 2 charging on a

15A circuit (over 2x Level 1; 75-130 miles a night)
20A circuit (over 3x Level 1; 100-160 miles) or
30A circuit (over 4x Level 1; 150-250 miles).

And often, the house which cannot support a 50A circuit in its Load Calculation can support a 15-20A circuit, and that's all you need if you're almost anybody.
For that "But Sometimes" moment, there's always DC fast charging.
You can use a wall unit set to a lower speed, or an alternate dongle for the travel unit to get a more achievable Level 2 speed.
By the way, the "Over 2x" etc. is because some power is needed simply for the overhead of charging, e.g. battery pre-heat, or water cooling.  That comes right off the top, so e.g. if it's 200 watts, that's 15% of Level 1 charging but only 5% of 20A/240V charging.
Comment: This is one of the best concise explanations I think I've ever seen for all of this. Wish I could upvote it more than once.
Comment: Completely agree. There's no need I can discern for anything more than a 13A "granny charger" connection (I'm in the UK). I only use higher rate AC or super-fast DC chargers when I'm on long journeys on the road and need to top-up, for "destination" charging (e.g. at a hotel), or on the extremely rare occasion I did many miles one day and need to leave agan the next morning. My average trip is less than 30 miles a day.
Comment: I missed this when asked in July. I'm bookmarking to add a [related] comment to darn near every EV charging question that comes up from now on. Added in the definition of SAE for completeness. (That's about the level of detail I feel qualified to add to a Harper answer).
Comment: I've been using the trunkable EVSE that came with my 2012 Volt, nightly, for nearly a decade now.  Perfectly adequate; pulls 12A from a 20A wall outlet in the garage.  I have an equivalent unit at work (~30 miles away) and so I can do virtually all of my commuting on electric.  I've used faster chargers when they're available for free but only for the convenience.
Comment: you know... i'm not sure what I just read here.  how is it *a masterful design of EV charging* and how is it different than selecting 10A, 5A, or 2A on my car battery charger? and then you mention hot tub skip to the end but you make no mention of what context of hot tub... outdoor?


How can I conditionally change the values in a numpy array taking into account nans?

Question: My array is a 2D matrix and it has numpy.nan values besides negative and positive values:
>>> array
array([[        nan,         nan,         nan, ..., -0.04891211,
                nan,         nan],
       [        nan,         nan,         nan, ...,         nan,
                nan,         nan],
       [        nan,         nan,         nan, ...,         nan,
                nan,         nan],
       ...,
       [-0.02510989, -0.02520096, -0.02669156, ...,         nan,
                nan,         nan],
       [-0.02725595, -0.02715945, -0.0286231 , ...,         nan,
                nan,         nan],
       [        nan,         nan,         nan, ...,         nan,
                nan,         nan]], dtype=float32)

(There are positive numbers in the array, they just don't show in the preview.)
And I want to replace all the positive numbers with a number and all the negative numbers with another number.
How can I perform that using python/numpy?
(For the record, the matrix is a result of geoimage, which I want to perform a classification)
Answer: The fact that you have np.nan in your array should not matter. Just use fancy indexing:
x[x>0] = new_value_for_pos
x[x<0] = new_value_for_neg

If you want to replace your np.nans:
x[np.isnan(x)] = something_not_nan

More info on fancy indexing a tutorial and the NumPy documentation.
Comment: It would be better if there were a single transformation, because your approach doesn't work if e.g. `new_value_for_pos < 0`.
Comment: @oulenz I posted [an answer about that](/a/74175287/4518341)
Answer: Try:
a[a>0] = 1
a[a<0] = -1

Answer: to add or subtract to current value then (np.nan not affected)
import numpy as np

a = np.arange(-10, 10).reshape((4, 5))

print("after -")
print(a)

a[a<0] = a[a<0] - 2
a[a>0] = a[a>0] + 2

print(a)

output
[[-10  -9  -8  -7  -6]
 [ -5  -4  -3  -2  -1]
 [  0   1   2   3   4]
 [  5   6   7   8   9]]

after -

[[-12 -11 -10  -9  -8]
 [ -7  -6  -5  -4  -3]
 [  0   3   4   5   6]
 [  7   8   9  10  11]]

Answer: Pierre's answer doesn't work if new_value_for_pos is negative. In that case, you could use np.where() in a chain:
# Example values
x = np.array([np.nan, -0.2, 0.3])
new_value_for_pos = -1
new_value_for_neg = 2

x[:] = np.where(x>0, new_value_for_pos, np.where(x<0, new_value_for_neg, x))

Result:
array([nan,  2., -1.])

Comment: P.S. I have the feeling there's an easier way to do this, but I'm not sure what
Comment: Another option would be to save `lt = x<0` first then do `x[lt] = new_value_for_neg`, but then you're left with another array. Hmm... Maybe packaging it in a function could be cleaner, so the other array gets cleaned up automatically.


Jagged 2D Array

Question: I'm trying to create an array with the following structure
D
C C
B B B
A A A A

Which will be N x N but split diagonally. Initially, all I know is the bottom row essentially just:
string[,] table = new string[n,];

How can I build on this structure so that when I get to the next row I can declare how many elements it has? Would it be something along the lines of:
for(int i = 0; i <= n; i++) {
    table[i] = new string[--n]
}

Comment: That looks about right to me, though I don't know about the predecrement. What's your question? Have you compiled it? We generally won't act as compilers for you.
Answer: The [,] syntax creates multidimensional arrays, not jagged arrays. For the latter, you would need to do this:
int n = 4;
string[][] table = new string[n][];
for (int i = 0; i < n; i++)
    table[i] = new string[n-i];

Btw. you really don't want to decrement n while looping in a loop with the condition i < n (or i <= n).

Jagged 2D Array


How to reload files tree in CodeLite?

Question: Is it possible to reload or update folders in the CodeLite environment?
I mean, add newly added files to the project and remove files or folders that doesn't exist anymore.
Answer: Right click in the project folder (blue one). click, in the context menu click "reconcile project". The wizard will take care of the rest.

How to reload files tree in CodeLite?


Induction proof concerning Pell numbers

Question: Problem: The Pell numbers $p_n$ are defined by the recurrence relation \begin{align*} p_{n+1} = 2p_n + p_{n-1} \end{align*} for $n \geq 1$, together with $p_0 = 0$ and $p_1 = 1$.
Prove with mathematical induction that \begin{align*} p_{n+1} p_{n-1} - p_n^2 = (-1)^n \end{align*} for every $n \in \mathbb{N} \setminus \left\{0\right\}$.
Proof: Initial step: for $n = 1$ we have $p_2 p_0 - p_1^2 = (-1)$ which is true given the initial conditions.
Inductive step: Suppose the above expression is true for $n > 1$. Then we have to show that it is also true for $n + 1$. So we have \begin{align*} p_{n+1} p_{n-1} - p_n^2 = (-1)^n. \end{align*} I now plugged in the expression for $p_{n+1}$ given above, and thus got: \begin{align*} (2p_n + p_{n-1}) p_{n-1} - p_n^2 = (-1)^n, \end{align*} or \begin{align*} 2p_n p_{n-1} + p_{n-1}^2 - p_n^2 = (-1)^n. \end{align*}
I'm not sure if I'm doing this right, and I don't know how to proceed. Any help would be appreciated.
Answer: Look at what you want to show: you want to show that $p_{n+2}p_n-p_{n+1}^2=(-1)^{n+1}$. You know that $p_{n+2}=2p_{n+1}+p_n$, so this is equivalent to
$$(-1)^{n+1}=(2p_{n+1}+p_n)p_n-p_{n+1}^2=p_n^2+2p_np_{n+1}-p_{n+1}^2\;.\tag{1}$$
Your induction hypothesis is that $p_{n+1}p_{n-1}-p_n^2=(-1)^n$; that has a $p_{n-1}$ that isn't present in $(1)$, so perhaps we should manipulate the target $(1)$ a bit more to get a $p_{n-1}$. We might apply $p_{n+1}=2p_n+p_{n-1}$ to one of the factors of $p_{n+1}$ in $p_{n+1}^2$ to get
$$\begin{align*}
p_n^2+2p_{n+1}-p_{n+1}^2&=p_n^2+2p_{n+1}-p_{n+1}(2p_n+p_{n-1})\\
&=p_n^2+2p_np_{n+1}-2p_np_{n+1}-p_{n-1}p_{n+1}\\
&=p_n^2-p_{n-1}p_{n+1}\;.
\end{align*}$$
Can you finish it from there?
Comment: Thanks for your help, but I'm not sure if I can finish. I don't really know towards where I have to work. How did you get to the left-hand side of that equation, I mean: $p_n^2 - 2p_{n+1} - p_{n+1}^2$ ? Because that's not the same as the equation in (1).
Comment: @Kamil: Do the calculation that led to $(1)$: $p_{n+2}p_n-p_{n+1}^2$ is equal to $p_n^2+2p_np_{n+1}-p_{n+1}^2$. You want to show that $p_{n+2}p_n-p_{n+1}^2=(-1)^{n+1}$, so you're done if you can show that $p_n^2+2p_np_{n+1}-p_{n+1}^2=(-1)^{n+1}$. Now just remember that by your induction hypothesis you have $p_{n-1}p_{n+1}-p_n^2=(-1)^2$, and notice that $p_n^2-p_{n-1}p_{n+1}=-(p_{n-1}p_{n+1}-p_n^2)$.
Comment: Found it this morning. A night sleep can do wonders, thanks for help =-)
Comment: @Kamil: It can indeed; you're welcome.
Answer: You have shown that it is true for $n=1$. The next step is not to suppose it is true for $n>1$, but for $n=k$. Then you must show that it is true for $n=k+1$.
Comment: ok, thanks for the heads up.

Induction proof concerning Pell numbers


Getting Directory Not Found When Not Looking For That Directory

Question: I'm trying to display random image from an array that looks like this:
[
    {
        "name": "weedle",
        "image": "https://c0.klipartz.com/pngpicture/478/959/sticker-png-pokemon-red-and-blue-pokemon-x-and-y-weedle-beedrill-others-tail-pokemon-evolution-pokemon-red-and-blue-pokemon-x-and-y.png"
    },
    {
        "name": "caterpie",
        "image": "https://img.favpng.com/2/19/21/pok-mon-diamond-and-pearl-pok-mon-sun-and-moon-pok-mon-tcg-online-caterpie-png-favpng-znPm71z43VHMdHAMhCqitLD5w_t.jpg"
    }
]

This is the line that should store one of them randomly. I'm not even sure if what I'm trying to do is possible:
const pokemon = require('./pokemon.json');
const pokemonImage = new Discord.MessageAttachment(pokemon[0].image[Math.floor(Math.random() * pokemon.length)]);

When attempting this and trying to have the message sent, I got this error:
(node:8880) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\h'

I'm not sure why it's trying to search for the directory "h" when I'm not searching for it in the first place.
If I remove "image" in "pokemon[0].image" I get this error:
(node:1520) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'path' of undefined
    at findName (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\structures\APIMessage.js:290:17)
    at Function.resolveFile (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\structures\APIMessage.js:306:31)
    at C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\structures\APIMessage.js:241:72
    at Array.map (<anonymous>)
    at APIMessage.resolveFiles (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\structures\APIMessage.js:241:46)
    at TextChannel.send (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:172:46)
    at Client.<anonymous> (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\index.js:33:50)
    at Client.emit (events.js:315:20)
    at MessageCreateAction.handle (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\xaguy\Desktop\PokeCord (My Version)\DiscordBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)

Comment: Also one of my friends that is helping me maintain my other bot is getting the second error when attempting to display an image. When I did it, it worked fine, when he used the same code, he got "path undefined". I'm assuming the issue has to do with that mainly. To add, I sent him all the files for the bot. I also copied and pasted the files in a new folder to start up as a new bot. I've done that before with no issues up until now.
Answer: Let's dig down into what is going on in here:
const pokemonImage = new Discord.MessageAttachment(pokemon[0].image[Math.floor(Math.random() * pokemon.length)]);

You start with this array in pokemon:
[
    {
        "name": "weedle",
        "image": "https://c0.klipartz.com/pngpicture/478/959/sticker-png-pokemon-red-and-blue-pokemon-x-and-y-weedle-beedrill-others-tail-pokemon-evolution-pokemon-red-and-blue-pokemon-x-and-y.png"
    },
    {
        "name": "caterpie",
        "image": "https://img.favpng.com/2/19/21/pok-mon-diamond-and-pearl-pok-mon-sun-and-moon-pok-mon-tcg-online-caterpie-png-favpng-znPm71z43VHMdHAMhCqitLD5w_t.jpg"
    }
]

You get the first element via pokemon[0]:
{
        "name": "weedle",
        "image": "https://c0.klipartz.com/pngpicture/478/959/sticker-png-pokemon-red-and-blue-pokemon-x-and-y-weedle-beedrill-others-tail-pokemon-evolution-pokemon-red-and-blue-pokemon-x-and-y.png"
    }

Then the image property:
"https://c0.klipartz.com/pngpicture/478/959/sticker-png-pokemon-red-and-blue-pokemon-x-and-y-weedle-beedrill-others-tail-pokemon-evolution-pokemon-red-and-blue-pokemon-x-and-y.png"

Then you use [Math.floor(Math.random() * pokemon.length)] to get the character at a random index in that string, heavily biased to the front based on the length of the pokemon array. In the posted error, that random character was h. The discord library tries to resolve h to a file relative to the working directory and of course fails.
I presume you want to pick a random pokemon and then get the image, which would be something more like this.
const pokemonImage = new Discord.MessageAttachment(pokemon[Math.floor(Math.random() * pokemon.length)].image)

Comment: Wow that was a perfect breakdown. Had I done that myself I would've realized immediately. Thank you for that. Now it may just be bad luck since it's 50/50 but it only seems to be displaying the second image. I've tested it 13 times and each time it was caterpie that showed up. Is that just bad luck or is something else wrong?
Comment: @QuazArxx I tested the random number generation and get each number within a few hundred times of the other running 100k at a time, that seems like a coincidence. https://jsfiddle.net/tnmuw710/1/
Comment: Gotcha thank you for your help. Do you know why I was also getting path undefined? Maybe the reasoning can help me fix why my friends' code won't work when I told him what to type out.
Comment: @QuazArxx That is worth a separate question.


Firebase function listening on project A, writing to project B

Question: I have two Firebase projects, A and B. When a user follows another user on Project A, data is written to <code>/followers/{followedUid}/{followerUid}</code>. I would like to perform this same update to Project B.
Users of Project A aren't (can't be) authorized to write to Project B, so I need to use a cloud function. I already do things like this with Node.js functions and firebase-admin using service accounts, but here I want to use a function deployed to Firebase.
How can I add or reference a service account, or otherwise authorize a second project in a Firebase cloud function?
Answer: If you've already done this with a local Node.js process and service account, the process within Cloud Functions is going to be pretty similar.
You'll need to initialize the Admin SDK with the credentials (in the form of a JSON file that you deploy with the code) for project B, and then use that for writing the data.
Also see the Firebase documentation on initializing the Admin SDK.
Comment: You'd deploy that credentials file with your Cloud Functions, by just putting the file in the same directory. Then you can load it with `require(./projectB-svcact.json').
Comment: yes, but how? In my Node functions I can put something like,
const secondaryServiceAccount = require('/path/to/service/account')
Where would the service account be located in this case? Thanks.
Comment: Sounds good, I'll try it! Obvious, I guess... thanks again


Problem on Mean Value Theorem

Question: The Question:
Let $f$ be a function defined on an interval $[a,b]$. What conditions could you place on $f$ to guarantee that
$$
\min f'\leq \frac{f(b)-f(a)}{b-a} \leq \max f'
$$
My Answer
We must require a $\min f'$ and a $\max f'$ before we can proceed further. That means $f'$ must be defined in $[a,b]$, that is, $f$ should be differentiable in $[a,b]$. So that's one condition.
Now, if $f$ is continuous in $[a,b]$ and differentiable in $(a,b)$ then, per the mean value theorem
$$
\exists \text{ } c\in(a,b) \text{ | } f'(c)=\frac{f(b)-f(a)}{b-a}
$$
and obviously
$$
\min f'\leq f'(c) \leq \max f'
$$
So the only condition would be for $f$ to be differentiable in $[a,b]$.
Now, I'll tell what's bothering me.
The textbook I'm reading currently has the following definition for absolute extrema.

Let $f$ be a function with domain $D$. Then $f$ has an absolute
maximum value on $D$ at a point $c$ if    $$ f(x) \leq f(c) \text{ }
 \forall \text{ } x \in D $$
and an absolute minimum value on $D$ at $c$ if $$ f(x) \geq f(c) \text{ }
 \forall \text{ } x \in D  $$

The reason, I've considered $f$ to be differentiable in $[a,b]$ and not just $(a,b)$ is because of the definition of absolute extrema.
Did I miss anything?
Comment: Looks good to me.
Comment: A function can be differentiable on $[a,b}$, but its derivative needs not be bounded.
Comment: @egreg That is exactly the doubt I'm having.

The textbook that I'm reading right now, where I came across this problem has the following definition for extrema: If $f$ is a function with domain $D$, then $f$ has an absolute extremum value on $D$ at a point $c$ if $f(x)\leq f(c)$ or $f(x)\geq f(c)$ (as applicable) for all $x$ in $D$.

That is why I considered $f'$ to be bounded so that it can have extrema, though, I can make up functions that are unbounded and have extrema. I'm confused.
Comment: @AbhishekAUdupa If a function is upper and lower unbounded, it cannot have extrema.
Comment: @egreg so then, if $f'$ is unbounded then $\max f'$ and $\min f'$ wouldn't exist right?
Comment: @AbhishekAUdupa Exactly my point!
Comment: @egreg So that means $f$ should be differentiable in $[a,b]$ and my answer attempt is correct?
Answer: You need to assume that the derivative is bounded if you want to actually bound the ratios $\frac{f(b)−f(a)}{b−a}$.
If you look at $f$ defined as:

$f(x) = \sin(1/x^2)\times x^2$ if $x\in(0,1]$
$f(0) = 0$

then $f$ is differentiable over all $[0,1]$, but its derivative is not bounded, as for $x>0$:
$$f'(x)=2x\sin\left(\frac1{x^2}\right) -\frac2x\times\cos\left(\frac1{x^2}\right)$$
and since the derivative values are limits of ratios $\frac{f(b)−f(a)}{b−a}$, those ratios are not bounded either.

Problem on Mean Value Theorem


Modifying a variable in Python

Question: I'm creating a Galaga clone with pygame and I am having issues with using a value in one function that was modified in other function.  I created a very simple version of the code to try to debug it but I have not had any luck.
import pygame
import time
pygame.init()
clock = pygame.time.Clock()

var1 = 10

def function3(var1):

    var1 = var1 + 2

def function1():
    gameExit = False
    while not gameExit:
        function3(var1)

        print(var1)
        clock.tick(5)
function1()

My question is (based on this simplified version) how do I display the updated value of var1.  I would like print(var1) to display 10,12,14,16...
My guess is to use a global declaration but the closest question that I found on stackexchange was this and it didn't seem to work with my scenario.
Please note that I'm aware that this increase of var1 could be done with a while loop but a while loop will not work with my actual code.  I would like an answer (or hint) that utilizes this format (as shown above).
Any suggestions would be appreciated.  Thanks!
Comment: return the value of `var1` as well in `function3`. And initialize it in `function1`. Refraining a downvote because Galaga is great.
Comment: So you want `var1=16` but `print(var1)` to show "10,12,14,16"? Perhaps you want each print to add to what you have already printed?
Comment: whoever downvoted this, please go back to facebook or something.
Answer: You should use return in your function:
import pygame
import time
pygame.init()
clock = pygame.time.Clock()

var1 = 10

def function3(v):
    return v + 2

def function1():
    gameExit = False
    while not gameExit:
        var1 = function3(var1)

        print(var1)
        clock.tick(5)

function1(var1)

Comment: Thanks!  I'm thinking of creating a class as @MK. suggested but return could also work.
Comment: This really is the "correct" way in Python as modifying global variables ruins modularization.
Answer: Here is "correct" way of doing what you want:
var1 = 10

def function3():
    global var1
    var1 = var1 + 2

print var1
function3()
print var1

Your code is modifying local variable var1 which is only defined within your function3.
I put word correct in quotes because global variable is (almost) never a good idea.  If you need state (variable) shared between multiple functions, you could create a class.  Or you could be modern functional and immutable and have the function take a value as argument, modify and return it.
Comment: Good to know.  Thanks for your quick response!   I'll look into creating a class...

Modifying a variable in Python


Fixed width div losing its background-color upon resizing the browser window

Question: I am creating a blog based on the 960 grid system. It has three simple divs:

header 2. Content 3. Footer and each of them has a fixed width div which holds 2-3 columns of text. The content div, and the fixed width div inside it have the same background color, but when i reduce the size of the browser window, for some reason it ignores the content div's color and reveals the color of the html body.

here's an example of another website where it happens: http://encourageothers.com/ ... reduce the size of the browser to something less than 900 px or so, and scroll horizontally to the right ... u will see what I mean.
Please help me! ... This is driving me nuts!!
Comment: This happens because the  tag's CSS "width" property is set to 100% (the default on all pages), which is the length of the browser's viewport. When you scroll horizontally, you go beyond 100%, where the body tag "stops". I haven't found a way to fix this, though.
Answer: jake is absolutely right with the 100% width related to the viewport of the browser.
instead of adding an additional max-width, add an additional MIN-width to the div showing the resize-problem. if your smallest width, before the scrollbar appears, is 1200px - just give the div in question a min-width of 1200px.
Answer: Found the solution! ... just set a max-width in pixels and also a width in 100% wherever u see this problem. Works for me.
Answer: I too encountered this problem.
Setting a width (in pixels) on the div container can lead to overflow problems. The same is true if you use rem or em. I needed a different solution.
My solution is to set display:inline-block; on the div container & wrap it in a div.

body {
    background-color: gray;
}
.container {
    background-color: red;
    display:inline-block;
}

bodybodybodybodybodybodybodybodybodybodybodybodybodybodybodybodybodybod

        divdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdivdiv

The above image shows what the problem looks like. To re-create the problem, just set display:block; on the container div & resize the browser window until you see the scrollbar on the bottom, then move the scrollbar all the way to the right.
As you probably noticed, the issue does not occur on the body tag when it has a background. But it does occur on the div tag with a red background.
Comment: A simpler solution might be to just add display:inline-block; on the body tag.


What is the probability that the system is working?

Question: A system consists of 10 devices.the system is working if atleast 8 devices are working.if each individual device is working with probability of 0.2,what is the probability that the system is working?
Comment: http://en.wikipedia.org/wiki/Binomial_distribution
Comment: There is no way to tell from the information given. Perhaps you are meant to assume that the events "device 1 is working", "device 2 is working", _etc._ are independent.
Answer: HINT: It's working if at most two devices have failed. Calculate the probability that no device has failed, the probability that exactly one device has failed, and the probability that exactly two devices have failed, and add them. Answers the following questions may help:

What is the probability that the first and third devices have failed and all other devices are working? How about the probability that the third and sixth devices have failed and all other devices are working?
How many pairs of devices are there altogether?


Do UIButtons' properties stay when put into an array?

Question: I was wondering if when I put a UIButton into an array like this:
<code>var array:[UIButton] = [UIButton]()
</code>
would the buttons tags, titles, images and other values be put into the array?
When the UIButton is appended, will the properties' values stay under the UIButton at the index that was appended?
Thanks,
Jack
Answer: All properties of the buttons would remain the same because you're not changing the buttons or their properties. Instead, you're just grouping the buttons into an array.


mumble-server i386 depends on libqt4-core and libssl0.9.8

Question: I am trying to use apt-get and i get this error.  It also doesnt allow me to install devs.
root@ubuntu:~# sudo apt-get install mumble
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 mumble : Depends: libasound2 (>= 1.0.23)
          Depends: libavahi-compat-libdnssd1 (>= 0.6.16) but it is not going to be installed
          Depends: libg15daemon-client1 but it is not going to be installed
          Depends: libprotobuf7 but it is not going to be installed
          Depends: libpulse0 (>= 1:0.99.1) but it is not going to be installed
          Depends: libqt4-network (>= 4:4.5.3) but it is not going to be installed
          Depends: libqt4-sql (>= 4:4.5.3) but it is not going to be installed
          Depends: libqt4-svg (>= 4:4.5.3) but it is not going to be installed
          Depends: libqtgui4 (>= 4:4.8.0) but it is not going to be installed
          Depends: libsndfile1 (>= 1.0.20) but it is not going to be installed
          Depends: libspeechd2 (>= 0.7.1) but it is not going to be installed
          Depends: libspeex1 (>= 1.2~beta3-1) but it is not going to be installed
          Depends: libspeexdsp1 (>= 1.2~beta3.2-1) but it is not going to be installed
          Depends: gconf2 (>= 2.28.1-2)
          Depends: libqt4-sql-sqlite but it is not going to be installed
          Recommends: speech-dispatcher but it is not going to be installed
 mumble-server:i386 : Depends: libqt4-core:i386 (>= 4.3.2) but it is not going to be installed
                      Depends: libssl0.9.8:i386 (>= 0.9.8e-1) but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
root@ubuntu:~# apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following extra packages will be installed:
  mumble-server:i386
Suggested packages:
  mumble-server-web:i386 mumble-django:i386
The following packages will be upgraded:
  mumble-server:i386
1 upgraded, 0 newly installed, 0 to remove and 5 not upgraded.
1 not fully installed or removed.
Need to get 0 B/958 kB of archives.
After this operation, 2,109 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
dpkg: dependency problems prevent configuration of mumble-server:i386:
 mumble-server:i386 depends on libqt4-core (>= 4.3.2).
 mumble-server:i386 depends on libssl0.9.8 (>= 0.9.8e-1).
dpkg: error processing mumble-server:i386 (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mumble-server:i386
E: Sub-process /usr/bin/dpkg returned an error code (1)

Comment: Edit your qustion and add the output of `sudo dpkg -C` and `apt-cache policy mumble-server:i386 libqt4-core libssl0.9.8`.
Comment: @close-voters Which answer in the original question is same as mine?
Answer: Try these commands on terminal,
sudo apt-get purge mumble-server:i386
sudo apt-get install mumble


Wordpress showing page name instead of blog posts

Question: I'm currently working on my first Wordpress theme and I've a problem:
I want to have my last 3 posts on every site. Everything works fine on my home page, but when I go to another page it just shows the page name and the "Read more..." tag after it.
The code I use is:
<?php while(have_posts()) : the_post(); ?>

» <?php the_time('l, j. F Y')?>

    <?php the_title(); ?>
    <?php the_excerpt(); ?><a href="<?php echo get_permalink(); ?>" style="color:white"> Mehr...

<?php endwhile; ?>

Does anyone know how to fix this issue? Thanks in advance!
Answer: For displaying posts on other pages, you have to display custom query before while loop.
Here is the updated code of your code:
<?php $the_query = new WP_Query( 'post_type'=>'post', 'posts_per_page=3' ); ?>

// Start our WP Query
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

» <?php the_time('l, j. F Y')?>

    <?php the_title(); ?>
    <?php the_excerpt(); ?><a href="<?php echo get_permalink(); ?>" style="color:white"> Mehr...

<?php endwhile;
wp_reset_postdata();
?>

May be this would be helpful for you.
Comment: Thanks! Works perfectly!


socket [SSL: CERTIFICATE_VERIFY_FAILED] (_ssl.c:590) from Client.py to Node Server.js

Question: I am getting this error
 File "C:\Python27\lib\ssl.py", line 844, in connect
    self._real_connect(addr, False)
  File "C:\Python27\lib\ssl.py", line 835, in _real_connect
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 808, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

I am trying to establish a secure connection(ssl.socket) between a python client and a node.js server and I took the above  error. I don't know what is missing or what's my fault. Here is my source code both for python client and for node.js server
Server Socket in Node.js :
var _HOST = '192.168.1.136';
    var _PORT = 1337;
    var _address;

    const tls = require('tls');
    const fs = require('fs');

    const options = {
        // These are necessary only if using the client certificate authentication
        key: fs.readFileSync('./SSL_TLS/ServerCakey.pem'),
        cert: fs.readFileSync('./SSL_TLS/Server-cert.pem'),
        requestCert: true
    };

    var server = tls.createServer(options, (socket) => {
        //const ProtocolEmmitter = new BasicProtocolEmmitter();

        socket.on('connect', (e) => {
            console.log('client connected ' +
                socket.remoteAddress + ':' +
                socket.remotePort);
            console.log('server connected',
                socket.authorized ? 'authorized' : 'unauthorized');
        });

        socket.on('data', function(data) {
            console.log('clients says' + ': ' + data);
        });

        socket.on('error', function(data) {
            console.log('client on error', data);

        });

        socket.on('close', (e) => {
            console.log('client disconnected');
            socket.end;
            setTimeout(() => {
                server.close();
                server.listen(_PORT, _HOST, () => {
                    _address = server.address();
                    console.log('opened server on %j', _address);
                    console.log(' Server listening on %j ', _HOST, ':', _PORT);
                });
            }, 10000);
        });

    });

and here is my Client.py Socket :(I am using  Python 2.7.11)
class SSLSocket:
    def __init__(self):
        Context = self.__loadContext()
        self._SSL_Sock = Context.wrap_socket(socket.socket(socket.AF_INET),
                                                           server_hostname=host)
       self._SSL_Sock.connect((host, port))

    def __loadContext(self):
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.verify_mode = ssl.CERT_REQUIRED
        context.check_hostname = True
        context.load_verify_locations("..Path/Client.crt")
        return context

i forgot to mention that i create with success the client.crt and i validate it with success
 `openssl x509 -req -days 365 -in server.csr -signkey server.key -out client.crt`

Signature Ok

Answer:
    context.load_verify_locations("..Path/Client.crt")

I think you have to problems here:

Wrong setup of the trust path: load_verify_locations should setup the trusted CA, i.e. it should contain the issuer of the servers certificate and not some client certificate.
Missing setup of the client certificate: For loading the client certificates you should use load_cert_chain.


How to fix a through hole in stucco on the outside of the house?

Question: Some contractors drilled some holes on the outside of the house and I need to patch them up.
One hole is about 1 to 1.5" in diameter. They drilled through so that they can put a piece of wire through to feel for studs! (apparently a stud finder didn't work)
There are some other smaller holes...they used a small drill bit...maybe 1/4" diameter.
My question is how do I patch those holes up? These holes don't have a surface on the other side.  If I were to just fill it with something there's nothing on the other side for the filler to hold on to, right?
What should I do this fix?
Can I just fill the hole with stucco patching compound? (Something like Quikrete Pre-Mixed Stucco Patch?)
UPDATE:
I can access some holes from the attic. Is there something that I can do from the back side of the hole from the attic? Should I screw in a metal mesh on the back side in the attic and then go to the outside and fill the whole with stucco patching compound?
Answer: The best way is to knock out enough stucco to find the studs, mount a backing plate to the studs, and stucco over that.
Now, that's a lot of work, so there are quicker& easier ways.  Perhaps you could cut a small plug out of plywood or similar material which press-fits each hole, then do a skim-coat over it to match the stucco.
It comes down to time vs. quality, basically.
Comment: That does seem like a lot of work for a 1.5" hole.  Aren't studs 16" apart?
Comment: @milesmeow   Well, I *did* sayit would be a lot of work...
Comment: Interesting idea to use a plug...
Comment: What about the small 1/4" holes? Just fill it right?


Long execution time when running PySpark-SQL on hadoop cluster?

Question: I have a data set of weather data and I am trying to query it to get average lows and average highs for each year. I have no problem submitting the job and getting the desired result but it is taking hours to run. I thought it would run much faster, Am I doing something wrong or is it just not as fast as I'm thinking it should be?
The data is a csv file with over 100,000,000 entries.
THe columns are date, weather station, measurement(TMAX or TMIN), and value
I am running the job on my university's hadoop cluster, I don't have much more information than that about the cluster.
Thanks in advance!
<code>import sys
from random import random
from operator import add
from pyspark.sql import SQLContext, Row
from pyspark import SparkContext

if __name__ == "__main__":
    sc = SparkContext(appName="PythonPi")
    sqlContext = SQLContext(sc)
    file = sys.argv[1]
    lines = sc.textFile(file)
    parts = lines.map(lambda l: l.split(","))
    obs = parts.map(lambda p: Row(station=p[0], date=int(p[1]) , measurement=p[2] , value=p[3]  )  )
    weather = sqlContext.createDataFrame(obs)
    weather.registerTempTable("weather")

    #AVERAGE TMAX/TMIN PER YEAR
    query2 = sqlContext.sql("""select SUBSTRING(date,1,4) as Year, avg(value)as Average, measurement
                                from weather
                                where value<130 AND value>-40
                                group by measurement, SUBSTRING(date,1,4)
                                order by SUBSTRING(date,1,4) """)

    query2.show()
    query2.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("hdfs:/user/adduccij/tmax_tmin_year.csv")
    sc.stop()

</code>
Comment: try out the suggestions I mentioned. If you provide some more details e.g. # executors and which part of code is actually taking long, maybe I can provide more input.
Answer: Make sure that spark job in fact started in cluster (and not local) mode. e.g. If you're using yarn, then job is launched in 'yarn-client' mode.
If that's true, then make sure you've provided enough #executors/cores/ executor and driver memory. You can get the actual cluster/job information from either the resource manager (e.g. yarn) page or from spark context (sqlContext.getAllConfs).
100Mil records is not that small. Let's say each record is 30 bytes, still the overall size is 3gb and that can take a while if you only have a handful of executors.
Let's say that the above suggestions do not help, then try to find out which part of the query is taking long. Few speed up tips are:

Cache the weather dataframe
Break the query into 2 parts: 1st part does group by, and output is cached
2nd part does order by
instead of coalesce, write the rdd with default shards and then do a mergeFrom to get your csv output from shell.
Comment: ok great. 4th point was about .coalesce(1) that you do before writing to text file. That essentially causes your rdd to get redistributed into 1 partition before writing to hdfs. That might be a slow operation as well. If you're doing that so that you get only 1 file in output, then same thing can be achieved by writing the rdd as it is in the hdfs and then running following to merge output in single file: hdfs dfs -getmerge /user/adduccij/tmax_tmin_year.csv single_file_out.csv
Comment: Breaking query apart and caching helped significantly. Can you explain the fourth bullet a little more, "instead of coalesce, write the rdd with default shards and then do a mergeFrom to get your csv output from shell."


Kalman Filter sensor model - Variance changes over distance

Question: I'm using a range sensor (Infrared Sensor) to measure the distance between the robot and an obstacle. However I did some measurements and their variances change over distance.
I took 1000 samples of a few distances (10cm, 20cm, 30cm, 40cm, 50cm ...) and their mean value matches the distance, however the variance increases about 2x at every 10cm increments. What is the best way to deal with it? I can create my covariance matrix R dinamically based on its values or what should be the best approach in this case?
Answer: You should calculate the variance including all the measurements and use that for your measurement covariance, $R$. I am not familiar with any method that does what you describe. Using an adaptive Kalman filter, the process covariance, $Q$, and the measurement covariance $R$, are dynamically modified, but those methods do not do what you describe (e.g. specify a different variance for each different magnitude of the measurement).


Do all sliding glass patio doors come pre-assembled in one piece?

Question: I'm doing a soundproofing project in my basement, setting up a small home recording studio, and I need a door that doesn't swing. Looking at other studios, I notice that they often go with a double set of exterior sliding glass patio doors (air gap in between). I think this is a great solution since patio doors are designed to be air tight and insulate well (in Canada anyways) and shouldn't let a lot of sound through.
My problem is that all the patio doors I can find come with pre-assembled frames (72"x80"), and I won't be able to fit it around the turn in my basement stairs.
Where can I find glass exterior doors that come in pieces so that I can actually get it down to the basement?
Any other soundproof non-swinging door ideas out there? DIY options?
Answer: A swinging door would be very convenient in this case since you can very easily find a thick door, seal any gaps and install sound insulation. However, if you really won't be able to install a swinging door you might find this helpful:
Door:
You could install a soundproofing sliding door, with roughly the same money. I suggest installing above the door entry a slider. Now you can find a really cheap wooden sliding door that fits around the turn. You don't need to go for a glass door, it is more expensive and will be more difficult to soundproof. A swinging door will do just as fine if you tweak it and add some rollers on top of it. This is what requires the most effort because you need to be very precise with the measurements, in order to leave as small gaps as possible. (In fact, we did the same on a door we couldn't replace because it was too old, and we weren't able to find doors with those dimensions).
Soundproofing:
If the door is really cheap, then it is also probably hollow and that won't block the sound. You can install soundproofing material of your choice (you can find really good deals for old foam mattresses which do the job) on the side of the door that is always shown whether it is open or closed. Lastly, however good the measurements are, there will always be gaps on the sides. To eliminate this, you can glue some sort of soundproofing strips on the 2 walls on the side, the ledge above and on the bottom part of the door, so that they are a tight fit for the door.
I hope this helps!
Comment: Hi Michael, agreed, a heavy swinging door would be more convenient, and it is an option I suppose, I just really don't want to lose the room space. Typically the DIY approach is to actually put 2 swinging exterior fibreglass doors together with an air gap in between, although that would result in losing space on both sides of the entry. The challenge of putting a door like that on a slider is making it seal tight enough to be soundproof. Hanging foam or mattresses on the door may be considered acoustic treatment for a room, but will do absolutely nothing in regards to soundproofing the room
Answer: There are three possibilities I have for you.
In your sliding door scenario : one door is for first entry and the air Gap provides some sound insulation properties when traversing from one area into the other.
Anderson Sliding Glass Door frame that requires assembly.
Here are some possibilities or a combination of the two items.
If you have the possibility to install a pocket door this might allow you to achieve the same thing with the ability to install in pieces.
Also revolving dark room doors for the outer and the pocket door for the inner
Comment: Hi Ken, great answer, it shows that unassembled glass sliding doors do exist! I also really like the pocket door idea, although this would require a lot more work and creativity. I would have to make my wall thicker (so it could house a sliding door inside and still be soundproofed), and It would have to be heavy, thick, and sealed airtight when closed (for soundproofing). I am up-voting this answer, however I will be posting my own as I did some searching around this weekend, and found a door perfect for my needs. Thanks Ken
Answer: I'm going to answer my own question here as I found a door perfect for my needs. After asking the folks at my local home depot, I found out about a door called a 2 plus 2. That is, a sliding door with essentially 2 sets of glass doors in it. These doors are often used in houses to help insulate against more extreme weather conditions, and should work quite well for my soundproofing project.
http://standarddoors.com/products-high-quality-doors/the-original-2Plus2-aluminum
The best part, you can buy them in a knocked-down format! That is, completely unassembled so that one person can easily carry, transport and install. Perfect.


Combining inequalities

Question: When working through the division algorithm I came across a combined inquality that does not strike me as obvious.  This fact is used to prove the uniqueness of the remainder.
Given that $0 \leq r < b$ and $0 \leq r_1 < b$, we have
$$-b < r - r_1 < b.$$
Is there a obvious way to combine these guys?  Is there some bounded theorem I an use here?  I can see that the result is true, I just do not see a comcrete way of getting there.
Answer: If $a\leqslant r\lt b$ and $-b_1\lt -r_1\leqslant -a_1$ then $a-b_1\lt r-r_1\lt b-a_1$.
Comment: It is much more clear if you put it that way.  It helps, thank you very much.

Combining inequalities


bitwise operators and error levels (php)

Question: I have created a user error handler, and I want to make sure that I am using bitwise operators correctly.
Here are my config settings to set which errors will be handled in which way:
// user error logging level (change for production)
define('LEV_USER_ERROR_LOG_LEVEL', E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);

// user error display level (change for production)
define('LEV_USER_ERROR_DISPLAY_LEVEL', E_USER_ERROR);

Here is how I set the user error handler:
// set user error handler
set_error_handler('user_error_handler', E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);

Here is the error handler itself:
    // user error handler
    public static function user_error_handler($error_level, $message, $file_name, $line_number) {
        if (LEV_USER_ERROR_LOG_LEVEL | LEV_USER_ERROR_DISPLAY_LEVEL == 0) return true;
        switch ($error_level) {
            case E_USER_ERROR:
                if (LEV_USER_ERROR_LOG_LEVEL & E_USER_ERROR) {
                    error_log('[' . date('Y-m-d h:i:s') . '] User Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . "\"\n", 3, 'application/logs/user_error_log.txt');
                }
                if (LEV_USER_ERROR_DISPLAY_LEVEL & E_USER_ERROR) {
                    echo '[' . date('Y-m-d h:i:s') . '] User Level Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.'
';
                }
                die;
                break;
            case E_USER_WARNING:
                if (LEV_USER_ERROR_LOG_LEVEL & E_USER_WARNING) {
                    error_log('[' . date('Y-m-d h:i:s') . '] User Warning: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . "\"\n", 3, 'application/logs/user_error_log.txt');
                }
                if (LEV_USER_ERROR_DISPLAY_LEVEL & E_USER_WARNING) {
                    echo '[' . date('Y-m-d h:i:s') . '] User Level Warning: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.'
';
                }
                break;
            case E_USER_NOTICE:
                if (LEV_USER_ERROR_LOG_LEVEL & E_USER_NOTICE) {
                    error_log('[' . date('Y-m-d h:i:s') . '] User Notice: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . "\"\n", 3, 'application/logs/user_error_log.txt');
                }
                if (LEV_USER_ERROR_DISPLAY_LEVEL & E_USER_NOTICE) {
                    echo '[' . date('Y-m-d h:i:s') . '] User Level Notice: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.'
';
                }
                break;
            default:
                // call PHP internal error handler
                return false;
        }
        // do not call PHP internal error handler
        return true;
    }

Questions:

The bitwise OR operator used in my handler setting will make it so that the error handler is ONLY called when one of those three errors occurs?
The bitwise OR operator used in the first line of my error handler will make it so that ONLY if both of the config settings are set to zero, the function will exit?
Answer: In the line
if (LEV_USER_ERROR_LOG_LEVEL | LEV_USER_ERROR_DISPLAY_LEVEL == 0) return true;

the comparison is stronger than the bitwise operator, so you need parentheses:
if ((LEV_USER_ERROR_LOG_LEVEL | LEV_USER_ERROR_DISPLAY_LEVEL) == 0) return true;

Then your code will work as you describe.


How to declare a Linq Expression variable in order to have it processed as a dbParameter

Question: I'm trying to create dynamic queries against Entity framework (or other Linq provider).
Let me explain my problem with some sample code.
If I hardcode an expression :
var id = 12345;

Expression<Func<ItemSearch, bool>> myLambda = (s) => s.Id == id;

var finalQuery = context.ItemSearch.Where(myLambda);
this.Log((finalQuery as ObjectQuery).ToTraceString());

The generated SQL looks like this :
SELECT ...
FROM ViewItemSearch "Extent1"
WHERE "Extent1".ID = :p__linq__0

with a nice :p__linq__0 dbParameter.
If I create an expression :
var id = 12345;
ParameterExpression param = Expression.Parameter(typeof(ItemSearch), "s");
Expression prop = Expression.Property(param, "Id");
Expression val = Expression.Constant(id);
Expression searchExpr = Expression.Equal(prop, val);

Expression<Func<ItemSearch, bool>> myLambda =
    Expression.Lambda<Func<ItemSearch, bool>>(searchExpr , param);

var finalQuery = context.ItemSearch.Where(myLambda);
this.Log((finalQuery as ObjectQuery).ToTraceString());

The generated SQL looks like this :
SELECT ...
FROM ViewItemSearch "Extent1"
WHERE "Extent1".ID = 12345

No more :p__linq__0 dbParameter so the Db engine cannot cache query plans.
I understand that it is because I use
Expression val = Expression.Constant(id);

But I can't figure out how to bind a variable instead of the value.
Comment: I find your question somewhat confusing. If you want to dynamically add `AND` logic conditions, just declare an `IQueryable` and dynamically append `.Where(i => yourPredicate)`. See:
http://stackoverflow.com/questions/11189826/c-sharp-dynamic-linq-variable-where-clause

If you want to apply `OR` logic you will need an approach such as this:
http://www.albahari.com/nutshell/predicatebuilder.aspx
Comment: The 'or' and 'and' expressions work just fine. The problem reside on the binding of parameters. Maybe I should edit the question and remove the end. Which is just for context.
Answer: You'll need to create a lambda at compile time to close over the id variable, to which you can then grab the body of an use in the composition of your more complex lambda:
var id = 12345;
ParameterExpression param = Expression.Parameter(typeof(ItemSearch), "s");
Expression prop = Expression.Property(param, "Id");
Expression<Func<int>> idLambda = () => id;
Expression searchExpr = Expression.Equal(prop, idLambda.Body);

Expression<Func<ItemSearch, bool>> myLambda =
    Expression.Lambda<Func<ItemSearch, bool>>(searchExpr, param);


Bootstrap 3 Navbar Dropdown functionality not working with JScript

Question: I am using Bootstrap 3 and the Datepicker and MaskMoney plugins. My problem is that when I don't reference the above plugins, the bootstrap dropdown Navbar works 100%, but as soon as I have any javascript used in these plugins, the dropdown functionality on the Navbar stops working.
Any help would be greatly appreciated.
My layout file (_Layout.cshtml) is as follows:-
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>@ViewBag.Title - My Application</title>
    @RenderSection("meta", required: false)
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    @Styles.Render("~/Content/bootstrapcss")
    @Styles.Render("~/Content/customcss")

    @Html.Partial("_NavBar")

    @RenderSection("featured", required: false)

        @RenderBody()

© Company Name 2014

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrapjs")

My navigation bar file (_NavBar.cshtml) is as follows:-
@helper ActiveItem(string actionName, string controllerName, string areaName)
{
    if (ViewContext.RouteData.Values["action"].ToString() == actionName &&
            ViewContext.RouteData.Values["controller"].ToString() == controllerName &&
            (ViewContext.RouteData.DataTokens["area"] == null || ViewContext.RouteData.DataTokens["area"].ToString() == areaName))
    {
    @:active
    }
}

            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

            </button>

@Html.ActionLink("Home", "Index", "Home")

                    Client

@Html.ActionLink("Standing Data", "Index", "Client")

Exposure

Guarantees

Investments

Loans

Transaction Accounts

Combined View

My view file (Client\Index.cshtml) is as follows:-
@using TwitterBootstrap3
@model Px.MVC.BS.Web.Models.Client
@{
    ViewBag.Title = "Index";
}
@Styles.Render("~/Content/bootstrapcss")
@Styles.Render("~/Content/customcss")

Client Details

                    @(Html.Bootstrap().LabelFor(m => m.Surname).LabelText("Surname"))

                    @(Html.Bootstrap().TextBoxFor(m => m.Surname))

                    @(Html.Bootstrap().LabelFor(m => m.Forname1).LabelText("Forenames"))

                    @(Html.Bootstrap().TextBoxFor(m => m.Forname1))

                    @(Html.Bootstrap().LabelFor(m => m.Initials).LabelText("Initials"))

                    @(Html.Bootstrap().TextBoxFor(m => m.Initials))

                    @(Html.Bootstrap().LabelFor(m => m.DOB).LabelText("Date of Birth"))

                        <input class="form-control" type="text" readonly="" placeholder="Select Date">

                    @(Html.Bootstrap().Label("Balance").LabelText("Balance Outstanding"))

                    <input class="form-control" type="text" id="Balance">

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrapjs")

As I have bundled all my CSS and JS files, my BundleConfig.cs file is as follows:-
using System.Web;
using System.Web.Optimization;

namespace Px.MVC.BS.Web
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.IgnoreList.Clear();

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery.maskMoney.min.js"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrapjs").Include(
                        "~/Scripts/bootstrap.min.js",
                        "~/Scripts/bootstrap-datepicker.js"));

            bundles.Add(new StyleBundle("~/Content/bootstrapcss").Include(
                        "~/Content/bootstrap.min.css",
                        "~/Content/datepicker.css"));

            bundles.Add(new StyleBundle("~/Content/customcss").Include(
                        "~/Content/font-awesome/css/font-awesome.min.css"));

            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
        }
    }
}

If I go into Client -> Standing Data, the Client\Index.cshtml view displays correctly, but the dropdown in _Navbar.cs does not expand. If I then go into Home on the menu, the functionality of the dropdown is again available - it is as if it gets reset?
Thanks is advance for helping me out here.
Comment: did you see any script errors in browser console? F12 in chrome or in IE.
Comment: As far as I can see there are no script errors.
Comment: Problem solved. Unfortunately as I do not have enough points I am unable to post the answer here for 24 hours. I will post in the next few days. The problem lay in the order of the .js files within view Client\Index.cshtml and BundleConfig.cs
Comment: cool. please answer your question, so that it may help someone who has the same problem.
Answer: I changed the order of the .js files in Client\Index.cshtml as follows:-
@using TwitterBootstrap3
@model Px.MVC.BS.Web.Models.Client
@{
    ViewBag.Title = "Index";
}
@Styles.Render("~/Content/bootstrapcss")
@Styles.Render("~/Content/pluginscss")
@Styles.Render("~/Content/customcss")

Client Details

                    @(Html.Bootstrap().LabelFor(m => m.Surname).LabelText("Surname"))

                    @(Html.Bootstrap().TextBoxFor(m => m.Surname))

                    @(Html.Bootstrap().LabelFor(m => m.Forname1).LabelText("Forenames"))

                    @(Html.Bootstrap().TextBoxFor(m => m.Forname1))

                    @(Html.Bootstrap().LabelFor(m => m.Initials).LabelText("Initials"))

                    @(Html.Bootstrap().TextBoxFor(m => m.Initials))

                    @(Html.Bootstrap().LabelFor(m => m.DOB).LabelText("Date of Birth"))

                        <input class="form-control" type="text" readonly="" placeholder="Select Date">

                    @(Html.Bootstrap().Label("Balance").LabelText("Balance Outstanding"))

                    <input class="form-control" type="text" id="Balance">

@Html.Partial("_ClientTab")

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/pluginsjs")

As well as changing BundleConfig.cs as follows:-
using System.Web;
using System.Web.Optimization;

namespace Px.MVC.BS.Web
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.IgnoreList.Clear();

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrapjs").Include(
                        "~/Scripts/bootstrap.min.js"));

            bundles.Add(new StyleBundle("~/Content/bootstrapcss").Include(
                        "~/Content/bootstrap.min.css"));

            bundles.Add(new ScriptBundle("~/bundles/pluginsjs").Include(
                        "~/Scripts/jquery.maskMoney.min.js",
                        "~/Scripts/bootstrap-datepicker.js"));

            bundles.Add(new StyleBundle("~/Content/pluginscss").Include(
                        "~/Content/datepicker.css"));

            bundles.Add(new StyleBundle("~/Content/customcss").Include(
                        "~/Content/font-awesome/css/font-awesome.min.css"));

            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
        }
    }
}

I have found that the order of both .css and .js files included in your page is very important.
I hope this helps others.


Is it possible to replace content in a file without deleting the file?

Question: I am wondering is it possible to replace contents without?
I have tried this with file.write(), however, it has just been added to the content of the file, not replacing it. Does it possible to replace the contents in a file without deleting the file itself?
 the_json_file.write_all(inside_da_file.as_bytes()).expect("Failed to write");I wanted to clear out the file before I write into it.
Comment: Hi @TaceCat, please give us an example (code) of what you want to do
Comment: Does [How to replace a word in a file in a .txt](https://stackoverflow.com/questions/27215396/how-to-replace-a-word-in-a-file-in-a-txt) help?
Comment: Hi @gedflod, I have edited it and what I wanted to do is listed on top.
Comment: Duplicate: https://stackoverflow.com/questions/65782872/how-to-delete-the-contents-of-a-file-before-writing-to-it-in-rust
Answer: As documented under OpenOptions::truncate:

Sets the option for truncating a previous file.
If a file is successfully opened with this option set it will truncate
the file to 0 length if it already exists.
The file must be opened with write access for truncate to work.
Examples
use std::fs::OpenOptions;

let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");

Alternatively, to truncate the file after it has been opened, there's File::set_len followed by Seek::rewind:
use std::io::{Seek, Write};

the_json_file.set_len(0).unwrap();
the_json_file.rewind().unwrap();
the_json_file.write_all(inside_da_file.as_bytes()).expect("Failed to write");


Is it safe to remove vent and cap off unused drain

Question: I am in the process of renovating my kitchen and removed a wall. I discovered a closed off drain and a vent that goes through the ceiling.
There does not appear to be anything else tied into the vent. It also appears to be an old laundry area. Maybe it's not important but there is an active sink next to it. It has a separate drain and its own dedicated vent out the ceiling.
It will be blocking the walk way so it needs to be removed. Is it safe to cap off the entire pipe and cement over it? Anything else I should be cautious of before I proceed?
I have a licensed plumber standing by, just waiting for him to fit me into his schedule. I would love a second opinion.
Comment: When you remove the section of pipe, will the weight of the remaining pipe cause it to drop down...pulling it through the roof?
Comment: I would go into the attic and cut it there first.
Answer: With it being unused I would not have called a plumber. But taken it off myself, the hard part will be the threads will be above the slab so capping flush with the concrete will be more work , you may be able to plug it With an expanding plug that would allow it to be cut off flush but it may need a gap so the plug never gets pushed down.
Answer: It is unwise to disconnect any active drain vent. If that laundry area has a washer, sink, or anything else you need to leave it in place. If you remove it you will have problems with the laundry devices and possible other items draining properly. If the vent is in the way it can be rerouted. My best advice is do what the plumber suggestions, he is a pro and knows the codes etc in your area. You can verify my suggestions with him to be sure.
Comment: Thanks for the update. Have a great week!
Comment: It was actually unused and previously capped off. I removed it safely, no issues with plumbing so far. Just need my plumber to come over and help me route a vent underground. (It's been tough scheduling him, everyone seems to want to be rennovating these days)


trouble generating new rails controller

Question: I am new to ruby on rails development. I am currently having difficulties generating a new rails controller. here is what I input into the terminal:
$ rails generate controller static_pages home help

here is the response I receive:
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:177
:in `rescue in spec': Specified 'sqlite3' for database adapter, but the gem is not loaded.
Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). (Gem::LoadError)

I am also using Heroku for production so I initially removed sqlite3 because Heroku cant use it by doing:
$ gem uninstall sqlite3

and I removed it from my gemfile and gemfile.lock. Was this a mistake? Any guidance would be much appreciated.
Answer: you cold try to rm Gemfile.lock and bundle install to reinstall your gems
Also make sure that the sqlite3 gem is in the development group
gem 'sqlite3', :group => :development

So that it will not be install on Heroku
Comment: http://rubyofftherails.blogspot.com.br/2016/02/i-want-to-use-heroku-but-my-app-uses.html
Answer: The error is because the config/database.yml file still has sqlite3 as the database adapter for the development database.
If you know which database you want to use for your local development database, set the appropriate database adapter in this file.
Heroku can't use sqlite3; however, you can use sqlite3 for your local development database, and specify postgres or mysql for production database.
Since you are a total beginner, I would recommend following the steps from a detailed tutorial as it is till you become familiar with the various concepts. Michael Hart's Rails Tutorial book is available for free online, and is a very good resource for beginner rails developers.
Comment: I am using that book. Thank you very much for your help!

trouble generating new rails controller


Coffee machine trips circuit breaker

Question: Not always but it happens from time to time.
A technician visited for this issue and at that time we couldn't reproduce the situation but he observed my coffee machine hit very high ampere like 9 or 11A at the beginning very shortly. but breaker unit can hold 20A. We guessed even though the reader couldn't catch it but it could reach to 20A or nearby threshold point. Anyway, he replaced the break unit with another and said let's see what would happen.
Later, I have the same problem one or two times a week again.
Now, I wonder if there is any high current holding outlet so that it prevent high current from flowing in a very short moment?
Or, is this coffee machine problem?
Comment: If it has a test _button_, then it would be GFCI.  Square D commercial breakers have a clear window that shows red when a breaker is tripped so don't confuse the two.  The breaker would probably say "GFCI" or "AFCI" if that's what it is.
Comment: Is this a normal breaker or a GFCI/AFCI breaker?
Comment: A standard breaker will not trip instantly.  It has a time delay relative to the current being drawn.  Depending on the breaker, you can draw multiples of the listed current for seconds before the breaker will trip.  A small spike that the meter wasn't fast enough to catch wouldn't trip a standard breaker.
Comment: I checked the breaker and found yellow square D symbol and red test button and on/off switch with "20" only. So, I think it is not a GFCI.
Comment: Thank you, @JPhi1618. I decided to move my coffee machine to the other line as Billy C suggested.
Answer: It sounds like there is other equipment on this circuit of which you are unaware.  Perhaps your refrigerator?  It's a common intermittent load in kitchens that could easily pop a breaker in combination with a coffee maker.
Your electrician should have measured amperage draw inside the electrical panel when he swapped out the breaker.
Invite the electrician back over, for some coffee.
You can use a Watts-Up or Kill-a-Watt meter to measure the coffee maker's draw at the outlet:
And the electrician should have an amp clamp to measure at the breaker.
Comment: Ok.  So that's the answer.  Fridge and coffee maker shouldn't be sharing circuits.   Refrigerators often have several stages of power draw, and can pull quite a lot at their max.  If you can't move your coffee machine to another circuit, you'll need to turn off the fridge first.  Try that for a couple weeks, and you'll see the problem go away.  I could hypothetically imagine using zwave controllers to cut power to your fridge automatically every time the coffee maker goes on.  But you'd have to program that, and it could damage the fridge to do that to often.
Comment: One last thing just occurred to me that I thought I'd add.  You could use the zwave controllers in the opposite order.  Set it up so that when the FRIDGE is drawing > 2A, it turns power off to the coffee machine.  Most simple coffee machines I've seen should suffer NO damage being controlled like that, though it could make it a nuisance to make coffee in the morning.  When I was a kid I had an AC, mini fridge, microwave, and four computers on UPS in my bedroom on a shared 15A circuit.  I used X-10 and a VB 6 program to juggle load, and the UPSes were needed to keep the computer running it on.
Comment: Yes, he had the amp clamp and measured on the breaker line on which I connect refrigerator, my coffee machine, and my echo. usually, without coffee machine, it showed 1~2A.
Comment: I wonder if the only solution is to move my coffee machine to the other line which has no device connected. :(
Answer: If the coffee maker's heating coil is cracked, it will fault through the water to ground and trip the breaker as it should.

Coffee machine trips circuit breaker


How do I improve specific gravity in a 4 year old battery

Question: The specific gravity indicates almost nonexistent acid level.   Barely above water.   What is the best way to bring this battery back to life.  It is a 6 volt solar battery.
Comment: What is the open circuit voltage? What's the voltage under load?
Answer: In most cases, take it on a trip to the recycling center, or trade it in to be recycled when you buy the replacement. Lead acid batteries are a consumable item in solar service, and more so if the solar service is poorly managed such that they are not brought to full charge, or are over-discharged on a regular basis. They are a finicky and fickle part of the system, but less costly than batteries that are more tolerant of imperfect operating conditions.
You can charge the heck out of it, but it's probably past saving that way. You may be thinking "I can just add acid" but that does not actually work since the problem is not lack of acid, but where that acid has gone, chemically. Add sufficient distilled water, only, but I very much doubt you'll bring it back from the grave.
Answer: Assuming a standard lead acid battery, it is difficult if not impossible to reanimate it after a long time without recharging. The lattice of the active material changes into a status that can no more be reversed. This is why lead acid batteries should be only stored if 100% charged, and regularly recharged to compensate for the self discharging.
Otherwise sometimes a sort of pumping = short high current pulses helps to bring an unloaded battery back to life. These pulses must only be applied if the battery is below ca. 40% charge status. It helps to bring the possible insulated active material "islands" back into contact to it's neighbours. The temperature must be  checked against overheating. The location must be well vented, since H2 and/or O2 gases can be produced, which are an explosive mixture. PPE is mandatory to protect the eyes, face, skin.
If destilled water must be filled into the cells, the material like funnel and bottles must be free of any dirt or ions. No metal must be used. Any plastic containers that were in contact with detergents can ruin a battery. Some chemists say the open battery needs a cleaner room resp. cleaner air then a hospital's surgery room.
The reason might be the very tiny volume/mass of material needed to be chemically dissolved in the acid and spread over the surface of the active material thus ruining it.


hierarchical tables?

Question: I have a shallow tree to display: action -> action item -> error
There can be millions of actions, tens to thousands of items per action and (usually) 0 to 1 errors per item. There can be also errors for an action (then I guess tens of them).
Obviusly with that amount of data actions and action items need to have some filtering.
The goal is to:

quickly see the status of an action
to browse errors for an action
to see on which action items the action was executed

All of these 3 object have more properties than the columns I could fit resonably in a table (but not too much, 5-15 at the moment).
Do you have some pattern for showing such data?
Would you use 2 paginated tables for actions and items, the items table depending on actions table?
Some kind of paginated tree? What is your suggestion for such kind of data?
Answer: This is difficult to answer without more context.What are the types of actions, items, and errors?  What function/s are you trying to perform or what problem/s you are trying to solve?
It looks like you are wanting to show potentialy thousands of millions of entries.  Trying to show this quantity of data in a meaningful way is pointless without specialist visualization methods/tools such aggregate vizualizations or treemaps.
For an idea of just how pointless it is trying to use something like tables for this try doing a google search for 'music' - out of the 8,470,000,000 results you are only shown the first 10-100 items (depending on settings).  Even at 50 results I would consider this to be cognitive overload.
Tring to show this much data you will run into some of the following problems:

clutter
performance issues
information loss

The Visual Information Seeking Mantra states:

Overview First, Zoom and Filter, Details-on-Demand
  - Ben Shneiderman

This was evolved to the Visual Analytics Mantra:

Analyze First, Show the Important, Zoom, Filter and Analyze Further, Details-on-Demand
- Daniel Keim

What these break down into is that sometimes you need to use the power of the machine first and let it discover if there is anything interesting/useful to show before visualization is used.
See also Fell in Love with Data and Extreme Visualization:
Squeezing a Billion Records into a Million Pixels

hierarchical tables?


How does OpenID work?

Question: Can someone help me understand how OpenID works? I'm interested in the following answers:

Do you still have to store user ids and passwords if using OpenId?
How does my application create a new session when a user logs in?
When users log out of the application do I need to do anything other than clear their session data? Do I need to inform the openId server?
Answer: My understanding is the following:

OpenId allows users to log in in a decentralized manner.  Which means the the user's login credentials are handled by one site, the provider
Your system will interact with the provider to determine if a user is who they say they are.  If they pass that check, your system logs them in.
You still need to store some user information because the details of how they can use your system must be stored within your system.

So, if Google is an open id provider, SO can verify that I logged into google and am who I say I am.  SO then says, great, this user is hvgotcodes in our system and gives me privileges that make sense for who I am in SO.
In answer to your specific question about logout, yes, you still log the user into your system after the open id provider verifies the users credentials, and hence you can handle their log out status from your own system.
Answer: I recently made an openid authentication system this is how it works.
login:

User puts in openid url (not
necessarily unique),
Openid provider verifies and
provides a unique openid url,
on success.
Put this url in the session.

authenticate request:
there is a table that maps openid url to user.
for each request:

Look for openid url in the session
If exists, lookup user record and
attach it to the request
Process the request.

Do you still have to store userIDs and
  passwords if using openId?

userIDs yes, passwords no (unless you provide other ways to login except openid)

How does my application find out and
  create a new session when someone logs
  in?

Sessions are handled as normal, sessions are for authenticated and unauthenticated users.

When I use logs out of my own
  application, do I need to do anything
  more than just clear their session
  from my application? (Do I need to
  inform the openId server?)

Nope.

How does OpenID work?


Using dependent name in base class name without "typename"

Question: I have a template class for which the base class is also a template parameterized with a type member of one of the outer template type parameters. Example:
template <typename X>
class Adapter : public Generator<typename X::generated_type>{
    using G = typename X::generated_type;
};

Here X is some type that has a member generated_type and we want to subclass a Generator for X::generated_type. Because X::generated_type is a dependent name, we have to prefix it with typename when we use it in the base class name.
In the rest of the definition of Adapter, I can use G instead of typename X::generated_type, which is obviously a lot more convenient.
Is there any way to use G in the name of the base class too?
In the actual code it's not this simple; I've tried to distill the example down to the core issue.
The only thing I could think of was to have G as a template parameter and create a wrapper that passes X::generated_type as G.
Answer: One possible solution is to cheat, something along these lines:
template <typename X, typename G=typename X::generated_type>
class Adapter : public Generator<G>{
   // ...
};

You were almost there, heading into an additional template parameter territory, but you don't need to explicitly pass it in, just default it.
Complete example:
template<typename> class Generator {};

template <typename X, typename G=typename X::generated_type>
    class Adapter : public Generator<G>{
       // ...
    };

struct Y {
    typedef int generated_type;
};

int main()
{
    Adapter<Y> a;

    return 0;
}

Comment: I thought I tried that but maybe I didn't do it correctly and just assumed it wouldn't work.
Comment: Okay, it does work! Thanks, that's what I was looking for.
Comment: I can't accept your answer yet, have to wait a few min.
Comment: Other way would be for Generator provide that type , or have a type trait class
Comment: By having `Generator` provide the type, I assume you mean a `typedef` or `using` in `Generator` that exposes `G`. But I don't think that helps avoid the need to use `typename` when declaring the `Generator` base class.