Let $(x_n)$ be a sequence that converges to a number x. Show that $(s_n)$ converges to x as well.

Question: Let $(x_n)$ be a sequence that converges to a number x.  Define a new sequence $(s_n)$ by
$s_n= \frac{1}{n}\sum\limits_{k=1}^n x_k$
Show that $s_n$ converges to $x$ as well.
Comment: This has been asked before.
Comment: I just realized the linked duplicate covers a converse. I'm looking for a duplicate.
Answer: Given $\varepsilon >0,$ there is $n_0\in \mathbb{N}$, such that for all $n>n_0$ implies that
$\left|x_n-x\right|<\varepsilon.$ So, for $n>n_0$,
$$\left|\frac{1}{n}\sum_{i=1}^nx_n-x\right|=\frac{1}{n}\left|\sum_{i=1}^nx_n-nx\right|\leq\frac{1}{n}\sum_{i=1}^n \left|x_n-x\right|\leq \frac{1}{n}n\varepsilon=\varepsilon.$$
Then, $s_n=\frac{1}{n}\sum_{i=1}^nx_n$ coverges to $x$.
Comment: In the last inequality you don´t have $|x_k - x| < \epsilon$ for all $k$, only for those where $k>n_0$.


Nested Dictionary Comprehension in Python with List of Values

Question: I have three dictionaries that I would like to combine:
dict_A = {'Archives': '1234',
          'Content Revenue': '4567'}

dict_B = {'Archives': {'Content Partners Draft': '1111',
                       'Revenue Dashboard': '2222',
                       'Customer Lifetime Value Dashboard': '333',
                       'Customer Liftime Value V3': '4444'},
          'Content Revenue': {'License Tracker': '5555',
                              'MONTH_END_PARTNER_REPORT': '6666',
                              'Par': '7777',
                              'Report': '8888',
                              'Impressions': '9999'}}

dict_C = {'Content Partners Draft': {'Content Partner Payout': '1111',
                                     'Device Partner Payments': '1111',
                                     'FirstRights (FirstRights xReference)': '1111',
                                     'Sheet1 (Combined Partner Rev Share & Usage Rev Share)': '1111',
                                     'Sheet1 (Rev Share xReference)': '1111'},
          'Revenue Dashboard': {'Device Breakdown CPM and Fill Rate': '1111',
                                'Device CPM and Fill Rate Targets': '1111',
                                'Platform Breakdown CPM and Fill Rate': '1111',
                                'Platform CPM and Fill Rate Targets': '1111'},
          'Customer Lifetime Value Dashboard': {'LTV Data Source 1-9-2020 Extract': '1111'},
          'Customer Liftime Value V3': {'Customer LTV Data Source': '1111'},
          'License Tracker': {'Sheet1 (Licensing)': '1111'},
          'MONTH_END_PARTNER_REPORT': {'impressions_monthly': '1111', 'kpis_monthly_est': '1111'},
          'Par': {'impressions_monthly': '1111', 'kpis_daily_est': '1111', 'kpis_monthly_est': '1111', 'timelines': '1111'},
          'Report': {'kpis_monthly_est': '1111', 'partner_kpis_prog_hourly (public)': '1111'},
          'Impressions': {'impressions_daily': '1111', 'impressions_monthly': '1111'}}

I try to combine them with this nested dict comprehension:
combined_dict = {
    outer_key : {nested_key : nested_value
                 for nested_key in dict_B[outer_key]
                 for nested_value in dict_C[nested_key]}
    for outer_key in dict_A}

and I get this result:
{'Archives': {'Content Partners Draft': 'Sheet1 (Rev Share xReference)',
              'Customer Lifetime Value Dashboard': 'LTV Data Source 1-9-2020 '
                                                   'Extract',
              'Customer Liftime Value V3': 'Customer LTV Data Source',
              'Revenue Dashboard': 'Platform CPM and Fill Rate Targets'},
 'Content Revenue': {'Impressions': 'impressions_monthly',
                     'License Tracker': 'Sheet1 (Licensing)',
                     'MONTH_END_PARTNER_REPORT': 'kpis_monthly_est',
                     'Par': 'timelines',
                     'Report': 'partner_kpis_prog_hourly (public)'}}

The result combines the values from dict_A and dict_B successfully, but only includes one value from dict_C.  Is it possible to have a list of values (keys) as a value in a nested dictionary comprehension?
Thanks!
My expected output would include a full list of keys as the nested values:
{'Archives': {'Content Partners Draft': ['Content Partner Payout', 'Device Partner Payments', 'FirstRights (FirstRights xReference)',
                                         'Sheet1 (Combined Partner Rev Share & Usage Rev Share)', 'Sheet1 (Rev Share xReference)'],
              'Customer Lifetime Value Dashboard': ['LTV Data Source 1-9-2020 Extract'],
              'Customer Liftime Value V3': ['Customer LTV Data Source'],
              'Revenue Dashboard': ['Device Breakdown CPM and Fill Rate', 'Device CPM and Fill Rate Targets', 'Platform Breakdown CPM and Fill Rate',
                                    'Platform CPM and Fill Rate Targets']}
{'Content Revenue': {'Impressions': ['impressions_daily', 'impressions_monthly'],
                     'License Tracker': ['Sheet1 (Licensing)'],
                     'MONTH_END_PARTNER_REPORT': ['impressions_monthly', 'kpis_monthly_est'],
                     'Par': ['impressions_monthly', 'kpis_daily_est', 'kpis_monthly_est', 'timelines'],
                     'Report': ['kpis_monthly_est', 'partner_kpis_prog_hourly (public)']}}

Comment: What is your expected output?
Comment: As mentioned please specified your expected output, it is unclear what you really expect your code to do. Also a possible issue could arise from the use of double `for` in a dict comprehension, this would result in duplicate keys and therefore value overwriting.
Answer: you could use:
combined_dict = {
    outer_key: {nested_key: list(dict_C[nested_key].keys())
                for nested_key in dict_B[outer_key]}
    for outer_key in dict_A}

output:
{'Archives': {'Content Partners Draft': ['Content Partner Payout',
   'Device Partner Payments',
   'FirstRights (FirstRights xReference)',
   'Sheet1 (Combined Partner Rev Share & Usage Rev Share)',
   'Sheet1 (Rev Share xReference)'],
  'Revenue Dashboard': ['Device Breakdown CPM and Fill Rate',
   'Device CPM and Fill Rate Targets',
   'Platform Breakdown CPM and Fill Rate',
   'Platform CPM and Fill Rate Targets'],
  'Customer Lifetime Value Dashboard': ['LTV Data Source 1-9-2020 Extract'],
  'Customer Liftime Value V3': ['Customer LTV Data Source']},
 'Content Revenue': {'License Tracker': ['Sheet1 (Licensing)'],
  'MONTH_END_PARTNER_REPORT': ['impressions_monthly', 'kpis_monthly_est'],
  'Par': ['impressions_monthly',
   'kpis_daily_est',
   'kpis_monthly_est',
   'timelines'],
  'Report': ['kpis_monthly_est', 'partner_kpis_prog_hourly (public)'],
  'Impressions': ['impressions_daily', 'impressions_monthly']}}

this line for nested_value in dict_C[nested_key]} cause you to have only one key from dict_C in the final result, it sets for the same key nested_key  all the values from dict_C[nested_key], in a dict one key can have only one value


What is this called in GUI? A "panel" that contains tabs

Question: I have a feeling this answer will depend on everyone's opinions and which design spec they follow. However, maybe it will give me a broader perspective.
I have a "panel" (as best as I can describe). It so happens to contain tabs in this instance, but may not always. It sits in my sidebar, but again, should be able to sit anywhere.
It's similar to the gaming.youtube.com example attached with the suggested/comments tabs and pane.
What is this called in GUI? A panel?
I tend to think so but then I see lots of examples of panels like this which are kind of like cards:
http://foundation.zurb.com/sites/docs/v/5.5.3/components/panels.html
But is this just one example of a panel which has the fundamentals of:
"Panels are often used to section window (browser window in my case) contents to ease visual organization."
Comment: I agree that panel is the best word to name what you are describing. But I would call that specific panel in the sidebar of your screenshot a "playlist". Particularly because it has that autoplay toggle which means it will play each video one by one.
Comment: Yeah I agree with the playlist. The playlist is also only 1 tab though, the other tab is comments. So to combine both of those components into one, lets say its called "playlist-comments" you'd get playlist-comments-panel. Panel being the most important part of the name I want to get correct.
Comment: I think "panel" would be good. However I think it might be a good idea to use a more general name. Like "video-sidebar-panel". That way if you add or remove tabs later, you don't have to change the name of the panel. I would put a more specific name on each individual tab. Like "playlist-tab" or "comments-tab".
Comment: Yeah absolutely, totally agree with making it generic, was just a quick example above. Cheers!
Comment: @Rhys Just wondering in your design system/library whether you have the concept of nested panels. If so, then what's the difference between a panel and a container from your perspective?
Answer: "Tabbed panel" distinguishes it from non-tabbed panels, accordion panels, etc.
Comment: Thanks! Only thing I'm not sure about is putting tab in the name. Panel contains the tab and panes. If in the gaming.youtube they drop the comments (or in my case the need to have tabs) then I am left with tab in the component name. Having said that, if there was a specific component which handled tabs in a panel for you to pull in I can see that working. If you decided to drop the tabs in that instance, you would have to change component, rather than edit in my instance, which is fine too. My question was more referring to the "panel" part of the ui but thanks for the input!


Could a spade bit be used to widen an existing hole in a wooden cabinet?

Question: The spade bit which I have is this one.
Comment: Only if you have a way to keep it centered.  You can use a trick like sticking a wood plug in the old hole, then re-drilling.
Comment: How big is the current hole? How big do you want the enlarged hole to be?
Answer: Use a hole saw with a long pilot drill bit and clamp a board to the other side of the existing board. The long pilot drill will ensure that the saw stays centered all the way through the board that you are cutting. There is usually no way to control the spade bit to keep it centered and cut a clean hole.
Answer: https://www.youtube.com/watch?v=uGQSvkc4Ujw
Watch this video it shows a simple way to accomplish what you are trying to do.


google login GUI in windows forms

Question: I made an application that brings you to google login window, using the web browser control in windows forms, all works fine, yet I the GUI is not like how it suppose to be, the form is fixed in size, so I want to make the login window more like auto fit by itself, to know what I mean check the window that appears after clicking the button in this link: https://developers.google.com/identity/sign-in/web/build-button
Thanks in advance.
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.
Answer: I just contacted Gmail team, and they replied that this feature isn't available right now for Gmail login page

google login GUI in windows forms


Objective C memory management for anonymous objects

Question: I'm working on learning Objective-C, and I'm trying to get a feel for the memory management. I'm fairly familiar with C memory management, but I'm trying to figure out how different ObjC is.
Let's say I have a class called Complex that is used for holding complex numbers, which has a method -(Complex*)add:(Complex*)c; that adds the passed in complex number to self (Complex is a mutable object, let's say).
So I can call it this way:
Complex *c = [[Complex alloc] withReal: -3.0 andImag: -2.4]; // c = -3.0-2.4i
[c add : [[Complex alloc] withReal: 1.0 andImag: 2.0]]; // now c = -2.0-0.4i

What happens to the memory used for the temporary object created in the call to add? I assume it's a memory leak; is this the correct code?
Complex *c = [[Complex alloc] withReal: -3.0 andImag: -2.4]; // c = -3.0-2.4i
Complex *b = [[Complex alloc] withReal: 1.0 andImag: 2.0]; // b = 1+2i
[c add : b]; // now c = -2.0-0.4i
[b release];

Bonus noob question: would the Objective-C 2.0 GC deal with the situation?
Answer: In the first example:
[c add : [[Complex alloc] withReal: 1.0 andImag: 2.0]];

You have allocated object with reference count 1 and it is not released so it is memory leak because you don't store the pointer to that object so you can't send release to it.
You could modify it to autorelease the 'temporary' object:
[c add : [[[Complex alloc] withReal: 1.0 andImag: 2.0] autorelease]];

You would probably use init in the name to point out the fact that the object is not autoreleased and the user has to handle the memory management:
initWithReal:(double)r andImag:(double)i

The second example is correct.
Cocoa provides many methods (both static and member) that return autoreleased objects for example [NSString stringWithString:@"example"] so you could create methods that return autoreleased objects so you don't have to deal with releasing:
Complex * c = [Complex complexWithReal:1.0 andImag:2.0]

You could also create method that takes raw data e.g. something like addReal:(double)r andImag:(double)i so you can skip the alloc/init step.
Another option is to use structures, as used in Cocoa (CGRect and so on). They are the same as in C meaning they are allocated on stack and they disappear once they go out of scope, as opposed to allocated objects on heap with alloc/init. Good for 'small' objects that are frequently used but often you don't want to keep them around.
As to GC I don't see any reason why GC would not be able to handle releasing the object - I haven't used it much though (only looked at couple of examples - I prefer to manage memory myself - unless using python ...)
Answer: First, with my "best practices" hat on, when you create custom classes, the Objective-C idiom is to name the initializers (equivalent of "constructors" in other languages) with a leading "init". Also, try not to abbreviate parts of the method selector, or the named parameters.
For example, instead of this:
- (id) withReal:(double)r andImag:(double)i { ... }

You should consider doing this:
- (id) initWithReal:(double)real imaginary:(double)imaginary { ... }

The "and" before the second part is a matter of taste — it's perfectly acceptable to use it, but I prefer it without, since you probably wouldn't use it for methods with 3+ parameters. For example, it would more verbose than necessary if you were creating an RGB color to use -initWithRed:andGreen:andBlue: — writing/using -initWithRed:green:blue: is usually preferable.

For your actual question, I completely agree that creating a convenience class constructor is the smart way to go for situations such as these. It's visually much cleaner than alloc-init-autorelease each time you need a throwaway instance. Matching the changes above, I would tweak @kent's answer to look like this:
+ (Complex*) complexWithReal:(double)real imaginary:(double)imaginary {
    return [[Complex alloc] initWithReal:real imaginary: imaginary] autorelease];
}

For the bonus question, yes, Objective-C 2.0's GC would handle this just fine; most well-written retain-release code works as-is under GC, especially if you are careful to set pointers to nil when you no longer need them. When GC is enabled, calls to retain/release/autorelease are essentially no-ops, and objects are collected once there are no references to them. Once the last pointer to an object is lost, or goes out of local scope, the object is eligible for collection. (Technically, the GC only counts strong references, but unless you're knowingly using weak references, the distinction is probably irrelevant for now.) Just remember that garbage collection is currently NOT supported on iPhone.
Comment: Thanks for the GC tips - but it'll be a while before I have the scratch to start playing with an iPhone ;)
Comment: Sure thing. GC is great if you can use it, although it means you have to drop Tiger support, and all the frameworks you use have to support GC as well. But as time goes on, that will become more common, and who knows, perhaps as iPhones get faster, they'll start to support GC as well. :-)
Answer: stefanB is correct. since you will be doing alot of this 'on the fly' instantiation (i would assume...) it would make sense to build a static 'convenience' constructor (there are tons of examples of these in the appKit & co.)
+(Complex*) complexWithReal:(double)r andImag:(double)i
{
  return [[Complex alloc] initWithReal:r andImag:i] autorelease];
}

which would make your call to add message then look like this:
[c add : [Complex complexWithReal:2.0 andImage:1.0]]

have fun!


Windows partition recognized as unallocated space

Question: I am new to Linux.
I was trying to dual boot windows 8.1 and ubuntu when I came across this: ubuntu installer won't recognize windows as an OS and the C drive is recognized as "unallocated space" by ubuntu. How can I install Ubuntu alongside windows? I tried installing before, when windows 8 was UEFI, I now reinstalled windows 8 and it's not UEFI now, what should I do?
Comment: anyone? please, I am quite desperate getting an answer now
Comment: Have a look at [Partitions not showing while installing (K)ubuntu 14.04](http://askubuntu.com/questions/474812/partitions-not-showing-while-installing-kubuntu-14-04/474881#474881). If it does not solve your problem, then post a screenshot of the partitions in Windows Disk Management (like [this](http://i.stack.imgur.com/THo5q.jpg))
Answer: Try to resize your C partition under Windows using the built-in disk management (just use the search function of Windows 8). Then select your C drive, right-click on it and choose Shrink Volume.... You will have to enter the amount of MB you want to shrink your C drive. Note that you have to leave some free disk space for Windows. Then reboot and repeat the installation of ubuntu; now the free space will be recognized by the installation routine.


Constructing a world, in which these 2 sentences outputs a true value.

Question: Basically I've this program, in which I can create shapes like pentagon, triangle, and square. I need, to create a geometric world such that these two following statements are true:
$ ¬(∀x)(∀y)(∀z)\{ (∃t)[BackOf(x,t) ∧ BackOf(y,t) ∧ BackOf(z,t) ∧ Square(t)] → x = y ∨ x = z ∨ y = z \}; $
$(∀x)(∀y)(∀z)\{ [BackOf(x,a) ∧ BackOf(y,a) ∧ BackOf(z,a) ∧ Square(a)] → x = y ∨ x = z ∨ y = z \} $
Now a bit of an explanation:
x,y,z are variables that represent shapes in the world, while the letter a is a constant, meaning there exists a shape named a (not necessary a square - but must be a shape named a).
BackOf(x,y) is a function that returns true if x is a shape that is found behind y.
Square(x) is a function that returns true if x is a square. Now all the other predicates are well known to you guys and also the symbols of "or - V" and "derive ->".
Basically I construct this world by creating shapes and giving them the needed names (like a), I draw triangles, pentagons and squares on a table.
Now hopefully that you understood the program and my task: I'm having a difficulty creating a geometric world in which these 2 sentences receive true value since I'm almost positive they are the negation of each other.
Basically, the second statement will be able to receive false value only if the part before the derive sign:
$(∀x)(∀y)(∀z)[BackOf(x,a) ∧ BackOf(y,a) ∧ BackOf(z,a) ∧ Square(a)]$
is true, and that only happens when a itself is behind a because of the predicates "for all" before the statement and that is impossible for a shape to be behind itself, therefore the second statement is always true because false ->true/false is true (I'm pretty sure of it).
The first statement is something I've not yet understand completely and I could use some help to distinguish it.
Thanks!
Answer: The first statement says that it is not true that there cannot be three or more different objects behind any square.
The second statement says that if $a$ is a square, then there cannot be three or more different objects behind it.
OK, to satisfy this, simply make sure that $a$ is not a square, and have another object in the world that is a square, and that has at least three different object behind it.
Comment: First of all, you are brilliant, since it solved it and I've done it. Now, I still don't fully understand it, could you elaborate?
Comment: @BarVered The second statement is a universal statement with a conditional inside of it, rather than a conditional whose 'if' part is a universal. So, your analysis of this sentence was incorrect.
Comment: @BarVered The second statement says: 'If you ever have three objects behind square $a$, then at least two of those three are the same' ... Which really means: if $a$ is a square, then it cannot have three different objects behind it. But the first sentence says that 'it is not true that (if there is a square with three objects behind it, then at least two of them are the same)' ... Which means that there is a square with three distinct objects behind it.  ... But this square cannot be $a$ according to the second sentence. So: either $a$ is not a square, or $a$ does not have 3 objects behind it
Comment: So you can try this too: have 4 objects $a$, $b$, $c$, and $d$, have them all be squares, but make sure that $a$ is not in front of all the others.
Comment: ... But still have one square in front of all the others, e.g. Have square $d$ in front of squares $a$, $b$, and $c$.


Sliding Puzzle in Java, need help understanding this method

Question: I am following an online tutorial for building a Sliding Puzzle in Java on Android Studios and I need help understanding this method.
Here it is, I've never seen something like the return before. I know it is bit shifting but I have no clue how that works. Also, left is 0, right is 1, up is 2, down is 3. Thanks
public int getPossibleMoves() {
    int x = getColumnAt(handleLocation);
    int y = getRowAt(handleLocation);

    boolean left = x > 0;
    boolean right = x < width - 1;
    boolean up = y > 0;
    boolean down = y < height - 1;

    return(left ? 1 << DIRECTION_LEFT : 0) |
            (right ? 1 << DIRECTION_RIGHT : 0) |
            (up ? 1 << DIRECTION_UP : 0) |
            (down ? 1 << DIRECTION_DOWN : 0);
}

Comment: [Why is "Can someone help me?" not an actual question?](http://meta.stackoverflow.com/q/284236)
Answer: The statement in the return is called Conditional expressions.
Conditional expressions are in a completely different style, with no explicit if in the statement. The syntax is:
boolean-expression ? expression1 : expression2;

The result of this conditional expression is expression1 if boolean-expression is true; otherwise the result is expression2 .


Creating dictionary in Python using a variable

Question: Using following method to create a dictionary:
>>> dict(name = 'Joe')
{'name': 'Joe'}

What if I already had a variable name with a value 'Joe' and wanted to use it as a key in the dictionary?
Python picks the first argument and transforms it into a string.
Why it's not:
>>> dict('name' = 'Joe')
{'name': 'Joe'}

That is, why doesn't it require quotes for generating a dictionary with a string key, and treats name as a variable otherwise?
Comment: what are you trying to do?
Comment: @JohnD: actually trying to understand why the dict() accepts a string without quotes... Other methods that expect a str won't let you go away with it.
Comment: yeah `dict(2=1)` gives SyntaxError: expression cannot contain assignment, perhaps you meant "=="? So that is undefined behavior, python happens to treat it as a string but it's not something you should count on. Just do it the way my answer described and you should be fine.
Answer: When using dict(name = 'Joe'), the name is not passed as a variable but instead as a parameter to the function dict.
If you want to use a variable as a key, you can use:
name = 'joe'
dict[name] = 'joe'

which will result in a dictionary {'joe': 'joe'}
Answer: Use {} instead of dict() if you are tryna initialize a python dictionary with key-value pairs.
>>> name = 'Joe'
>>> my_dict = {name: 3}
{'Joe': 3}
>>> my_dict['name'] = 5
>>> my_dict
{'Joe': 3, 'name': 5}

will use the value of the variable name.


How do I make a deck glossy?

Question: I went to Home Depot and Sherwin Williams and I was unable to find a deck stain that looked like the shiny blondish color of the following image:

At Sherwin Williams they said that their stains were all matte.
Does anyone make glossy stains that are appropriate for decks?
Would it be appropriate to just use a matte stain and then go over it with some sort of glaze? I have a gallon of Shield-Crete which is supposed to make cement shiny. Could I use that over the top of a matte stain?
Ideally it'd be great if someone could just point me to a place online to buy a glossy blond stain like the one in the image. I've googled for a while, but nothing seems quite like that.
Comment: that's not glossy, it's matte but lit up really nicely to make it look shiny and attractive.
Comment: It's also really, really, really clean!
Comment: Cabot Gold oil based stain at Menards
Answer: The other answers not withstanding, please keep in mind that a glossy finish will probably be more slippery when it is wet (maybe even when it is still dry). This  may be why you are having a hard time finding a glossy deck finish. I think you will find that surfaces that are great for traction and safety (rougher, sandpaper like) will be the exact opposite of what you need for a great gloss finish and vise-versa.
Answer: I would suggest using outdoor polyurethane varnish.
Answer: If you're set on a glossy finish, there are a couple of things to keep in mind. One, it will require more prep and maintenance than a stain/water barrier finish (i.e. Thompson's). For a glossy finish, the wood needs to be dry, then sanded, stained (if desired) and sealed prior to the final glossy application.
For the final glossy application, the most important characteristic is a product with good UV protection. This will keep it from drying out and scaling off too fast. Even so, you'll need to do some yearly touch ups. Depending on the weather in your location, you'll get maybe 2 or 3 years out of the finish before needing to strip and re-coat. The best outdoor finish products are made for the marine industry, so you'll want to check into those. As a reference, check out http://www.pettitpaint.com/catalog_browse.asp?ictNbr=56
Comment: For a glossy finish, you don't want to use Thompson's or any other waterproofing product. Stain then coat with marine varnish. Most stains will seal so you won't need a separate sealer.
Comment: So just to be clear, I should stain the deck with a matte stain then cover that with Thompsons water seal, then go over the top of that with possibly multiple coats of marine varnish? Why do I need to use Thompsons water seal if I'm going to use marine varnish?
Answer: WE have tried SEVERAL products over the last 4 years to keep our 5 year old cedar back-deck looking new and beautiful. The neighbors cottonwood trees dump on our poor deck every year and so it's a "June Project" to re-do our deck. So, let me tell you this much from experience:

Year 1  Sun Frog: it came highly recommended and it was horrible AND what was worse is that it literally stained our deck to the extent that we could not get it sanded off. Would NEVER use again.
Year 2  Thompson's Water Seal (regular): Great product, actually! It kept the deck looking new and went on great with a cotton type roller. Why in the WORLD we switched I will never know.
Year 3  Behr Weatherproofing Wood Stain: went on nice but did NOT hold up to its reviews here in Oregon.  Rain, sun, etc. just really took their toll.
Year 4  Switching back to Thompsons!  Because, well, why WOULDN'T I?
Comment: Did any of these products give the deck the look that the OP was asking for?
Answer: The picture shows a "semi-transparent oil-based stain" over very pretty and smooth wood. Probably expensive lumber!
If the wood looks good, the semi-transparent stain will look good. Do not use any clear coats as they disintegrate under UV and you will have a nightmare on your hands.
Answer: I used CIL Home Depot product in transparent. You have to do at least two coats to get that "glass" look to it. I used the natural base and tinted it to their Aged Tan colour. We sanded with 36 and 60 grit electric floor sander as there was old dark brown stain on it previously. I washed it and allowed it to dry overnight. Product went on well. Time will tell how it stands up. It looks beautiful. Picture is of first and second coat difference.
Answer: I felt the same with my deck but I used wet look feast and watsons.  It was rubbish as it just went dull after a month so I am back on aquadeck.  It's a great product by Cabot's: not expensive and easy to apply.  I do mine twice a year. I have gotten over the shiny look you get used to matte. Its more practical as well, so try it. And if it is a quality hard wood timber it does have a nice shine to it.

How do I make a deck glossy?


How do I search a list of objects most efficiently?

Question: I have a List<T> of objects with a few fields.
How can I most efficiently search this list to find a certain object?
For now I just make a for loop which looks like this:
for(int i = 0; i < theList.Count; i++)
{
  if (theList[i].certainField == whatImLookingFor)
  {
    doSomething();
    break;//to exit for loop to prevent unnecessary processing
  }
}

Is there a more efficient way I can go about this? It's usually the same field which I am comparing it too. I thought maybe to use a dictionary but am not quite sure if I should.
Comment: This will stop at the first object you find, is this what you want?
Comment: Thanks for the comment. Yes I am always looking just for one specific object in the List.
Comment: Well then, I don't see how this could be improved by building a dictionary except if your object list is _really_ huge. I'd have gone for a `Map` if you were actually looking for several objects, but since you stop at the first one, you'd be taking more time building the dictionary than searching the way you currently do.
Comment: Since I am usually comparing the same field, I thought to make something like:
    Dictionary  theDictionary;
so then I wouldn't need a for loop, I just do
    theDictionary[whatImLookingFor]

(whatImLookingFor should always be there)
Comment: That is true, yes, but you still need to inject into this dictionary (what language is that by the way?), so it's up to you to see if it is worth it.
Comment: c#. Well the objects would be added to the dictionary once basically, but once in the the dictionary they would be accessed many times. Thoughts?
Comment: In this case, yes, creating a dictionary can help. Your choice ;)
Comment: Thanks a lot :) Just in general, my List has a Count of max 32, do you think it would be significantly more efficient instead of the for loop?
Comment: In case of a list with 32 entries it is probably not that critical except if you do look for the item many times a second... Write a simple console app to time it and find out!
Answer: This is dependent on your usage.
If you need to execute this many times and want to make execution as fast as possible, create a dictionary:
//save a dictionary somewhere
var dictionary = theList.ToDictionary(i => i.certainField);

//execution:
var item = dictionary[whatImLookingFor];
dosomething();

This comes at expense of creating the dictionary (longer initialization time) but gives a faster lookup O(1).
If you only need to do this once then keep your code as is (O(n) lookup).
Answer: theList.First(x => x.certainField.Equals(whatImLookingFor)); //already optimized

BTW You don't really know how .NET Dictionary[index] operator internally implemented (eg. loop through array or using pointer linked-list in low-level)
I would recommend reading Extensive Examination of Data Structures Using C# an in-depth analysis of .NET data structure efficiency (Array, Stack, Dictionary, List) though it writen years ago its still valid and worth looking at


Simplification of Summation for an Expected Value Problem

Question: Could Someone explain how the expression is simplified here (from 1 to 2)?
$g(x,y) = 3(1+x)y$
(1)$$E[g(X,Y)] = \sum_{k=0}^1 \sum_{l=0}^3 g(k,l)p_{X,Y}(k,l) = \sum_{k=0}^1 \sum_{l=0}^3 3(1 +k)lp_{X,Y}(k,l) $$ (2)$$=\sum_{l=0}^3 3lp_{X,Y}(0,l) + \sum_{l=0}^3 6lp_{X,Y}(0,l)$$
edit: getting rid of the external link (sorry!!)
Answer: Since $k=0$ and $k=1$, the sum becomes
$$\sum_{k=0}^1\sum_{\ell = 0}^3 3(1+k)\ell p_{X,Y}(k,\ell) = \sum_{\ell = 0}^3 \left[3 \ell p_{X,Y}(0,\ell) + 3(1+1)\ell p_{X,Y}(1,\ell)\right]$$
$$=$$
$$\sum_{\ell = 0}^3 3\ell p_{X,Y}(0,\ell) + \sum_{\ell = 0}^36\ell p_{X,Y}(1,\ell)$$
simply by using the fact that :
$$\sum(a+b) = \sum a + \sum b$$
Comment: Thank you. I think the variables confused me
Comment: No problem, if you are a begginer, summations usually scare people away ! Glad I could help.
Comment: Is there a reason I got down-voted by someone? Not upset, just want to make sure I'm following the community guidelines correctly.


arrangement of objects in circle (circular permutation)

Question: I know  circular arrangement of $n$ different objects can be done  is $(n-1)!$ ways.
For example :-
I arranged $7$ objects in circle
This can be done in $720$ ways (using $6!$)
$1$) Can I also do this problem as below  ??
I made circular arrangement of $6$ objects in $5!$ ways.
Then I selected $1$ gap out of $5$ gaps between objects to put $7$th object
$2$) If yes
then It will give answer = $5!$ $5$
=$600$ (not $720$)
my solution:-

($1$) it is possible
But gap should 6 (as there are 6 gaps if we arrange them in linear way)
($2$) we have to use different formula .
like $5!$ 6

But I am not sure
plz help
Comment: Your second version is correct: there are $6$ gaps, not $5$, so there are $6(6-1)!=6\cdot5!=6!$ ways to insert the $7$-th object into the circle of $6$ objects. This is of course the same as the original $(7-1)!$ calculation.
Comment: @BrianM.Scott, thanks for the confirmation.
Answer: Converting my comment to an answer to get this off the Unanswered list:
Your second version is correct: there are $6$ gaps, not $5$, so there are $6(6-1)!=6\cdot5!=6!$ ways to insert the $7$-th object into the circle of $6$ objects. This is of course the same as the result of the original $(7-1)!$ calculation.
Comment: @rst: You're welcome.


Get input separated by commas

Question: I need to make a program that asks the user for input (until they terminate it by typing exit). The input is separated by commas (example: value,value,value). Each separate value then needs to be put into its own variable.
Example:
If the user types in hello,15,bye, I need to put hello into the first variable, 15 into the second variable, and bye into the third variable.
Here's what I have so far:
int main(void) {
  char input[100];
  char first[100];
  char second[100];
  char third[100];

  printf("Enter commands: ");

  while(fgets(input, 100, stdin)) {
    if(strncmp("exit", input, 4) == 0) {
      exit(0);
    }

    // missing code
  }
}

How would I separate the input by the commas and add the values into their own variables?
Comment: Minor: Recommend `fgets(input, sizeof input, stdin)`.
Answer: Use sscanf() and scan sets:
if (sscanf(input, "%99[^,],%99[^,],%99[^,\n]", first, second, third) != 3)
    ...oops...

The 99's appear because the strings are defined as 100, and this ensures no overflow, though with the input line also being 100, overflow isn't a problem.
Two of the scan sets are %99[^,] which looks like a limited form of regular expression; the caret means 'negated scan set', and therefore the string matches anything except a comma.  The last is %99[^,\n] which excludes newlines as well as commas.
You can skip leading white spaces on the names by adding spaces before the conversion specifications. Trailing white spaces can't readily be avoided; if they're a problem, remove them after the conversion is successful.

Get input separated by commas


What is the best practice for an icon placeholder?

Question: I'm designing a bunch of eCommerce themes which come with a design file - the file is a low fidelity version. In the high fidelity design there are various times when icons are used, for example:

When installing the theme there will be no icon by default which works well however in the design files by default there should be an icon to indicate that they can be added.
What would be the best practice for an icon "placeholder"?
Currently i've tried the following:
Answer: Much more representative than the fixed element is the action to do.
In other words, instead of looking for a graphic element for placeholder, easier and better to recognize is insert icon or add icon here.
Anyway, in page layout applications, the placeholder is represented by the blue square with the eight transformation points:

About the action:


Can I safely use my English Xbox 360 in Slovakia?

Question: just a quick question for anybody with the knowledge. I've brought my Xbox 360 from England with me to Slovakia. Can I use it here or will it blow up if plug it in?
Answer: The Voltage in the area is Fine for the version Xbox you have.
Both are 230 volts, just verify it on the back of the power pack.
This is an UK console not a USA, correct?
If it all matches, getting an adapter will work.
Comment: I think he should also take a look at frequency expressed in Hz
Comment: If you want to be safe, the way to go is to buy a replacement power supply for your Xbox in your destination country (assuming you're going to be staying long enough to make the expense worth it) -- but if you can verify that the voltage (e.g. 230V) and frequency (e.g. 50Hz) are the same, you can just buy a replacement cord much cheaper, without having to fuss with adapters that may be flimsy and unreliable (which could be fatal to your Xbox if it's bad enough)
Comment: That said, I just looked online and both UK & Slovakia are 230V/50Hz, so a replacement cord would indeed be your best bet, and should cost less than €20, probably under €10 if you look online.
Answer: No you cannot. The outlet's they use in Slovakia are far different than the ones used in England, for this you need a travel adapter.
Here is an example of the power outlet type used in Slovakia

which is far different than the outlets we use in England. A travel adapter will be useful because you can plug in your English adapter on one end, and it will have the other side attached to (usually multiple) different outlet types depending on the country.
Comment: "my xbox 360 from England" and you give an answer talking about American consoles?
Comment: @Powerlord the answer is basically the same, but my bad. I didn't see that.
Comment: Also, you did not address whether there are other issues in consideration like region zoning or restrictions. You did not mention if voltage will be an issue: i.e. if you use an adapter you still use the same voltage and current, there is no conversion in standard travel adapter. Will the console be fried ?
Comment: @BlueTrin, question states "Can I use it here or will it blow up if plug it in?" and also this is a year old question, although it might be better if someone gave a better answer, it is best to not touch it.


How to paste two strings with quotation signs?

Question: Let's say I have two columns in a dataframe, the first shows the codes of items; whereas the second shows the description, I want to construct a third that concatenates first two columns and displays in a format such as "1" = "soap" for the first row, and so on. Is it possible? Thanks in advance
I have tried something like c(""abc"", ""def"") and different variations of that format, none worked.
Comment: We need to escape the quotation mark: `c("\"abc\"", "\"def\"")`.
Answer: We may use sprintf in Reduce.
res <- Reduce(\(x, y) sprintf('"%s"="%s"', x, y), dat[c(1, 2)])
res
# [1] "\"1\"=\"a\"" "\"2\"=\"b\"" "\"3\"=\"c\"" "\"4\"=\"d\"" "\"5\"=\"e\"" "\"6\"=\"f\""

Looks weird, but just because internal storage method is shown. See if we cat it:
cat(res)
# "1"="a" "2"="b" "3"="c" "4"="d" "5"="e" "6"="f"

Data:
dat <- data.frame(a=1:6, b=letters[1:6], x=runif(6))

Answer: transform(dat, x=sprintf('"%s"="%s"', a, b))
  a b       x
1 1 a "1"="a"
2 2 b "2"="b"
3 3 c "3"="c"
4 4 d "4"="d"
5 5 e "5"="e"
6 6 f "6"="f"

transform(dat, x = paste(shQuote(a), shQuote(b), sep='='))
  a b       x
1 1 a "1"="a"
2 2 b "2"="b"
3 3 c "3"="c"
4 4 d "4"="d"
5 5 e "5"="e"
6 6 f "6"="f"


Is it acceptable to remove some of the metal box enclosure for the electrical breakers?

Question: A contractor removed the FRONT of the metal box encasing the circuit breakers. He started building a floor to ceiling wood enclosure (plywood in front), with a cut-out to reach the breakers.  I don't know what he intended to cover the opening with. Surely the front of the metal box cannot fit there - ?
What I originally asked:  Isn't this against code?  From what I can find (not the actual code), I understand the metal enclosure is for safety (to contain sparking) and because the door must be fire rated. And I don't know where the grounding wire would otherwise go.
Now I'm understanding from the answer received that the front of the box must be put back on to meet NEC code. I also found NFPA codes - beginning at 408.30 for electrical panels.
So this enclosure thing is not going to work, right?
Comment: Yeah, we can't tell what the contractor means.  We are all thinking "*Surely he can't* be talking about *that*"!  Because *that* is so wrong that the guy cannot possibly be a licensed contractor in *any* craft.  How do the wires get to the circuit breakers?  What keeps a breaker from rocking out if someone throws the switch hard?
Comment: Thank  you all.  I will try to get a photo this afternoon.
Comment: Yeah, that's the thing. Those lugs above and below the main breaker ARE HOT AND WILL KILL YOU.
Comment: And the answer to "what keeps a breaker from rocking out when you throw it" is "absolutely nothing" ... the breaker can literally fall out.
Answer: The National Electrical Code is the reference in most of North America.  It's a reference but let's read it front-to-back anyway.
Let's skip the formalities: Cover... disclaimers... index... credits...  Article 90 is about applicability (it applies to you)... Article 100 definitions... Ah. The meat starts at Article 110..
We immediately hit all this in the first half-page.

ARTICLE 110   --  Requirements for Electrical Installations
110.2 Approval. The conductors and equipment required or permitted by this Code shall be acceptable only if approved.
110.3(B) Installation and Use.  Listed or labeled equipment shall be installed and used in accordance with any instructions included in the listing or labeling.

This item was tested by Underwriter's Laboratories (UL).  The manufacturer submitted instructions for how the equipment is to be used, and UL safety-tested it in those conditions only.  They tested it for fire safety, performance and product safety.  As such, uses beyond the instructions are illegal.
That's the answer. You cannot alter an electrical panel unless the instructions tell you to.
There's another rule that says you can't cover up electrical junction boxes, by the way -- that's another specialty of interior designers incompetent in their craft.
The real problem here
The incompetent designer is nothing but the symptom of a core problem today.
The latest fad is to eradicate all utility space.  Utility spaces are seen as dirty or undesired, as if it's shameful to admit that your house actually does run on electricity.
These utility spaces are for your house to work.  That "unsightly" unfinished basement is what makes it possible for you (via your electrician or plumber) to fix a problem in an hour instead of spending a day busting up drywall and praying you're not busting up the wrong stuff for no reason, then having to re-drywall and repaint (and the paint aged so it no longer matches, so now you have to repaint the whole room).
Paying an electrician to patch drywall is like paying a lawyer to cut hair.
I lived in old Victorians.  There, hard plumbing to the tub was an afterthought.  The Victorians didn't trust it, so they made a "hatch" for easy access to the spigot and valves (later, mixer and diverter).  The hatch is tastefully trimmed in the Victorian way.  This makes changing the entire spigot/mixer/diverter a 30 minute job.  Now, some interior designer, eager to come up with easy ways to justify his fee, would say "get rid of that useless cabinet-to-nowhere". Sure. And now changing the spigot is so hard that you can't do it prophylactically anymore as a $50 "test fix".
Were the Victorians opposed to "gussying up"?  One guess.

I gotta fever, and the only prescription is more gingerbread!
The Victorians had panache, and still respected the value of utility space. You should hire a designer who can too.
Comment: Thank you.  I will try to get photos this afternoon.  I certainly appreciate what you are saying about practicality in design!
Comment: Rereading your answer, I see that I didn't need to bother adding photos.  To meet code, the front of the box has to be reunited with the rest of the box, correct?  And it's best to leave the box as is, without any enclosure (even one with a door) hiding it?  Thanks for being patient with me.
Comment: Hold the panel cover up to the drywall. Line up the screws and mark a perimeter 1" beyond the edge of the panel cover. Remove all that drywall so the cover can lay flush on the panel proper, assuming it is intact. If it is not intact,  it will need to be replaced. They make outdoor panels.  If you can save the panel, yes, you can cover it with a tasteful door, at least I do. All panels and all junction boxes must be accessible without disassembling the house in any way.


Understanding the Htop output

Question: I am a recent user of Ubuntu. I am running some simulations in my Ubuntu 20.04 which don't run successfully. When I look at the usage, I see numbers like these.

Does this mean that my machine is using all the resources and it can't do more computation?
I see that memory is not fully used up. If it is not about the computational limit, I think the problems are coming from my simulation itself. Could someone answer this?
Answer: Yes, you are currently using all available CPU resources on 8 CPU cores.
You have available memory, but this doesn't help if your simulation is requiring CPU resources.
I would assume that the simulation has to run for as long as it takes to finish, while your computer will probably be at 100% CPU usage.
If it doesn't finish, it's probably a problem with the simulation itself, as you suggest.

Understanding the Htop output


Add number inside several Input (Type=number) after button click

Question: I have added a button to my application that adds value to input type='number' after click. Everything works fine, but numbers starts from 0 and not 1.
How can I make it so after click number starts from 1.
Here is the code and Jsfiddle code: https://jsfiddle.net/gLs374h0/
 var arr_example = [1];
  $("#btn1").click(function(){
    $.each (arr_example, function() {
      $( ".order-number" ).each(function(value) {
        $( this ).val(value);
      });
    });
  });

Sort

    <input type="number" placeholder="sort order" class='order-number'>

    <input type="number" placeholder="sort order" class='order-number'>

    <input type="number" placeholder="sort order" class='order-number'>

    <input type="number" placeholder="sort order" class='order-number'>

    <input type="number" placeholder="sort order" class='order-number'>

Comment: Please post some code which you have tried so far. So others can point you in right direction
Answer: here you have a jsfiddle
 var arr_example = [1];
  $("#btn1").click(function(){
    $.each (arr_example, function() {
      $( ".order-number" ).each(function(value) {
        $( this ).val(value+1);
      });
    });
  });

Comment: Thanks @edisoni.1337:)
Comment: If you want the numbers to start from 1 in your input types you can add min='1' property but this will change only the min number that user can change not the start value here in javascript code :) Vote up :D
Comment: Great ;) Vote up mine too hahah need that ;)


How to show confirm box like StackOverflow's confirmation box?

Question: Ask a question, and while editing the body of your question, click on some link on the page. StackOverflow's script knows that you are not finished yet, and warns you about loosing your unsaved data. However, it's confirmation box is not a jQuery plugin, or anything like that. It seems that its confirmation box is browser-specific box, something like JavaScript's confirm box. To prove it, simply check it in many browsers and you see different UI styles.
How they've done it? Which JavaScript command?
Comment: possible duplicate of [Alerts when navigating away from a web page](http://stackoverflow.com/questions/1289234/alerts-when-navigating-away-from-a-web-page)
Answer: The onbeforeunload Javascript event is what you're looking for.
Comment: His question is a duplicate, I will remove my answer when this question is closed.
Comment: @Martin I already added the short answer when James marked it as a duplicate. So I did not write the longer version, as I normally do.
Answer: Trying setting a global flag to know when the page is "editing" and then use the onbeforeunload event
window.onbeforeunload = function(){ return globalEditingFlag ? 'You are editing': null }

Answer: Look at this :
http://www.w3schools.com/js/js_popup.asp
The section about the confirm box


in asp.net MVC 2 /beta Date format issue: The value is not valid

Question: in asp.net mvc 2 or beta , model not accepting the date 13 ( more than 12'th of date) . Model showing error ads

" The value '20/10/2010' is not valid for MyDateFieldName "

what have to do? Model showing false status as ModelState=False. why?
Comment: With a question like this I wouldn't expect any updates. You need to provide much more information, show sample code, ...
Answer: By default the model binder uses the InvariantCulture to parse DateTime and invariant is mm/dd/yyyy whereas you are using the European dd/mm/yyyy format. You could override the model binder for types of DateTime to use dd/mm/yyyy though this will have internationalisation issues (though in my opinion so does the choice of Invariant Culture, I'd have made either of the xx/xx/xxxx variants invalid without explicitly turning it on). You could override the model binder to parse in based on the client's culture settings (though if you are using datepickers you have more places to worry about it). Alternatively you could have your DateTimes taken in as yyyy/mm/dd format as as far as I know yyyy/dd/mm is not recognised by any other cultures and will be universally acceptable.


Is this a bug in LLVM?

Question: I am compiling this code (using clang 3.4.2):
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>

typedef struct __entry {
    char *name;
    int value;
} entry;

int main(int argv, char **argc) {
            printf("Size of entry: %lu\n", sizeof(entry));
        entry *entry = malloc(sizeof(entry));
        printf("entry is at %lu\n", (uint64_t) entry);
}

and I receive this bitcode:
define i32 @main(i32 %argv, i8** %argc) #0 {
entry:
  %argv.addr = alloca i32, align 4
  %argc.addr = alloca i8**, align 8
  %entry1 = alloca %struct.__entry*, align 8
  store i32 %argv, i32* %argv.addr, align 4
  store i8** %argc, i8*** %argc.addr, align 8
  %call = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([20 x i8]* @.str, i32 0, i32 0), i64 16)
  %call2 = call noalias i8* @malloc(i64 8) #3
  %0 = bitcast i8* %call2 to %struct.__entry*
  store %struct.__entry* %0, %struct.__entry** %entry1, align 8
  %1 = load %struct.__entry** %entry1, align 8
  %2 = ptrtoint %struct.__entry* %1 to i64
  %call3 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([17 x i8]* @.str1, i32 0, i32 0), i64 %2)
  ret i32 0
}

The call to printf receives 16 as an argument (which I expected for a struct with two pointers on a 64-bit system). However, the call to malloc receives 8. In C, they both got the same argument. What is going on?
Comment: The bug is overloading the `entry` identifier for both a type and an object.
Comment: [using the wrong format specifier invokes undefined behavior](https://stackoverflow.com/q/16864552/995714). You need to use [`%zu` to print size_t](https://stackoverflow.com/q/940087/995714), and [`PRIu64` to print `uint64_t`](https://stackoverflow.com/q/9225567/995714)
Comment: Does the program print the right values when run?
Comment: Your code invoke undefined behavior.
Comment: `%lu` is not the correct conversion type specifier for `size_t`, nor is it correct for `uint64_t`.
Comment: "Is this a bug in LLVM?" - Without reading the rest, I assure you: it is not! You might want to think about it.
Comment: The code as written is not portable because it doesn't use `PRIu64`, but it might be using the correct conversion specifier for the platform.
Answer: The two invocations of sizeof didn't get the same argument!  It only looked like they did at first glance.
The first sizeof(entry) refers to the type name.
The second sizeof(entry) refers to the local pointer variable.
After the variable is defined, you can no longer refer to the type in the block of code.
And this means that the answer to the headline question is "No — LLVM is following the requirements of the standard".
One minor quirk: the first sizeof(entry) must have the parentheses because the argument is a type name.  The second sizeof(entry) can be written sizeof entry because this argument is the name of a variable not a type.  This allows you to confirm that the second occurrence is referring to the variable and not the type.

Is this a bug in LLVM?


Find the second highest variable in array

Question: I would like to find the second highest variable in an array.
For example if I have:
$cookies = array(
                "chocolate" => "20",
                "vanilla" => "14",
                "strawberry" => "18",
                "raspberry" => "19",
                "bluebery" => "29"
);

I can use max($cookies) to find the highest variable, which is "bluebery" => "29".
But how do I find the second highest? "chocolate" => "20"
Comment: Option one: Remove max element from array and look for maximum again. Second: Order array and take the second element.
Comment: What approaches have you tried?  A couple ideas come to mind: You could step through the array and pick out the highest two, similar to picking the highed one.  Another is that you could sort and pick the second one.
Answer: Sort it and get the second item is the easiest way:
arsort($cookies);
$keys = array_keys($cookies);

echo $keys[1]; // chocolate
echo $cookies[$keys[1]]; // 20

If you want a more efficient way, you can also do it manually, by keeping track of both the highest and second-highest items at the same time:
function secondMax($arr) {
    $max = $second = 0;
    $maxKey = $secondKey = null;

    foreach($arr as $key => $value) {
        if($value > $max) {
            $second = $max;
            $secondKey = $maxKey;
            $max = $value;
            $maxKey = $key;
        } elseif($value > $second) {
            $second = $value;
            $secondKey = $key;
        }
    }

    return array($secondKey, $second);
}

Usage:
$second = secondMax($cookies);
echo "{$second[0]} => {$second[1]}"; // chocolate => 20

Comment: Good solution, but I'm skeptic that looping yourself is more efficient than the native, compiled functions?
Comment: $secondMax Undefined for function
Comment: @HardyMathew: Thank you; fixed, probably.
Answer: For fun you could use max() twice :)
For example:

Duplicate the array
Run max()
Remove the max
Run max() again

The alternative would to sort the array based on values and get the second element of the array. I'd be curious which is faster. Likely the sort.
Answer: arsort($cookies) AND array_shift($cookies) AND list($k, $v) = each($cookies);
echo "$k => $v"; // chocolate => 20

Answer: Try :
asort($cookies);
end($cookies);
prev($cookies);
list($key,$value) = each($cookies);

or reverse it
arsort($cookies);
reset($cookies);
next($cookies);
list($key,$value) = each($cookies);

** Edit **
I thought I'd share this anyway, if someone would stumble across this and need it :
/**
 * Returns the key => value pair with the specific rank.
 * if $rank is 0, falase is returned. If $rank is positive,
 * then the $rank th smallest pair is returned. If $rank
 * is negative, then the $rank th biggest pair is returned.
 * If $rank range is outside the size of the array, false
 * is returned. If a callable function is provided, it will
 * be used to sort the data. If $keySort is true, then the
 * data will be sorted by keys instead (the callback functions
 * will receive the keys to compare instead of values)
 *
 * @param $data array
 * @param $rank int
 * @param $cmd_function callable (optional)
 * @param $keySort boolean (optional)
 * @return array            the key => value pair or false
 */
function findByRank($data, $rank, $cmd_function = null, $keySort = false) {
    if (($rank == 0) || (abs($rank) > count($data))) {
        return false;
    }
    $sort = ($keySort?'k':'a').'sort';
    if ($cmd_function != null) {
        $sort = 'u'.$sort;
        $sort($data, $cmd_function);
    } else {
        $sort($data);
    }

    if ($rank > 0) {
        reset($data);
        $next = 'next';
    } else {
        end($data);
        $next = 'prev';
        $rank = abs($rank);
    }
    while (--$rank > 0) $next($data);
    return each($data);
}

$cookies = array(
                "chocolate" => "20",
                "vanilla" => "14",
                "strawberry" => "18",
                "raspberry" => "19",
                "bluebery" => "29"
);

header('Content-type:text/plain; charset=utf-8');
var_dump(findByRank($cookies, -10));  // -> false
var_dump(findByRank($cookies, -2));   // -> 'chocolate' key=>value pair
var_dump(findByRank($cookies, -1));   // -> 'blueberry' key=>value pair
var_dump(findByRank($cookies, 0));    // -> false
var_dump(findByRank($cookies, 1));    // -> 'vanilla' key=>value pair
var_dump(findByRank($cookies, 3));    // -> 'raspberry' key=>value pair

Comment: `ksort` sorts by key. Do you mean `asort`?
Comment: oops, yes, I was thinking "sort preserving key assocations", but `asort` is the correct function, yes
Answer: rsort($cookies);
echo $cookies[1];

Comment: you can't get the keys with that, though.
Answer: Sort the array descending and take the second value. Or, to be save, take the first value and go through the array until you find a smaller one.
Answer: Check this URL
http://maheshbokkisam.blogspot.in/2013/04/find-nth-highest-value-in-array-without.html
Find  Nth/ N th highest value from given array without using any sorting in PHP

$ar  =  array(23,56,87,12,98,85,24,54,99,100,1,4,5,2,76,37,92);

$n   = count($ar) - 5;

for($i = 0; $i < $n; $i++){
    // Get the max value from array // get the Nth value from last loop
    echo $a = max($ar);

    echo "

"; print_r($ar);

    $ar = array_flip($ar);    // Flip the array
    //print_r($ar);

    unset($ar[$a]);           // Unset the max value from array
    //print_r($ar);

    $ar = array_flip($ar);    // Flip the array
    echo "
";
    echo "
";
}

Answer: function second_largest($arr)
{
    sort($arr, SORT_NUMERIC);

    return($arr[count($arr) - 2]);
}

//echo 3

echo second_largest(array(0, 3, 4, 1, 2));

Answer: <?php

 // Finding Second highest number (In case of index of array is random)
$arr = [-5 => 33, -4 => -2, 8 => 0, 44, 44, 44, 44, 44];
$max = -INF;
$secondMax = -INF;
$size = sizeof($arr);
if ($size > 1) {
    foreach ($arr as $key => $value) {
        echo "KEY-> ", $key, "VALUE->", $value, "\n";
        if ($value > $max) {
            $max = $value;
        } else {
            if ($value < $max && $value > $secondMax) {
                $secondMax = $value;
            }
        }
    }
} else if ($size == 0) {
    $max = "No Max element";
    $secondMax = "No Second highest element";
} else {
    foreach ($arr as $key => $value) {
        $max = $arr[$key];
        $secondMax = "No second highest element";
    }
}

echo "maxvalue = ", $max, "\n";
echo "secondmax =", $secondMax;


Is there any API on the browser and nodejs that can convert base64 string to utf8 string?

Question: const atob = (encodedString) => Buffer.from(encodedString, 'base64').toString('latin1')

Is there an API that can be used normally in nodejs and browsers that can help me convert base64 to utf8 string?
In node.js, we can write:
const base64ToUtf8 = (encodedString) => Buffer.from(encodedString, 'base64').toString('utf8')

I need to use this function to process base64 encoded utf8 data-uri in node.js and browser.
Comment: There are two questions here, unrelated at that.
Comment: @Kaiido I have changed my question description now.
Comment: Better, but still too broad. What do you want to do with this "utf-8 string"? There is nothing like an UTF-8 string in a browser, there are only DOMStrings (utf-16), and USVStrings (utf-16 minus surrogates). To store an utf-8 text, you'd need to store it as binary data, in an ArrayBuffer, in a Blob or in a base64 encoded DOMString. But maybe utf-16 is enough for your case and what you really want is just to read your bytes "as UTF-8 text".
Comment: @Kaiido Thank you very much, I updated my description now, I need to use this function to process base64 encoded utf8 data-uri in node.js and browser.
Answer: This node-js code reads the data encoded in this base64 string "as UTF-8". Beware it's not the same as converting "to an UTF-8 string", since JavaScript only supports UCS-2 and UTF-16 strings.
This nitpick passed, there are many methods to do the same as this code in a browser.
The cleanest is to first decode this base64 string in an ArrayBuffer and then read that ArrayBuffer as string, just like your node code:

const b64 = "wqFIb2xhIG5pw7FvcyE=";
const buf = base64ToBuf(b64);
const txt = new TextDecoder().decode(buf);
console.log(txt);

function base64ToBuf(str) {
  const binStr = atob(str);
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }
  return arr;
}

An other, shorter in code, but implying more IO is to fetch it as text:

const b64 = "wqFIb2xhIG5pw7FvcyE=";
fetch('data:text;base64,' + b64)
  .then(r => r.text())
  .then(txt => console.log(txt));

And you could also make use of the FileReader API's readAsText(), which might be useful in case you want to support more encodings than utf-8.

const b64 = "wqFIb2xhIG5pw7FvcyE=";
const blob = base64ToBlob(b64);
const reader = new FileReader();
reader.onload = e => {
  const txt = reader.result;
  console.log(txt);
};
reader.readAsText(blob, "utf8");

function base64ToBlob(str) {
  const binStr = atob(str);
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }
  return new Blob([arr]);
}

There is also the new Blob.text() that does convert to utf-8 directly, but from a base64 string, there is very little interest in going that road. Still for the curious:

const b64 = "wqFIb2xhIG5pw7FvcyE=";
const blob = base64ToBlob(b64);

blob.text().then(txt => console.log(txt));

function base64ToBlob(str) {
  const binStr = atob(str);
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }
  return new Blob([arr]);
}

Is there any API on the browser and nodejs that can convert base64 string to utf8 string？


Find $\int\frac{dx}{\cos^3x-\sin^3x}$

Question: $\int\frac{dx}{\cos^3x-\sin^3x}$

Let $I=\int\frac{dx}{\cos^3x-\sin^3x}=\int\frac{dx}{(\cos x-\sin x)(\cos^2 x+\sin^2 x+\sin x\cos x)}$
But it does not seem to be solved further by this method,so i tried another method.
$I=\int\frac{dx}{\cos^3x-\sin^3x}=\int\frac{\csc^3 xdx}{\cot^3x-1}=\int\frac{\csc^2 x \csc xdx}{\cot^3x-1}=\int\frac{\csc^2 x \sqrt{1+\cot^2x}dx}{\cot^3x-1}$
Put $\cot x=t\implies -\csc^2 x dx=dt$
$I=\int\frac{-\sqrt{1+t^2}dt}{t^3-1}=\int\frac{-\sqrt{1+t^2}dt}{(t-1)(t^2+t+1)}$
But i am stuck here.
Comment: http://math.stackexchange.com/questions/595038/calculation-of-int-frac1-sin3-x-cos3-xdx-and-int-frac1-sin5-x-c
Answer: $$\cos^3x-\sin^3x=(\cos x-\sin x)(1+\sin x\cos x)=\dfrac{(\cos x-\sin x)\{3-(\cos x-\sin x)^2\}}2$$
Writing $\cos x-\sin x=t$ and using Partial Fraction,
$$\dfrac1{t(3-t^2)}=\dfrac1{3t}+\dfrac t{3(3-t^2)}$$
$$\implies\dfrac3{\cos^3x-\sin^3x}=\dfrac1{\cos x-\sin x}+\dfrac{\cos x-\sin x}{3-(\cos x-\sin x)^2}$$
The first integral can be managed easily
For the second $$\text{as }\int(\cos x-\sin x)dx=\sin x+\cos x$$ and as $$(\cos x-\sin x)^2+(\sin x+\cos x)^2=2$$
write $$3-(\cos x-\sin x)^2=1+(\sin x+\cos x)^2$$ and replace $\sin x+\cos x$ with $u$

Find $\int\frac{dx}{\cos^3x-\sin^3x}$


How I can make a configure AWS EC2 apache server

Question: How I can make configure for an AWS EC2 apache instance server to do the flowing:
Accepts incoming POSTs from subnets 22.214.171.124/20 and 126.96.36.199/22 on port 443, 80, 88, or 8443
Comment: Can you clarify. Is this question about how to setup security groups for the instance, or it can be assumed that SGs are correctly setup?
Comment: it's public question
Answer: Attach a security group to the instance with four rules as follows (in Inbound rules section), one per port(443, 80, 88, 8443), four different rules like this for port 443
You can check more info at AWS Documentation
Comment: i did all allow all traffic it's same or not?


CSS media queries for handheld and not small browser screens

Question: In the modern days of hi-resolution handhelds, is it possible to detect handheld with CSS media queries only and not by resolution? I don't want to target iPads only like some other questions here, I want to be sure if I'm using a handheld browser or a desktop browser so the user will see mobile CSS on hi-res tablets and will not see mobile layout if he resizes the browser window. Is that possible with CSS only?
Comment: Maybe this will help you: http://stackoverflow.com/questions/14942081/detect-if-a-browser-in-a-mobile-device-ios-android-phone-tablet-is-used
Answer: You use it for example like this
<code>@media handheld and (min-width: 700px) and (orientation: landscape) { ...  }
</code>
Src: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
To be noted, unfortunately many "handheld" still doesn't pick up that type so you will have to address those individually.
Further help: Detect if a browser in a mobile device (iOS/Android phone/tablet) is used
Comment: @C0dekid.php Yeah, I know ... updated with a note and posted as a wiki as there is a good answer already.
Comment: That's the problem that many handhelds, namely Apple stuff, don't support it because it "does not supply high-end web content" whatever that was supposed to mean.
Comment: @pokrishka Why do you need to know if it is handheld? .. I strongly recommend your work on a resolution based solution.
Comment: the UX team in the project has it as a requirement that a mobile touch oriented design is shown in any handheld/tabled, no matter how big it is and desktop design is shown on desktops even when you resize the screen (scrollbars introduced).
Comment: @pokrishka The is not one answer to your question, follow the links in my answer and their links and so on .. you will see that it is quite a challenge to address "mobile touch oriented" devices ... especially with media queries only (scripting will help vastly).


C++ #define value not defined in source file

Question: I'm defining a value in my Main-file and then including a header file. The defined value isn't defined in the source file.
Main.cpp:
#define TN_VALUE double
#include "SomeFile.hpp"

int main()
{
  TN_VALUE x = 3;
  func(x);
  return 0;
}

SomeFile.hpp:
#ifndef _SOME_FILE
#define _SOME_FILE
#ifndef TN_VALUE
#define TN_VALUE float
#endif
void func(TN_VALUE); // TN_VALUE = double
#endif

SomeFile.cpp:
#include "SomeFile.hpp"
#include <iostream>

void func(TN_VALUE _value) // TN_VALUE = float
{
  std::cout << _value << std::endl;
}

Comment: It's defined in both cases. I'm not sure what exactly you are asking. Are you asking why it's `double` in one file and `float` in the other?
Comment: What makes you think it's not defined? And you have two #define statements for `TN_VALUE`, one as double and one as float. Why in the world would you do that?
Comment: This doesn't address the question, but names that begin with an underscore followed by a capital letter (`_SOME_FILE`) and names that contain two consecutive underscores are reserved for use by the implementation. Don't use them in your code.
Answer: We can investigate what the preprocessed code looks like with g++'s -E flag:

Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output.

(source)
Here is the preprocessed code for Main.cpp:
$ g++ -E Main.cpp
# 1 "Main.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "Main.cpp"

# 1 "SomeFile.hpp" 1

void func(double);
# 3 "Main.cpp" 2

int main()
{
  double x = 3;
  func(x);
  return 0;
}

And here is the preprocessed code for SomeFile.cpp, if we remove the #include <iostream>:
$ g++ -E SomeFile.cpp
# 1 "SomeFile.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "SomeFile.cpp"
# 1 "SomeFile.hpp" 1

void func(float);
# 2 "SomeFile.cpp" 2

void func(float _value)
{
  std::cout << _value << std::endl;
}

What we can see, is that in Main.cpp, TN_VALUE is double, and therefore we get void func(double); and double x = 3;. In SomeFile.cpp, TN_VALUE is float. Why is this?
This all has to do with the
#ifndef TN_VALUE
#define TN_VALUE float
#endif

in SomeFile.hpp. This tells the preprocessor that, if TN_VALUE is not defined, set TN_VALUE to float. If TN_VALUE is defined, do nothing (leave TN_VALUE with the value it has.
In Main.cpp, you have
#define TN_VALUE double
#include "SomeFile.hpp"

The order here means that TN_VALUE will be defined before the preprocessor reaches the ifndef in SomeFile.hpp, and so TN_VALUE will keep the double value.
Then in SomeFile.cpp, you immediately have #include "SomeFile.hpp". Since SomeFile.cpp is a separate translation unit from Main.cpp, TN_VALUE is not defined. That means, since TN_VALUE is not set when the preprocessor gets to the ifndef in SomeFile.hpp, the preprocessor will reach the #define TN_VALUE float line, which will cause it to set TN_VALUE to float.
More g++ -E analysis
If this was a larger and more complicated code base, we might have wanted to isolate the problem more carefully by looking just at SomeFile.hpp and the preprocessed output generated with different defines.
We can look at the preprocessed output of SomeFile.hpp with no defines:
$ g++ -E SomeFile.hpp
# 1 "SomeFile.hpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "SomeFile.hpp"

void func(float);

We can also use g++'s -D flag to make a define. If we use -D TN_VALUE=double, we should see something matching the Main.cpp case:
$ g++ -D TN_VALUE=double -E SomeFile.hpp
# 1 "SomeFile.hpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "SomeFile.hpp"

void func(double);

We already expected these results from our analysis above. However, this demonstrates that we can test what preprocessed code is generated by any C or C++ header file based on the various values of different defines.
Answer: I'm assuming your question is,
Why does TN_VALUE is double in Main.cpp and float in SomeFile.cpp.
For that question, this is the explanation,
In C++, when you include a header file, it's content gets copied to the source file. Which means that there will be one copy of the SomeFile.hpp file in Main.cpp file and another copy in the SomeFile.cpp file. So now when the compiler runs through the source file, in one file the definition of TN_VALUE is float (in SomeFile.cpp) and its value is double (because you have defined it explicitly) in the other file (Main.cpp).
This means that there will be two different (overloaded) functions. One is void func(float) and the other is void func(double).
Since the function definition is present in the SomeFile.cpp file, it'll compile without an issue, but the Main.cpp file will have an issue because the compiler says that there's a function with the signature of void func(double) which the linker cannot find (because a function like that is not compiled). This will trigger a link error.
To resolve this issue, you can define the function in the header file itself and ditch the SomeFile.cpp file altogether. This way the function definition will be placed in the Main.cpp file and the definition of the TN_VALUE will resolve to double. No linking errors will arise from this function after that.


VBA: add char to a column and resize the range

Question: I am writing a macro to hopefully copy the values in cells A1,A2, A3, A4, A5, A6...to columns C1, D1, E1, C2, D2,E2...respectively.
I also want to add characters before and after each copied cell.
This is what I currently got after reading
How to add text to the beginning or end of all cells in Excel? and some other websites.
Sub reformat()
Dim c As Range
dim destination As Range
Set destination=Range("C1")
Set destination=destination.Resize(3,33)
For Each c In Selection
If c.Value<>" " Then destination.Value="beginning"&c.Value&"ending"
Next
End Sub

This gives the following error message run-time error'91':object variable or with block variable not set for line If c.Value<>" " Then.  My biggest problem is figuring out how to copy values to the specified area which has more columns.

Update:
Thanks to Stefan's advise, I have changed my code to the following:
Sub reformat()
Dim c As Range
dim destination As Range
Set destination=Range("C1")
destination=destination.Resize(3,33)
For Each c In Selection
If c.Value<>" " Then destination.Value="beginning"&c.Value&"ending"
Next
End Sub

Now the old problem no longer appears but only cell C1 is filled.
Comment: I can't replicate this.  What line is throwing the error?
Comment: Your destination does not change. Consider using `destination.offset(rowindex).value=something` then increment `rowindex`
Comment: The error comes for `If c.Value<>" "` @Comintern
Answer: In
Set destination=Range("C1")
Set destination=destination.Resize(3,33)

you should should only use set one time to initialize the destination object.
I guess you should just say
destination.resize(3,33)

Edit
Dim c As Range
dim destination As Range
Set destination=Range("C1")
destination.Resize(3,33)
I=0
For Each c In Selection
   If c.Value<>"" Then
      destination.offset(i).Value="beginning"&c.Value&"ending"
   Endif
   I=i+1
Next
End Sub

Comment: Thanks a lot. I changed but there is still same error message for  line`If c.Value<>" "`
Comment: Did you select A1 to A6 before running the macro? You could replace `Selection` with `Range("A1:A6")` if it's always this range.
Comment: Also, you probably should remove the space in `if c.value<>" "`
Comment: Yes, I selected. I fixed a typo and now the previous error message no longer appears, but the problem is that only cell C1 is filled
Comment: See my comment  to your question, about `.offset`
Answer: This code will copy the selected values into a 3-column matrix, upper left corner in [M1]:
Sub reformat()
' copy cell values from selection into 3-column wide destination
' http://stackoverflow.com/questions/34473802/vba-add-char-to-a-column-and-resize-the-range#34473802
' 2015-12-26
    Dim c As Range, destination As Range
    Dim ct As Long

    ct = Selection.Cells.Count
    Set destination = Range("M1").Resize(CInt((ct + 1) / 3), 3)
    ct = 0
    For Each c In Selection
        If c.Value <> "" Then
            destination(CInt(ct \ 3) + 1, (ct Mod 3) + 1).Value = "beginning" & c.Value & "ending"
            ct = ct + 1
        End If
    Next
End Sub

Answer:     Dim c As Range
    Dim destination As Range
    Set destination = Range("C1")

    i = 0
    For Each c In Selection
       If c.Value <> " " Then
          destination.Offset(i \ 3, i Mod 3).Value = "beginning" & c.Value & "ending"
       End If
       i = i + 1

Next


withFilter Implementation while writing custom monad in scala

Question: I am not able to implement monad to compose function. It throws error in for comprehension that "value withFilter is not a member of MonadFunctionComposition.Writer"
object MonadFunctionComposition extends App {

  case class Writer(value1: Int, value2: Int, logs: String) {

    def map(x : (Int, Int) => Int): Writer = {
      Writer( x(value1, value2), x(value1, value2), logs)
    }

    def flatMap(x: (Int, Int) => Writer): Writer = {
      val temp = x(value1, value2)
      val temp1 = x(value2, value2)
      Writer(temp.value1, temp1.value2, logs + "..." + temp.logs)
    }
  }

  val f: (Int, Int) => Writer = (value1, value2) => {
    Writer(value1 + 57, value2 - 2, s"execute function f with $value1 $value2 value.")
  }

  val g: (Int, Int) => Writer = (value1, value2) => {
    Writer(value1 + 10, value2 - 1, s"execute function g with $value1 $value2 value.")
  }

  val result = for
  {
    (a,x) <- g(5, 100)
    b <- f(a,x)
  } yield b

 // val result = g(5, 100).flatMap((a,b) => f(a, b))
  println(s"Result $result")

}

Comment: using custom monads in `for comprehension` requires withFilter funciton implementation signature: `def withFilter(p: T => Boolean): Writer[T]` . Try to add function to your monad.
Comment: @BorisAzanov what should be the implementation of withFilter?
Comment: @abhi essential this is form of lazy `filter` - like you are applying filter, which will take action later during terminal operations. In case of for instance `List` - methods like toString, fold, etc.
Comment: @IvanKurchenko what should be the implementation of withFilter? I am not able to execute the code.
Comment: @IvanKurchenko It depends on you Monad implementation.  In general: if value inside monad does not satisfy predicate you should fallback into `error` or `empty` value. Btw, looking at your code - it's not really a monad, it is just a class which implements methods used by `for-comprehension`.
Comment: @IvanKurchenko Is not writer a Monad? If not could you please explain why? Also in the above code what should be the implementation of withFilter to run the code?
Answer: Don't think that it's possible to have a useful withFilter implementation in this case.
Your Writer is not a monad.
First, to be a monad it has to be generic (Writer[T]).
Second, map and flatMap must have proper signatures:
def map[B](f: T => B): Writer[B]
def flatMap[B](f: T => Writer[B]): Writer[B]

It's surprising that the compiler doesn't throw an error in your case.
And then you may think of adding withFilter method:
def withFilter(p: T => Boolean): Writer[T]
But what should it do?
There is of course a trivial implementation that just does nothing and returns this.
Also it's possible to discard the log if p(this) is false but it's not what people expect.
Ability to do filtering on a monadic value is encoded in MonadPlus typeclass. And neither Scalaz/Cats nor Haskell implements MonadPlus for Writer.
Comment: Then how to compose function f and g using for comprehension in the above-mentioned case?
Comment: You may add to this answer that if you add the [**bm4** compiler plugin](https://github.com/oleg-py/better-monadic-for) then that code would compile without needing to implement stupid `withFilter`.
Comment: @LuisMiguelMejíaSuárez seems I got the question wrong. I thought that OP actually wants to use `if` inside `for`
Comment: Pattern matching on values got from `<-` also uses `.withFilter` unless you use better-monadic-for.


Img in  don't show

Question: Image in my
 doesn't show under the writing, it appear only the writing but not the image, I've tried many ways but ther was unsuceesful.
Someone can help me?
I've tried change class in id, manually resize img, change the css code, change name:

.img-header {
 height: 100vh;
 min-height: 500px;
 background-image: url('img/header.jpg');
 background-size: cover;
 background-position: center;
 background-repeat: no-repeat;
}

My Site

Welcome to My site!

The image from div should appear under the writing "My site - Welcome to my site".
Comment: make sure you have specified the right path: `background-image: url('img/header.jpg');`
Comment: or `~/img/header.jpg` will go to the root directory of your solution
Comment: i've specified the right path, i've tried too with a hosted img but the result is the same
Comment: write z-index:1; in your css code then try.
Comment: You're not using Ad-block or anything like that?
Comment: seems like you might not be getting the path right to your img is all, try `../img/header.jpg` to go up one directory. You do have an img folder in your solution, yes?
Answer: Try this background-image: url('/img/header.jpg');
instead of background-image: url('img/header.jpg');
Always provide appropriate path.
Answer: Check if your .css file is correctly linked.
Use browser developer tools to inspect the div and verify if the image is reachable.

Img in  don't show


Spectral Sequence involving "Triple Tor"

Question: Can someone help me with the first 4 lines of Page 111 of Local Algebra by Serre?

I would like to know which spectral sequence is being used.

Initially I thought it is the Grothendieck spectral sequence, but I don't think that is the case, and I don't know what a "Triple Tor" is. Any help would be appreciated. Thank you.
Answer: Basically he's computing the homology of the complex $M \otimes^{\mathbb{L}}N \otimes^{\mathbb{L}} k$ (where tensors are taken over $A$). Associativity of the tensor product tells us that
$$
(M\otimes^{\mathbb{L}}N) \otimes^{\mathbb{L}} k = M \otimes^{\mathbb{L}}(N \otimes^{\mathbb{L}} k)
$$
And so we get two different spectral sequences...
$$
\operatorname{Tor}_p(\operatorname{Tor}_q(M, N), k) \Rightarrow \operatorname{Tor}_{p+q}(M, N, k)
$$
$$
\operatorname{Tor}_p(M, \operatorname{Tor}_q(N,k)) \Rightarrow \operatorname{Tor}_{p+q}(M, N, k)
$$
which you can think of in many different ways. One comes from the spectral sequence associated to a double complex. That is, in general if we have complexes $A_*$ and $B_*$ and we want to compute $H_*(A_* \otimes^{\mathbb{L}} B_*)$ (this is sometimes called "hypertor" but that makes it sound scarier than it is...) then we can choose Cartan-Eilenberg resolutions $P \rightarrow A$ and $Q \rightarrow B$, and consider the spectral sequence of the double complex $P \otimes Q$. This gives:
$$
H_*(H_*(A) \otimes^{\mathbb{L}} H_*(B)) \Rightarrow H_*(A \otimes^{\mathbb{L}} B)
$$
which specializes to the aforementioned spectral sequences in your example.
Comment: @Dylan Thanks, yes you are right, I finally got it.
Comment: Do you know if we have a spectral sequence involving Ext. Something similar to above where all the Tor is replaced by Ext? Thanks
Comment: I mean if we have something like "Triple Ext"?
Comment: @messi: If you can say what you mean by "triple Hom" then that should tell you what to do with "triple Ext"


React how to add custom js file web application

Question: Styles and  Js file how to add in react ,
I developed a template using  html css js ,
now i want to switch all to react ,
i have assets files and how i will change to react .
Answer: You can include react to html file by  including

And you can include your components to the app using

The css you can link easily the only difference is, instead of keyword "class" on tags you should use "classname"
You can refer the react documentation https://reactjs.org/docs/add-react-to-a-website.html#add-react-in-one-minute


Embedded WLST minimal file set

Question: I'm using Eclipse to write a small Java application that uses WLST to manage a few development servers.  I want to be able to give this application to our developers who do not have Weblogic installed.  We are using Weblogic version 9.2.
When I add weblogic.jar to the classpath (but leave it in my WEBLOGIC_HOME tree) it works fine.  When I move the weblogic.jar to my projects /lib directory I get a failure when it tries to connect to node manager.
It is pretty clear that code in the weblogic jar is using hard coded relative paths to find other files.
Does anyone know the complete minimal set of files WLST needs to work?
Answer:
config.jar

jsafe.jar

jython.jar

pdev.jar

weblogic.jar

wlcipher.jar
DemoTrust.jks needs to be on the class path.

Embedded WLST minimal file set


jQuery: print_r() display equivalent?

Question:
Possible Duplicate:
JavaScript data formatting/pretty printer

I am getting a bit tired of looking at unformatted json blobs in FireBug.
Does anyone know an equivalent to PHP's print_r() for jQuery?
Something that would recursively make a display string from an object or array, that I could display on the page for quick debugging?
Thanks!
Answer: console.log is what I most often use when debugging.
I was able to find this jQuery extension though.
Comment: @the0ther console.log can take multiple arguments, so if you want to tack a string at the beginning, use `console.log(string, object);` (notice the comma). This way you get your string and the object is correctly shown too.
Comment: This is perfect.  I've been using console.log, but didn't realize I could pass it an object. Durr...
Comment: Durr indeed. I didn't really figure this out until now, because I always tack on a string at the beginning of my console.log() and so everytime i just get the string representation [Object object]. I tried console.log(myObj) and it's much better now.
Comment: Also, console.dir is best for objects :)
Comment: The link for the jQuery extension is broken.
Comment: freaking great it works on webkit as well! :)
Comment: Love console.log, however console.log is sadly not available in Titanium. I need a solid print_r() function.
Comment: Yes! why did i not know about this earlier... THX!
Answer: You could use very easily reflection to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;

alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"

But since you use Firebug, why not just use console.log?
Answer: How about something like:

function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'
').replace(/\t/g,'   '); }

Comment: a pretty good reply actually if someone hates console.log :)
Answer: You can also do
console.log("a = %o, b = %o", a, b);

where a and b are objects.
Answer: I've made a jQuery plugin for the equivalent of

<?php echo print_r($data) ?>

You can download it at https://github.com/tomasvanrijsse/jQuery.dump
Comment: I modified your code: Your code output need to attach to a div. But with this function I can able to display to on console both string and object.                                                            function print(variable) {
    if(typeof variable == 'object') {
        $.each(variable, function(key, element) {
            console.log('' + key + ' => ' + element+"");
        });
    }
    else {
        console.log('' + variable +"");
    }
}
Comment: Could you send a pull request on https://github.com/tomasvanrijsse/jQuery.dump
Comment: I sent pull request. :-)
Answer: $.each(myobject, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

This does the work for me. :)
Comment: Because sometimes you need to output the results on the page. I created a function which outputted the array and called itself if it detected the child value is another array.
Comment: This won't work with multi-dimensional objects.
Comment: Hmm that might be true, but why don't you use console.log for complex arrays / objects?
Comment: If you still want to do this (assuming that you really need this for coding, rather than debugging), you might need nested foreach statements, which can really be complex at certain times :P
Answer: Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().
Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:

In the console you can see the url of
the AJAX response.
Click the triangle to expand the response and see details.
Click the JSON tab in the details.
You will see the response data organized with expansion triangles.

This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).
For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.
Answer: Look at this: http://phpjs.org/functions/index and find for print_r or use console.log() with firebug.

jQuery: print_r() display equivalent?


How to update the values of a dictionary with a condition?

Question: Supposing I have a dictionary,
 {'A1':[3, 2, 1],
 'A2': [9, 10, 11, 12, 13, 14],
 'B1': [4, 5, 6, 7, 8],
 'B2': [15]}

If I choose a number say 9, I want to update the values of all other keys, except A2 (since 9 belongs to key A2), with 'After' + the last element of the key where the value was found, in this case 14.
EDIT:
Another condition, when parsing through the dictionary if a given value is smaller than 9 we do not change its value.
Final dictionary,
 {'A1':[3, 2, 1],
 'A2': [9, 10, 11, 12, 13, 14],
 'B1': [4, 5, 6, 7, 8],
 'B2': ['After 14']}

Answer: Suppose your dictionary is dct, try a dictionary comprhension:
x = next(v[-1] for k, v in dct.items() if 9 in v)
>>> {k: v if (9 in v) or all(x < 9 for x in v) else [f'After {x}'] for k, v in dct.items()}

{'A1': [3, 2, 1], 'A2': [9, 10, 11, 12, 13, 14],
 'B1': [4, 5, 6, 7, 8], 'B2': ['After 14']}

Note this works for any value, not just 14.
Comment: thanks for your answer. I just realized there's another condition which I forgot to add. Please see the edited question.
Comment: @royalewithcheese Edited my answer with working code
Comment: @royalewithcheese Check out my edit :)
Answer: IIUC, assuming mutually exclusive values (i.e. values do not overlap):
n = 9
key, (*_, last)  = next((k, v) for k, v in d.items() if n in v)

{k: [f"After {last}"] if k != key else v for k, v in d.items()}

Output:
{'A1': ['After 14'],
 'A2': [9, 10, 11, 12, 13, 14],
 'B1': ['After 14'],
 'B2': ['After 14']}

Comment: thanks for your answer. I just realized there's another condition which I forgot to add. Please see the edited question.
Note: Yes, the values do not overlap.
Answer: If the dictionary is defined as d, then
d['A1'] = item

will change the item assigned at 'A1'.
If you want automated algorithm then you can use:
for key in d:
    d[key] = item


jquery image/description replacement with fade

Question: I am simply(for you, not me) trying to add image fading to the following code kindly provided by www.webdesignerwall.com.
$(document).ready(function(){
     $("h2").append('')
     $(".thumbs a").click(function(){
       var largePath = $(this).attr("href");
       var largeAlt = $(this).attr("title");
       $("#largeImg").attr({ src: largePath, alt: largeAlt });
       $("h2 em").html(" (" + largeAlt + ")"); return false;
     });
});

I have so far lost a lot of sleep/hair attempting to tie in a fading function from other code.
And from that other code, I have been unable to find anything that also has the .append function like this one has.
I know this is childs play for most of you Jquery/javascript professionals. Unfortunately, the webdev gods were not as kind to me.
Any help would be greatly appreciated.
Answer: $(document).ready(function(){
     $("h2").append('')
     $(".thumbs a").click(function(){
       var largePath = $(this).attr("href");
       var largeAlt = $(this).attr("title");
       $("h2 em").hide();
       $("#largeImg").load(function(){
            $(this).fadeIn();
            $("h2 em").html(" (" + largeAlt + ")").fadeIn();
       }).attr({ src: largePath, alt: largeAlt }).hide();
        return false;
     });
});

Comment: it will fadein AFTER the image is loaded... if you can ignore that and want it DIRECTLY to fade in, write a comment...
Comment: oc california? :D i only know, that this is a tv-series :D
;) i'm from germany, but i'll tell you, if i *EVER* will be there ;) thanx!


Protocol function sends the value back to the first VC but does not set it to the variables

Question: I am learning IOS, and I have three view controllers A, B and C, and I can access C from B and B from A, then I send back data using this delegate method from C to A then I want to use these received data in A, and finally update the text in the textView of VC A, but it always updates the textView using the default values not the received ones.
class A
protocol isAbleToReceiveData{
    func pass(book: String, chapter: Int)
}

class AViewController: UIViewController, isAbleToReceiveData{

    var verses: [DBTVerse] = []
    var text: String = ""
    var currentBook: String = "Test"
    var currentChapter: Int = 1

    @IBOutlet weak var TextView: UITextView!

    func pass(book: String, chapter: Int) {
        self.currentBook = book
        self.currentChapter = chapter
        print(currentBook, currentChapter)
        // current output is ok "the received data"
        }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

        getVerses(book: self.currentBook, Chapter: NSNumber(value: self.currentChapter))

        print(currentBook, currentChapter)
        // current output "test" "1" while it should be the received data
    }

    func data(verses: [DBTVerse]) {
        for verse in verses{
            if let chapter: Int = verse.verseId?.intValue{
            text.append(String(chapter))
            text.append(verse.verseText)
            }
        }
        updateData(text: text)
    }

    func updateData(text: String){
        if let textView = self.versesTextView {
        textView.text = text
        textView.setNeedsDisplay()
        }
    }

    func getVerses(book: String, Chapter: NSNumber) {
        DBT.getTextVerse(withDamId: "ARBWTCO1ET", book: book, chapter: Chapter, verseStart: nil, verseEnd: nil, success: { (verse) in
            if let verse = verse {
                    self.verses = verse as! [DBTVerse]
                    self.data(verses: self.verses)
            }
        }) { (error) in
            if let error = error {
                print("Error \(error)")
            }
        }
    }
}

class C
class CTableViewController: UITableViewController {

    var currentBook: String = ""
    var chapters: [DBTChapter] = []
    var AVC = AViewController()
    var delegate: isAbleToReceiveData?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = AVC
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let selectedChapter = Int(chapters[indexPath.row].chapterId) {
            doDismiss(book: currentBook, chapter: selectedChapter)
        }
    }

    func doDismiss(book: String, chapter: Int) {
        if let delegate = self.delegate{
            delegate.pass(book: book, chapter: chapter)
        }
        // Use presentingViewController twice to go back two levels and call
        // dismissViewController to dismiss both viewControllers.
        self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
    }

So in general A receives the data but it does not override it to the variable so I can use it later or in the viewWillAppear.
Comment: how are you presnet those viewcontroller, your navigation flow, i guess from a you us do a present or a segue to nextViewController and set the delagate what i saw in you code you create an instance of a class to be the delegate and thats wrong
Answer: You have to tell to next Viewcontroller who is it delegate like so if you are in A VC ande B goes trhow a segue then add in A viewController
class AViewController: UIViewController, isAbleToReceiveData{
   //all class details
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToClassB"{
        let vc = segue.destination as! bViewController
        vc.delegate = self
    }
}

in class B then you have a new property like c with
class b: UIVIewcontroller{
var delegate: isAbleToReceiveData?

So in the func to segue to next viewController c VC add this func
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToClassC"{
        let vc = segue.destination as! CTableViewController
        vc.delegate = self.delegate
    }
}

Comment: Oh many thanks!, I have tried this before too but in Class B I made it vc.delegate = self as? isAbleToReceiveData instead of what you did, and I guess this was the problem, thank you very much.
Comment: No problem man, some time is not clear how delegates work when and that kind of problems happens


Rewriting second order DE as first-order system in "normal form"

Question: I have the following problem: "Rewrite the given scalar equation as a first-order system in normal form. Express the system in the matrix form $x'=Ax+f$, Let $x_1(t)=y(t)$ and $x_2(t)=y'(t)$
$y''(t)-8y'(t)-5y(t)=tan(t)$"
However, I'm not sure what a "system in normal form" is. I don't see it in the online textbook when I ctrl+f it...
Answer: Hint
you have $x_1=y$ then $\dot x_1=y'=x_2 $
$$\implies \dot x_1=\color{red}{0x_1}+\color{blue}{1x_2}$$
You also have $y''= \dot x_2 =8y'+5y+ \tan(t)=8x_2+5x_1 +\tan(t)$
$$ \implies \dot x_2=\color{blue}{5x_1}+\color{blue}{8x_2}+\tan(t)$$
Therefore
$$\pmatrix { \dot x_1 \\ \dot x_2}=\pmatrix {0 & 1 \\ 5 & 8}\pmatrix{ x_1 \\x_2}+ \pmatrix {0 \\ \tan(t)}$$
$$\dot x=Ax+f$$