WPF Expand a grid outside an expander

Question: I have a status bar with an expander in it, and a grid with some content. How can I have the expander expand the grid, without nesting it in the status bar, and therefor effecting all other status bar items when its expanded?
<code>    <StatusBar>
       //Other status items
       <Expander ExpandDirection="Up" Header="Operations" />
       //Other status items
    </StatusBar>

    <Grid Name="the_grid" DockPanel.Dock="Bottom">
      //Content
    </Grid>
</code>
Comment: Use a `Popup` control.
Comment: Can you expand on that? Its not a listed type in the toolbox.
Comment: A `Popup` will be displayed above the window, so it will not resize your grid. See [here](http://www.blackwasp.co.uk/WPFPopup.aspx) for a tutorial.
Comment: That does not move and stay in the window of the application properly.
Answer: You basically want something simmilar to ComboBox funcionality. Look at ComboBox control template. Combobox uses a popup control to show items on top of other items and basicaly outside the combobox position.
You can edit Expander's control template and use similar approach there.
If you don't want to spend too much time with that, you can use small trick:
<code>    <StatusBar>
        <StatusBarItem Content="Item 1" />
        <StatusBarItem Content="Item2" Margin="20,0" />

        <Menu BorderThickness="0">
            <MenuItem Header="Item 3 (expandable)" Foreground="{StaticResource Accent}" BorderThickness="0" Background="#333">
                <MenuItem Header="Item 3.1" BorderThickness="0" />
                <MenuItem Header="Item 3.2" BorderThickness="0" />
            </MenuItem>
        </Menu>
    </StatusBar>
</code>

WPF Expand a grid outside an expander


anchor jumping by using javascript

Question: I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.
I have two problems regarding anchors.
The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.
So the structure of the anchors is:

One

Two

Three

    text 1
    text 2
    text 3

Okay, if you will click one of the links the url will automatically change to

www.domain.com/page#1

At the end this should be just:

www.domain.com/page

So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.
I have found this function:
function jumpto(anchor){
    window.location.href = "#"+anchor;
}

and calling that function with:
One

what will be the same like before. It will add the hash to the url. I also added

without success. So if there is someone who could tell me how to solve this I really would appreciate.
Thanks a lot.
Comment: In that case you will either have to manipulate the scrollTop of the window, typically by `window.scrollTo` or the corresponding jQuery helper: http://stackoverflow.com/questions/6677035/jquery-scroll-to-element or http://stackoverflow.com/questions/500336/how-to-scroll-to-an-element-in-jquery
Comment: Do not do that, please. Hashes are good when saving the page in your bookmarks.
Comment: Not sure about this, but you could try manually writing to the hash property after the jump. For example set a timeout in the onclick handler which sets `window.location.hash=''`.
Comment: Do you mean you don't want to have the # shown in the URL when jumping to another section in the same webpage?
Comment: @Jeff - If you do `location.hash=''`, the `#` remains there.
Comment: Perhaps worth noting that the name attribute of anchor tags is deprecated.  You should use id instead.
Answer: You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = "#"+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
}

This uses replaceState to manipulate  the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView:
document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. It's not complicated at all.)
Comment: "Even IE6 supports this" is the best comment I've ever seen.
Comment: 1+ for `scrollIntoView`. 1- for mentioning it last.
Comment: @Black There are no such thing as a "jQuery" element. If you want to get the first element out from your query, do `$(mySelector)[0].scrollIntoView()`.
Comment: Rats!! The link is broken :-(   I thought that JS Fiddles stayed there forever
Comment: @Mawg Apparently they have removed the ability to use add `/show` at the end of the url.
Comment: I think the "complicated" way is even easier than the simple way. I prefer the scrolling than tag
Comment: @Black I'm not sure what you mean by "hidden elements" either. All elements in your DOM subclass from `HTMLElement` which definitely contains the `.scrollIntoView` method.
Comment: @Derek朕會功夫 do you have a case of Mondays? (profile picture from Office Space movie)
Comment: @JuanMendez Yes :)
Comment: .scrollIntoView does not seem to work with a Jquery Element.
Comment: @Derek朕會功夫, I mean elements which have the attribute `hidden`. e.g. ``
Comment: @Black You might want to redesign your page if you need to jump to a hidden element.
Comment: @Derek朕會功夫, what are the reasons why this is bad?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172769/discussion-between-derek--and-black).
Comment: I find the "window.scrollTo(0, element.offsetTop)" method the best as it works perfectly with windows not on full screen (unlike scrollIntoView()). Also, this function alignes the element to the very top of the screen, making it easier to spot the change.
Comment: I couldn't make this to work. For some reason in my system / case document.getElementById(h).offsetTop return wrong values all the time. So I went the Jquery way: window.scrollTo(0, $("#elem").offset());
Answer: I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"

This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
Comment: I ended up with `window.location = window.location.origin + window.location.pathname + '#hash';`
Comment: And what rarely works on IE ,this works on all IE ;)
Comment: This reloaded the page for me.  Accepted answer ended up working, though, I wish it was shorter.
Comment: This is the Best way !!
Comment: @Alex Isn't that missing the protocol?
Answer: I don't have enough rep for a comment.
The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).
Something to bear in mind if you don't have control of the document markup (e.g. webextension).
The location based method in the selected answer can also be simplified with location.replace:
function jump(hash) { location.replace("#" + hash) }

Answer: Because when you do
window.location.href = "#"+anchor;

You load a new page, you can do:
One

Comment: It doesn't reload the page.
Comment: I don't think adding hashes makes it a new page.
Comment: You're right it doesn't reload page. I try in console with chrome and the favicon is reloaded.
Comment: In the latest Firefox, hash changes seem to force a reload for iFrames (in the src attribute). I'd consider this a browser bug, but something to be aware of.
Answer: I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page.  It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>

Hello

On the .js file I have
function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
Test link

which on click will send to the anchor.  For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces.  ☺
Answer: This is the simplest solution I've found to this that is also pretty robust:
window.location.href = window.location.href.split("#")[0] + "#your-anchor";

This:

Doesn't strip the anchor from the URL unlike scrollToView (better for  shareability/UX and useful for analytics)
Works no matter how many hashes are currently in the URL - whether 0, 1 or 20 - so won't fail if clicked more than once
Doesn't reload the page
Answer: The first suggested solution of accepted solution did not work for me entirely. The main problem was when it was already jumped to hash, and hash already in url, jump did not happen again. I propose here, for the sake of completeness, somewhat more elaborate solution which works (tested in Chrome and FF). el is element with anchor tag.
        el.addEventListener('click', function(ev) {
            ev.preventDefault();
            const href = ev.target.getAttribute('href');
            const hashIndex = href.indexOf('#');
            if (hashIndex !== -1) {
                const hashPart = href.substring(hashIndex);
                if (location.hash === hashPart) {
                    document.querySelector(hashPart).scrollIntoView();
                }
                else {
                    location.hash = hashPart;
                }
            }
        })

anchor jumping by using javascript


Query mysql with hard concatenament

Question: i need to help from you, this is my problem:
I have 2 table
Friends
----------------------------------------
friends_club_1 | friends_club_2 | state
1234                 4321          1
2345                 1234          1
1234                 4567          1
4569                 1567          1

  User Info
  -----------------------------------------------
    id  |    name    |    surname     |    age   |
   2345     Jhonny         Jenny           24
   4567     Linda          Minda           23
   1567     Stefan         Refan           25
   1234     me             me              23
   4569     dani           mari            28
   4321     Star           Gate            24

I would like have the follow result:
Result
-----------------------------------------------------
my_friends   | state |  name  | surname | age

4321           1        Star       Gate    24
2345           1        Jhonny    Jenny    24
4567           1        Linda     Minda    23
1567           1        Stefan    Refan    25

ecc....

I would like have this result knowing the me id 1234
I hope one help thank you so much
Comment: According to your desired result `Stefan` should be in the result but in your example tables he is not friends with `me`. Is this a mistake or are you trying to get friends and friends of friends?
Answer: I'm guessing something like
SELECT UserInfo.*
FROM UserInfo
LEFT JOIN Friends ON (UserInfo.id IN (friends_club1, friends_club2))
WHERE UserInfo.id = 1234

?
Answer: Here you go
SELECT u.id AS my_friends  ,u.state,  u.name,  u.surname , u.age FROM user_info u
INNER JOIN friends f1(u.id = f1.friends_club_1)
INNER JOIN friends f2(u.id = f2.friends_club_2)
WHERE f1.friends_club_1=1234 OR  f2.friends_club_2=1234

OR by subquery you can do it like
SELECT u.id AS my_friends  ,u.state,  u.name,  u.surname , u.age FROM user_info u
WHERE u.id IN(SELECT friends_club_1 FROM friends WHERE friends_club_2=1234) OR
u.id IN(SELECT friends_club_2 FROM friends WHERE friends_club_1=1234)

Hope it makes sense

Note: Don't use the spaces in the column names and the table name
Answer: You can use a JOIN to link the tables together combined with a UNION to handle both cases of friends.
SELECT uf.*, f.state
FROM User_Info u
INNER JOIN Friends f
  ON f.friends_club_1 = u.id
INNER JOIN User_Info uf
  ON uf.id = f.friends_club_2
WHERE u.id = 1234

UNION

SELECT uf.*, f.state
FROM User_Info u
INNER JOIN Friends f
  ON f.friends_club_2 = u.id
INNER JOIN User_Info uf
  ON uf.id = f.friends_club_1
WHERE u.id = 1234

Answer: Your results aren't correct, "Stefan Refan" wouldn't be in the results.
SELECT UI.id AS my_friends,
       COALESCE(F1.state,F2.state) AS state,
       UI.name, UI.surname, UI.age
FROM [User Info] as UI
LEFT OUTER JOIN [Friends] AS F1 ON (UI.id = F1.friends_club_1)
LEFT OUTER JOIN [Friends] AS F2 ON (UI.id = F2.friends_club_2)
WHERE COALESCE(F1.friends_club_2,F2.friends_club_1) = 1234;

You would need to Coalesce the F1.state and F2.state to find which one is used.
Comment: Thank you it's right the query, but if i want add the filter show the result only with state = 1 how can i do that? i've tried but without succes
Comment: Add to the WHERE section `AND COALESCE(F1.state,F2.state) = 1`
Comment: I found now one error not found very good, sometimes not show the right result when i have more same id in the database
Comment: Could you clarify the error your getting? When you have duplicate ids?

Query mysql with hard concatenament


Proof that if: a^2=b^2 then a=b or a=-b

Question: I have to prove that if a^2=b^2 then a=b or a=-b, and I came up with the following and I am wondering if it is valid use of absolute values?:
a^2=b^2 |square root of both sides
|a|=|b| |particularly interested in whether or not this next step is valid:
a=b or a=-b
Thank you in advance.
Edit: I do understand that perhaps easier way to prove is the following:
a^2=b^2
a^2-b^2=0
(a+b)=0 or (a-b)=0
a=-b or a=b
But I am interested in whether or not my prior proof was valid.
Comment: That is absolutely fine.
Comment: If possible, factorize!
Answer: $a^2=b^2$ means $a^2-b^2 = 0$ and so $(a-b)(a+b)=0$. Thus $a=b$ or $a=-b$.
Comment: I addressed that at the end of my post but appreciated nonetheless.
Answer: That is correct, from the logical point of view. But it is incomplete. You proved correctly that, if $a^2=b^2$, then $|a|=|b|$. But now you still have to prove that if $|a|=|b|$, then $a=b$ or $a=-b$.
Answer: Overkill
Consider the quadratic equation
$x^2-b^2=0;$
Two real solutions
$x_{1,2}=\sqrt{b^2}=\pm|b|;$
$x_1=|b|;$ $x_2=-|b|;$ which for
1)$b\ge 0:$ $x_1=b;$ $x_2 =-b;$
2)$b< 0:$ $x_1=-b;$ $x_2=b;$ or
with the original $a:$ $a=\pm b;$

Proof that if: a^2=b^2 then a=b or a=-b


Predicate in array

Question: I have an array which contains lots of info like lat,lon,city name etc.But all this info stored by class object.
("<GetCityList: 0x1fd334d0>",
"<GetCityList: 0x1fd33560>",
"<GetCityList: 0x1fd33310>",)

my array is looking like this.if i want city name then first i create GetCityList object and then object.cityName.
Now i have to search lat and lon by comparing cityName.so how can i do,because it consumes too much time?can i use predicate ?how?
Answer: Let say you have an array of cityList and want to Filter this by city name you can do
NSPredicate *cityNamePredicate = [NSPredicate predicateWithFormat:@"cityName contains[c] %@", @"cityName"]
NSArray *filteredCityList = [cityList filteredArrayUsingPredicate:cityNamePredicate];

Above filteredCityList will be your required filtered array whatever you passed in parameter. Here [cd] means case and diatric insensitive
You can refer this tutorial for further exploring NSPredicate.
Answer: Example:
self.data = [NSArray arrayWithObjects:
                         [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"To Airport",@"TO/AIR", nil] forKeys:[NSArray arrayWithObjects:kName,kCode, nil]],
                         [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Point-to-Point",@"PTP", nil] forKeys:[NSArray arrayWithObjects:kName,kCode, nil]],[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"From Airport",@"FR/AIR", nil] forKeys:[NSArray arrayWithObjects:kName,kCode, nil]], nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name CONTAINS[cd]  %@)",searchText];
self.searchableData = [self.data filteredArrayUsingPredicate:predicate];

Based on this you can replace name with cityName.
Answer: Use it in this way also:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cityName contains %@", @"cityNamehere"]

NSMutableArray *filtered = [cityListArray filterUsingPredicate:predicate];

Predicate in array


webhost (azure) blocks ajax calls

Question: I have a .php script on my azure server which returns JSON. When you visit the link in your browser, it shows you the JSON.
I want to make an ajax call to this script, but none of my ajax calls to the server get through. I have no idea why.
webpage that executes a failed ajax call to the .php script
Could it have something to do with cross-domain ajax calls?
Answer: I've found the solution here: origin-is-not-allowed-by-access-control-allow-origin ...
It's the browser who is blocking cross-origin ajax calls. You can overcome this by allowing your script to receive ajax calls from every domain by adding this to your script header:
C#:
Access-Control-Allow-Origin: *

php:
<?php header('Access-Control-Allow-Origin: *'); ?>

webhost (azure) blocks ajax calls


Web scraping: Index out of Bound (Possible scaling error)

Question: Hi Wrote a web scraping program and it gets the ASN number correctly, but after all the data is scraped, it returns a error "Array Out if Bounds".
I am using Pycharm and latest python version. Below is my code.
There is already a similar issue on stackoverflow but I am not able to get the pieces together and make it work. (Web Scraping List Index Out Of Range) its the exact same error but I am not sure how to get it working for my List.
Error seems to be at current_country = link.split('/')[2]
Any help is appreciated. Thank you.
import urllib.request
import bs4
import re
import json

url = 'https://ipinfo.io/countries'
SITE = 'https://ipinfo.io'

def url_to_soup(url):
    req = urllib.request.Request(url)
    opener = urllib.request.build_opener()
    html = opener.open(req)
    soup = bs4.BeautifulSoup(html, "html.parser")
    return soup

def find_pages(page):
    pages = []
    for link in page.find_all(href=re.compile('/countries')):
        pages.append(link.get('href'))
    return pages

def scrape_pages(links):
    mappings = {}

    print("Scraping Pages for ASN Data...")

    for link in links:
        country_page = url_to_soup(SITE + link)
        current_country = link.split('/')[2]
        print(current_country)
        for row in country_page.find_all('tr'):
            columns = row.find_all('td')
            if len(columns) > 0:
                current_asn = re.findall(r'\d+', columns[0].string)[0]
                print(current_asn)
                """
                name = columns[1].string
                routes_v4 = columns[3].string
                routes_v6 = columns[5].string
                mappings[current_asn] = {'Country': current_country,
                                     'Name': name,
                                     'Routes v4': routes_v4,
                                     'Routes v6': routes_v6}
      return mappings """

main_page = url_to_soup(url)

country_links = find_pages(main_page)
#print(country_links)

asn_mappings = scrape_pages(country_links)
print(asn_mappings)

Answer: The last href contains string "/countries" in https://ipinfo.io/countries is actually "/countries":

Global ASNs

After splitting this link, it produced list ["", "countries"] where the third element was missing. To fix this problem, simply check the list length before retrieving the third element:
        ...
        current_country = link.split('/')
        if len(current_country) < 3:
            continue
        current_country = current_country[2]
        ...

Another solution is to exclude the last href by changing the regexp to:
    ...
    for link in page.find_all(href=re.compile('/countries/')):
        ...

Comment: I am trying to get the data "REGISTRY" and "IP ADDRESS" by passing the each ASN Id (https://ipinfo.io/AS6984).  I am not sure how to write a regex. I am trying to do is print(abc.find_all('div')) which is not working.


Complex Search with Multiple Models and Geokit using Rails

Question: I am attempting to make a search very complicated (of course, to make it easier for users)
I've got an app with 3 models: Campaigns, Businesses and Locations
like so:
\\ campaign.rb
  belongs_to :business
  has_many :locations, :through => :business
  acts_as_mappable

\\ business.rb
  has_many :campaigns
  has_many :locations

\\ location.rb
  belongs_to :business
  has_many :campaigns, :through => :business
  acts_as_mappable

The way this is set up, there are some businesses that have multiple locations. For those that don't, the geokit info is coded into the campaign database entry.  For those that do have multiple locations the geokit info is coded into the location database entry.
I am trying to do a search for campaigns that will return the results within a certain distance. This is simple enough when dealing with businesses that have a single address.
  Campaign.find(:all,
       :conditions => [blahblahblah],
       :origin => address,
       :within => distance
       )

However, I want to also include campaigns that belong to businesses that have multiple locations. I want the search to return a result for that campaign, if the business has multiple locations, and if any of those locations fall within the bounds.  I was thinking something like:
  Campaign.find(:all,
       :include => [:business, :locations]
       :conditions => [blahblahblah],
       :origin => address,
       :within => distance
       )

But this doesn't return any results for campaigns that belong to businesses that have multiple locations.  I'm a noob when it comes to SQL so I'm not exactly sure how to have rails search in one model (Campaign), and search across another model (the Business model) to grab results from the Location model.  The fact that geokit is involved makes it even more complex.
I tried: acts_as_mappable :through => :locations in the campaign.rb but it just threw an sql error
I messed around with a polymorphic model "addressable" but I found I would pretty much have to start from the ground up on the controllers of the other models.
I've also thought about named_scopes but I believe that geokit does not support them.
Any suggestions?
Comment: Do you have to use Geokit? I have created a similar search mechanism where the user can enter multiple locations and radii, and be shown matches where their boundaries intersect. I do all the calculations in SQL for performance reasons. Ill post the queries later if you think they may help?
Comment: i suppose i don't have to use geokit, but the calculations seemed a bit intese to me, not to mention the conversion of address into lat,lng coordinates
Answer: If you think your model is overly complicated its a good sign that it needs a redesign.
Is it possible to have a campaign without a business? if not, then it doesnt make sense to make campaign act_as_mappable (Im assuming your campaign DB has lat and lng columns) if business already has mappable locations.
If campaign is associated with a business that has multiple locations, whats considered location of the campaign? What do you store in campaigns.lat and lng attributes?
If youre sticking with your datamodel, I recommend to break up your search into multiple commands:
def find_campaigns_near(origin,distance)
    locations = Location.find(:all,
            :origin => address,
            :within => distance
    );
    # use Hash for uniqueness based on id
    campaigns = Hash.new
    locations.each do |location|
        location.campaigns.each do |campaign|
            campaigns[campaign.id] = campaign if campaigns[campaign.id].blank?
        end
    end
    campaigns
end

Comment: thanks.  I implimented this almost exactly.  mainly the reason the datamodel was like this is I wanted to do a campaign search, not a business search.  It wasn't till much later that I dived into the complexities of geokit and found out I could do a location based search through another model


Simple prime number program - Weird issue with threads C#

Question: This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace FirePrime
{
    class Program
    {
        static bool[] ThreadsFinished;
        static bool[] nums;

        static bool AllThreadsFinished()
        {
            bool allThreadsFinished = false;
            foreach (var threadFinished in ThreadsFinished)
            {
                allThreadsFinished &= threadFinished;
            }
            return allThreadsFinished;
        }

        static bool isPrime(int n)
        {
            if (n < 2) { return false; }
            if (n == 2) { return true; }
            if (n % 2 == 0) { return false; }
            int d = 3;
            while (d * d <= n)
            {
                if (n % d == 0) { return false; }
                d += 2;
            }
            return true;
        }

        static void MarkPrimes(int startNumber,int stopNumber,int ThreadNr)
        {
            for (int j = startNumber; j < stopNumber; j++)
                nums[j] = isPrime(j);
            lock (typeof(Program))
            {
                ThreadsFinished[ThreadNr] = true;
            }
        }

        static void Main(string[] args)
        {
            int nrNums = 100;
            int nrThreads = 10;
            //var threadStartNums = new List<int>();

            ThreadsFinished = new bool[nrThreads];

            nums = new bool[nrNums];
            //var nums = new List<bool>();
            nums[0] = false;
            nums[1] = false;
            for(int i=2;i<nrNums;i++)
                nums[i] = true;

            int interval = (int)(nrNums / nrThreads);
            //threadStartNums.Add(2);
            //int aux = firstStartNum;
            //int i = 2;
            //while (aux < interval)
            //{
            //    aux = interval*i;
            //    i=i+1;
            //    threadStartNums.Add(aux);
            //}

            int startNum = 0;

            for (int i = 0; i < nrThreads; i++)
            {

                var _thread = new System.Threading.Thread(() => MarkPrimes(startNum, Math.Min(startNum + interval, nrNums), i));
                startNum = startNum + interval;
                //set the thread to run in the background
                _thread.IsBackground = true;
                //start our thread
                _thread.Start();
            }

            while (!AllThreadsFinished())
            {
                Thread.Sleep(1);
            }

            for (int i = 0; i < nrNums; i++)
                if(nums[i])
                    Console.WriteLine(i);
        }
    }
}

This should be a pretty simple program that is supposed to find and output the first nrNums prime numbers using nrThreads threads working in parallel.
So, I just split nrNums into nrThreads equal chunks (well, the last one won't be equal; if nrThreads doesn't divide by nrNums, it will also contain the remainder, of course).
I start nrThreads threads.
They all test each number in their respective chunk and see if it is prime or not; they mark everything out in a bool array that keeps a tab on all the primes.
The threads all turn a specific element in another boolean array ThreadsFinished to true when they finish.
Now the weird part begins:
The threads never all end. If I debug, I find that ThreadNr is not what I assign to it in the loop but another value.
I guess this is normal since the threads execute afterwards and the counter (the variable i) is already increased by then but I cannot understand how to make the code be right.
Can anyone help?
Thank you in advance.
P.S.:  I know the algorithm is not very efficient; I am aiming at a solution using the sieve of Eratosthenes also with x given threads.  But for now I can't even get this one to work and I haven't found any examples of any implementations of that algorithm anywhere in a language that I can understand.
Comment: Just a quick drive-by comment: Instead of looping while `AllThreadsFinished()` is false, you should [join](http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx) on each thread one at a time -- each call will block until the respective thread has terminated.  This is a much more CPU-efficient way to wait for threads to finish.
Comment: @Para: Are you aware of the new [Parallel class](http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx) in C# 4.0, which makes much of your manual book-keeping unnecessary?
Comment: The sieve of Eratosthenes can't be parallelized: You've got one prime number, you mark all it's multiples as not being primes. You move to the next non-marked number, print it out because it's an prime and repeat. What would two separate threads do?
Comment: @Cosmin Prund well it says here http://cs-alb-pc3.massey.ac.nz/notes/59735/seminars/01077635.pdf that it can be and gives an algorithm. I haven't researched the problem much and in school I only implemented it in a non parallel fashion. I only mentioned it because I knew it to be one of the fastest methods of finding primes.
Comment: @Cosmin Prund you can parallelise it by having enough communication between the threads so each thread marking off multiples in the sieve is always operating on numbers higher than the thread reading the primes. With light enough concurrency, you can have one task per prime and wake them periodically for each block of numbers for them to mark off. Alteratively, since all primes contributing to a block starting at *k* are less than *sqrt(k)*, process blocks in separate threads.
Comment: @BlueRaja - Danny Pflughoeft I am aware of it but the requirement was for a specified number of threads to run concurrently. I don't know how to run a specified number of threads with the Parallel class. It starts as many threads as it wants. This looks like a good implementation with parallel to find primes with the sieve of atkins http://alicebobandmallory.com/articles/2010/01/14/prime-factorization-in-parallel but overall not exactly within the requirements
Comment: @Cosmin Prund my implementation of the sieve in parallel http://paratechnical.blogspot.com/2011/01/c-implementation-of-parallel-sieve-of.html
Answer: The value the thread receives is the one startNum holds when the thread runs. To solve it copy the value into a local variable:
for (int i = 0; i < nrThreads; i++)
{
 var localStartNum = startNum; // save value in local variable
                                  // and use in the thread start
    var localIndex = i;

 var _thread = new System.Threading.Thread(() =>
                      MarkPrimes(localStartNum,
                                 Math.Min(localStartNum + interval, nrNums),
                                 localIndex));
 startNum = startNum + interval;
 _thread.IsBackground = true;
 _thread.Start();
}

Another bug in the code is waiting for all threads:
static bool AllThreadsFinished()
{
    bool allThreadsFinished = true; // Initialize to true instead of false
                                    // Otherwise, all ANDs will result false
    foreach (var threadFinished in ThreadsFinished)
    {
        allThreadsFinished = threadFinished;
    }

    return allThreadsFinished;
}

One tip which can help a little in synchronizing the threads: You can save all the threads in a list and join them from main thread.
var threads = new List<Thread>();

for (int i = 0; i < nrThreads; i++)
{
 var localStartNum = startNum; // save value in local variable
                                  // and use in the thread start
 var _thread = new System.Threading.Thread(() =>
                      MarkPrimes(localStartNum,
                                 Math.Min(localStartNum + interval, nrNums), i));
 startNum = startNum + interval;
 _thread.IsBackground = true;
 _thread.Start();
    threads.Add(_thread);
}

foreach(var thread in threads)
{
    thread.Join();
}

Comment: @Para, you're right, another bug exists in the code. `AllThreadsFinished` always evaluates false. Updated answer accordingly.
Comment: ah yes, that way it, thanks. Feel stupid now. But the local declarations that were missing were the big blunder. Thanks


MongoDB cursor causes my function to skip step

Question: This is my check permission function, and it work fine, but i can't return result because function skip one step and first return "access" variable, then execute cursor function to check permission. I do not idea what i do wrong. Console logs approve that:
Console result:
1
5 return here
2
3
3
3
4
function permissionChecker(guildID, reqUserID, checkPexArray) {
    console.log("1")
    let access = false

    let pexUserCheckCursor = db.db("MainDB").collection("Permissions").find({GuildID: guildID}).toArray(function (err, result) {
        console.log("2")
        let serverDB = result[0]
        let serverPexGroups = serverDB.PexGroups
        let serverPexGroupsNames = Object.keys(serverPexGroups)

        //Object of user's pexes.
        let serverPexUsers = serverDB.PexUsers
        //Looking for at least one of required pexes.
        for (let reqPex of checkPexArray) {
            for (let pexName in serverPexUsers) {
                console.log("3")

                //If reqPex has in DB
                if (reqPex == pexName) {
                    for (let userID of serverPexUsers[pexName]) {
                        //If req user has req pex.
                        if (userID == reqUserID) {
                            console.log("4")
                            access = true
                            return

                        } else {
                            access = false
                            return
                        }
                    }
                }
            }
        }
    })
    console.log("5 return here")
}

Comment: I recommend you read about promises and how they work, for example here:
https://www.freecodecamp.org/news/javascript-promises-explained/#:~:text=What%20is%20a%20promise%20in,operation%2C%20and%20its%20resulting%20value.
Answer: Your console output is correct, cause the db read is asynchronous.
Consider changing permissionChecker to an async function and then await the db callback result.
Or change the permissionChecker function to return a new Promise and then resolve(access) after the loops.


Scraping text after a span in with Regex (and Requests)

Question: I have an unformatted and messy bs4.BeautifulSoup element from a webpage. The soup looks like this.
soup = ' Jul 30, 2021"},{"id":"50014999","description":null,"displayValue":"M","value":"M","selected":false,"selectable":true,"url":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Variation?dwvar_2947_pv_rahmenfarbe=YE%2FBK&dwvar_2947_pv_rahmengroesse=M&pid=2947&quantity=1","hasComingSoon":true,"hasAllComingSoonAttr":true,"configurationUrl":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Configure?pid=2947&dwvar_2947_pv_rahmengroesse=M&dwvar_2947_pv_rahmenfarbe=YE%2fBK","sizeMin":178,"sizeMax":184,"measurementInterval":"178 cm - 184 cm","comingSoonReason":"productOrPreferenceInstockDate","comingSoon":true,"availability":{"messages":["Back order"],"inStockDate":"2021-08-09T00:00:00.000Z","onlyXLeftNumber":122,"onlyXLeft":false,"lowStock":false,"shippingInfo":"Coming in August 2021","available":false,"availableSufficient":true,"notifyMe":true,"showOutOfStock":false,"similarBikes":false,"comingSoonByBackOrderAllocation":false},"hasSuccessorProduct":false,"comingSoonMessage":"Coming in August 2021"},
{"id":"50015000","description":null,"displayValue":"L","value":"L","selected":false,"selectable":true,"url":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Variation?dwvar_2947_pv_rahmenfarbe=YE%2FBK&dwvar_2947_pv_rahmengroesse=L&pid=2947&quantity=1","hasComingSoon":true,"hasAllComingSoonAttr":true,"configurationUrl":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Configure?pid=2947&dwvar_2947_pv_rahmengroesse=L&dwvar_2947_pv_rahmenfarbe=YE%2fBK","sizeMin":184,"sizeMax":190,"measurementInterval":"184 cm - 190 cm","comingSoonReason":"productOrPreferenceInstockDate","comingSoon":true,"availability":{"messages":["Back order"],"inStockDate":"2021-08-16T00:00:00.000Z","onlyXLeftNumber":96,"onlyXLeft":false,"lowStock":false,"shippingInfo":"Coming in August 2021","available":false,"availableSufficient":true,"notifyMe":true,"showOutOfStock":false,"similarBikes":false,"comingSoonByBackOrderAllocation":false},"hasSuccessorProduct":false,"comingSoonMessage":"Coming in August 2021"},
{"id":"50015001","description":null,"displayValue":"XL","value":"XL","selected":false,"selectable":true,"url":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Variation?dwvar_2947_pv_rahmenfarbe=YE%2FBK&dwvar_2947_pv_rahmengroesse=XL&pid=2947&quantity=1","hasComingSoon":true,"hasAllComingSoonAttr":true,"configurationUrl":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Configure?pid=2947&dwvar_2947_pv_rahmengroesse=XL&dwvar_2947_pv_rahmenfarbe=YE%2fBK","sizeMin":190,"sizeMax":196,"measurementInterval":"190 cm - 196 cm","comingSoonReason":"productOrPreferenceInstockDate","comingSoon":true,"availability":{"messages":["Back order"],"inStockDate":"2021-08-09T00:00:00.000Z","onlyXLeftNumber":38,"onlyXLeft":false,"lowStock":false,"shippingInfo":"Coming in August 2021","available":false,"availableSufficient":true,"notifyMe":true,"showOutOfStock":false,"similarBikes":false,"comingSoonByBackOrderAllocation":false},"hasSuccessorProduct":false,"comingSoonMessage":"Coming in August 2021"},
{"id":"50015002","description":null,"displayValue":"2XL","value":"2XL","selected":false,"selectable":true,"url":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Variation?dwvar_2947_pv_rahmenfarbe=YE%2FBK&dwvar_2947_pv_rahmengroesse=2XL&pid=2947&quantity=1","hasComingSoon":false,"hasAllComingSoonAttr":false,"configurationUrl":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Configure?pid=2947&dwvar_2947_pv_rahmengroesse=2XL&dwvar_2947_pv_rahmenfarbe=YE%2fBK","sizeMin":196,"sizeMax":999,"measurementInterval":"> 196 cm","comingSoonReason":"","comingSoon":false,"availability":{"messages":["Back order"],"inStockDate":"2021-07-26T00:00:00.000Z","onlyXLeftNumber":10,"onlyXLeft":false,"lowStock":false,"shippingInfo":"Shipping Jul 26, 2021 - Jul 30, 2021","available":true,"availableSufficient":true,"notifyMe":false,"showOutOfStock":false,"similarBikes":false,"comingSoonByBackOrderAllocation":false},"hasSuccessorProduct":false,"comingSoonMessage":"Shipping Jul 26, 2021 - Jul 30, 2021"}],"resetUrl":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Variation?dwvar_2947_pv_rahmenfarbe=YE%2FBK&dwvar_2947_pv_rahmengroesse=&pid=2947&quantity=1","hasSelectedValue":false,"isLastAttributeOnPDP":true,"colorAttribute":false,"sizeAttribute":true,"buttonAttribute":false,"damagedAttribute":false}]}};</script>'

I need the elements after the span class =\productConfiguration__shippingDateEnd i.e the "id" dictionary so that i can have something like this after the search.
{"id":"50015002","description":null,"displayValue":"2XL","value":"2XL","selected":false,"selectable":true,"url":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Variation?dwvar_2947_pv_rahmenfarbe=YE%2FBK&dwvar_2947_pv_rahmengroesse=2XL&pid=2947&quantity=1","hasComingSoon":false,"hasAllComingSoonAttr":false,"configurationUrl":"https://www.xzy.com/on/demandware.store/Sites-RoW-Site/en_DE/Product-Configure?pid=2947&dwvar_2947_pv_rahmengroesse=2XL&dwvar_2947_pv_rahmenfarbe=YE%2fBK","sizeMin":196,"sizeMax":999,"measurementInterval":"> 196 cm","comingSoonReason":"","comingSoon":false,"availability":{"messages":["Back order"],"inStockDate":"2021-07-26T00:00:00.000Z","onlyXLeftNumber":10,"onlyXLeft":false,"lowStock":false,"shippingInfo":"Shipping}'

If i do soup1.find_all('span', class_ = 'productConfiguration__shippingDateEnd')  i only get this result. Also .next_siblings doesnt return anything.
[Jul 30, 2021,
[Jul 30, 2021,

Any ideas how i can go about here. ?
Thanks a lot for your help.
Comment: Can you share the link to the webpage?
Comment: @QHarr https://www.canyon.com/en-de/road-bikes/endurance-bikes/endurace/cf-sl/endurace-cf-sl-7-disc/2947.html?dwvar_2947_pv_rahmenfarbe=YE%2FBK For example looking for the product Size , XL, XS etc size availability.
Answer: What I see looks slightly different from as shown but contains stock info by size. You can use regex to extract the string, then json to handle turning the string into a json object.
import requests, re, json
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.canyon.com/en-de/road-bikes/endurance-bikes/endurace/cf-sl/endurace-cf-sl-7-disc/2947.html?dwvar_2947_pv_rahmenfarbe=YE%2FBK')
s = re.search(r'window\.deptsfra=(.*);', r.text).group(1)
#print(s)
data = json.loads(s)
print(data)

from pprint import pprint

pprint(data['productDetail']['variationAttributes'][1]['values'])

for i in data['productDetail']['variationAttributes'][1]['values']:
    print(i['value'], i['availability'])

Values as shown in the table as a dict:
results = {i['value']: (bs(i['availability']['shippingInfo']).get_text() if '<' in i['availability']['shippingInfo'] else i['availability']['shippingInfo']) for i in data['productDetail']['variationAttributes'][1]['values']}

Regex explanation:
Comment: @QHarr Great use of regex here. Thanks a lot.
Comment: Which service did you use for regex explanation?


Instant data type change to String JsonArray Vertx

Question: I have service proxy db call, I am sending the jsonarray over event bus through service proxy and converting the jsonArray to tuple to make DB call.
What Issue I am facing is jsonArray I received at my dbService the data-type of Instant got changed to String and data base throwing Invalid datetime format exception.
Answer: Yeah so you can't just 1 to 1 send a json array as a tuple - since the tuple is meant to define what the DB is to receive
So you need to convert the data types properly - might even see this issue with integers that are encoded as strings
Comment: I don't see issue with Integer, data type for integer not changed
Comment: Your profile says principal dev.. you can do a basic type conversion from string to date time


Python, transpose nested values adding None for Missing

Question: One of those days, Can't get me head around this tiny solution.
I am looking for generic solution as the length of the key value pairs in parent and child leg could vary.
so data source looks like following
data = {
    "New York": [
    { "Name": "John", "QTY": 56 },
    { "Name": "Richard", "QTY": 76 }   ],
    "Texas": [
    { "Name": "John", "QTY": 34 },
    { "Name": "Stephanie", "QTY": 23 }   ],
    "Florida": [
    { "Name": "Rebecca", "QTY": 28 },
    { "Name": "Richard", "QTY": 43 }   ],
    "Arizona": [
    {"Name": "Charles", "QTY": 23},
    {"Name": "Anne", "QTY": 31},
    {"Name": "William", "QTY": 44}   ],
    "New Mexico": [
    {"Name": "Rebecca", "QTY": 56},
    {"Name": "Charles", "QTY": 76},
    {"Name": "Stephen", "QTY": 21},
    {"Name": "William", "QTY": 63}   ],
    "New Jersey": [
    {"Name": "John", "QTY": 56},
    {"Name": "Richard", "QTY": 76},
    {"Name": "Stephen", "QTY": 45}   ] }

Now I want to re-arrange the the dictionary by Name and add values for each state and add None for missing. here is my code
output = {}

for x, y in data.items():
    for i in y:
        key = i['Name']
        try:
            output[key].update({x: i['QTY']})
        except:
            output[key] = {x: i['QTY']}

print(output)

This gives me result as following
{
  "John": {
    "New York": 56,
    "Texas": 34,
    "New Jersey": 56
  },
  "Richard": {
    "New York": 76,
    "Florida": 43,
    "New Jersey": 76
  },
  "Stephanie": {
    "Texas": 23
  },
  "Rebecca": {
    "Florida": 28,
    "New Mexico": 56
  },
  "Charles": {
    "Arizona": 23,
    "New Mexico": 76
  },
  "Anne": {
    "Arizona": 31
  },
  "William": {
    "Arizona": 44,
    "New Mexico": 63
  },
  "Stephen": {
    "New Mexico": 21,
    "New Jersey": 45
  }
}

What I will like to have is something like following, order is indeed important
{
  "John": {
    "New York": 56,
    "Texas": 34,
    "Florida": None,
    "Arizona": None,
    "New Mexico": None,
    "New Jersey": 56
  },
  .......
  .......
  "Stephen": {
    "New York": None,
    "Texas": None,
    "Florida": None,
    "Arizona": None,
    "New Mexico": 21,
    "New Jersey": 45
  }
}

I was wondering if defautldict from collections can be used. But I am not that savvy with it. Folks, remember I need generic solution as the number of states and number os Names can vary.. Any help is much appreciated.
Comment: One place to start might be to gather all of the required keys to begin with, then use `dict.get(i)` rather than `dict[i]`, as `get` can return a `None` if the key is not found
Answer: In your code, instead of:
try:
    output[key].update({x: i['QTY']})
except:
    output[key] = {x: i['QTY']}

do
try:
    output[key].update({x: i['QTY']})
except KeyError:
    output[key] = defaultdict(none_generator, {x: i['QTY']})

Here, none_generator is a function that takes no arguments and returns `None:
def none_generator(): pass

Note: You shouldn't be using a bare except: clause anyway. You know your output[key].update(...) line will produce a KeyError if all is working as expected, so only catch a KeyError (See What is wrong with using a bare 'except'? for more details)

Now, each value of your output dictionary is itself a defaultdict, and getting a non-existent key of these defaultdicts will return `None:
output = {'John': defaultdict(<function none_generator at 0x12256d6c20>, {'New York': 56, 'Texas': 34, 'New Jersey': 56}), 'Richard': defaultdict(<function none_generator at 0x12256d6c20>, {'New York': 76, 'Florida': 43, 'New Jersey': 76}), 'Stephanie': defaultdict(<function none_generator at 0x12256d6c20>, {'Texas': 23}), 'Rebecca': defaultdict(<function none_generator at 0x12256d6c20>, {'Florida': 28, 'New Mexico': 56}), 'Charles': defaultdict(<function none_generator at 0x12256d6c20>, {'Arizona': 23, 'New Mexico': 76}), 'Anne': defaultdict(<function none_generator at 0x12256d6c20>, {'Arizona': 31}), 'William': defaultdict(<function none_generator at 0x12256d6c20>, {'Arizona': 44, 'New Mexico': 63}), 'Stephen': defaultdict(<function none_generator at 0x12256d6c20>, {'New Mexico': 21, 'New Jersey': 45})}

print(output["John"]["Florida"]) prints None

If you want there to be None values explicitly at the keys in the dictionary that do not exist, you're going to have to populate the output dictionary first. Then, remake all dictionaries with their missing values set to None:
output = {}
for x, y in data.items():
    for i in y:
        key = i['Name']
        all_states.add(x)
        try:
            output[key].update({x: i['QTY']})
        except KeyError:
            output[key] = {x: i['QTY']}

for person, person_vals in output.items():
    output[person] = {state: person_vals.get(state, None) for state in data}

{'John': {'New York': 56,
  'Texas': 34,
  'Florida': None,
  'Arizona': None,
  'New Mexico': None,
  'New Jersey': 56},
 'Richard': {'New York': 76,
  'Texas': None,
  'Florida': 43,
  'Arizona': None,
  'New Mexico': None,
  'New Jersey': 76},
 'Stephanie': {'New York': None,
  'Texas': 23,
  'Florida': None,
  'Arizona': None,
  'New Mexico': None,
  'New Jersey': None},
 'Rebecca': {'New York': None,
  'Texas': None,
  'Florida': 28,
  'Arizona': None,
  'New Mexico': 56,
  'New Jersey': None},
 'Charles': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': 23,
  'New Mexico': 76,
  'New Jersey': None},
 'Anne': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': 31,
  'New Mexico': None,
  'New Jersey': None},
 'William': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': 44,
  'New Mexico': 63,
  'New Jersey': None},
 'Stephen': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': None,
  'New Mexico': 21,
  'New Jersey': 45}}

Comment: Yep, populating set of values for all states needed to be done. Thank you so much
Answer: Here's a straightforward way to do what your question asks:
nameList = []
nameSet = set()
for state, nameQtyList in data.items():
    for nameQty in nameQtyList:
        name = nameQty["Name"]
        if name not in nameSet:
            nameSet.add(name)
            nameList.append(name)
out = {name:{state:None for state in data} for name in nameList}
for state, nameQtyList in data.items():
    for nameQty in nameQtyList:
        out[nameQty["Name"]][state] = nameQty["QTY"]

Explanation:

walk through the input, compiling names in the sequence of first occurrence in names
initialize the result out to have the desired structure, with an initial value of None for each QTY
walk through the input again, updating out with each QTY encountered in the input.


Age buckets vs. Year of Birth vs. Fill-In

Question: I was wondering what you thought of the relative merits of getting age by

leaving a blank box for the user to fill in.
using a pull-down menu for birth year.
using age buckets ("under 18", "19 - 24", "25 - 34", etc.).

My instinct is to want exact data (either a fill-in or year of birth), because age buckets can still be created from that if I want it, but the reverse is not also true.
On the other hand, I'm new to this business (now in the video game industry after years in academia) and all I've seen so far are age buckets on surveys.  It seems to be the industry standard.
Any wise and wondrous thoughts?
Comment: Age is private and sensible info. People don't like to share it, until there is a clear reason for this. So I assume asking buckets is the most anonymous way of sharing this info. Also make shure you really need exact year of birth/age. Does it have critical impact on your business?
Comment: Yea its really private. It's not surprising that so many seem to be born in 01.01.1990 or at least seem to
Comment: what is the business objective and value of capturing users' age?
Comment: For mobile gaming, age (and capturing generational data) is an important factor in understanding both our general and paying audience.  ... Is it common here to ask the asker to justify the questions asked rather than answering it?  Just curious.
Comment: LOL, again, new here... but surprised anew that a user has edited my question to make it "better" but did not answer it.  There are now more people questioning my question and my question-asking methodology than there are people being helpful and responding.  Is this itself a UX issue?
Comment: this is a community driven resource, and people donates their time and knowledge to help their peers. Someone may not know the answer to your question yet can improve the format, just like Joshua did. Chill out, answers will come despite your attitude
Comment: When conducting research, it's always worthwhile to ask whether any given piece of data is actually needed or is something that would be nice to have.  Being able to draw that distinction will help you craft research that answers the questions you really need answered.
Comment: Don't mean to have an "attitude," per se.  New to this community and am not used to people correcting question wording/challenging my right to ask the question I'm asking.  As a resource, I would say that if you don't think my question is worthwhile or worded terribly, you do not need to respond to it.  But that's just me.  I appreciate all the pertinent feedback and am learning how to be a part of this community. =)
Comment: I don't think that Alexey challenged your right to ask the question you're asking.  Understanding whether something truly is business critical helps frame the answers that you receive, and being able to question assumptions is a critical UX skill.  For those who make improvements to questions, this not only helps you get better answers, but also helps people who come later who might have a similar question.
Answer: A pull-down menu to select either age or year of birth is immensely user-unfriendly.  A menu should never have 50+ values on it, and doubly so when the values are numeric.  This selection requires that the user pay a lot of attention to the menu, and is error-prone.  Worse, since the error is likely to be only wrong by a year or two, the survey respondent isn't likely to correct it because it's close enough.  This reduces your choice to two: buckets, and manual entry.
One consideration in selecting how to answer this question is to consider whether your survey respondent will be primarily answering your survey via keyboard or mouse.  Making the survey respondent switch back and forth between modes of entry is more likely to result in them quitting out of the survey altogether.  If you are going to switch between modes of entry, do so thoughtfully, and consider ordering your questions so that you limit the number of switches between them.
It's worthwhile to note that survey respondents who are on a mobile device tend to have higher response rates if the amount of keyboard entry is limited.  If your game dev is mobile, or if you anticipate that a large number of your respondents will use a mobile device to respond, I would choose buckets over manual entry.
Demographic questions are personal questions, and people can have unexpected reactions to being asked personal questions.  Requiring that someone divulge their exact age increases the likelihood that your survey respondent will either lie (if they're invested in the survey) or simply quit the survey (if they don't).  The age range buckets decrease your chance of the respondent quitting the survey because they don't want to divulge information that they feel is personal.
Answer: I would try very hard to not ask the question at all, but failing that you need to consider the audience.

Is it clear to the user why you need their age at all? Do they benefit in some way from giving you correct information? If not, expect a lot of fake (read: useless) data.
Is it clear to the user why you need exact ages? If it's some sort of age verification you're going to get a bunch of fake data for users set to 1900 or similar just because it's the easiest, least creepy way to get through your barrier to entry.
Is your business especially trustworthy or legally entitled to the information? A bank or other similar institution will be more likely to get actual answers than a supermarket chain.

If you care more about correct data than precise data, ranges are better. If you would rather precise data at the risk of getting a lot of false responses, ask for an age or year (as a numeric text field; most users don't know about typeahead and will have to scroll your monster drop-down to target the correct year with a mouse—another cause of potential false input, since it's much easier to let the scroll wheel fly to the bottom of the list than target the correct year).


Python Date / Time Regular Expression

Question: I am pretty new to regular expressions and it's pretty alien to me. I am parsing an XML feed which produces a date time as follows:
Wed, 23 July 2014 19:25:52 GMT

But I want to split these up so there are as follows:
date = 23/07/2014
time = 19/25/52

Where would I start? I have looked at a couple of other questions on SO and all of them deviate a bit from what I am trying to achieve.
Comment: Why use regex and not e.g. [`datetime.strptime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime)?
Comment: @jonrsharpe you should put this as an answer.
Comment: @jonrsharpe will strptime still work with the "July" in the xml?
Comment: @user3077627 why do you think it wouldn't?
Comment: @jonrsharpe worth an experiment - thanks for your insight!
Answer: Use datetime.strptime to parse the date from string and then format it using the strftime method of datetime objects:
>>> from datetime import datetime
>>> dt = datetime.strptime("Wed, 23 July 2014 19:25:52 GMT", "%a, %d %B %Y %H:%M:%S %Z")
>>> dt.strftime('%d/%m/%Y')
'23/07/2014'
>>> dt.strftime('%H/%M/%S')
'19/25/52'

But if you're okay with the ISO format you can call date and time methods:
>>> str(dt.date())
'2014-07-23'
>>> str(dt.time())
'19:25:52'

Comment: @user3077627 yeah, [here's the link](https://docs.python.org/3/library/datetime.html?highlight=datetime.datetime#strftime-and-strptime-behavior)
Comment: Thanks so much for your help! Annoyingly this is throwing a Value Error: Wed, 23 July 2014 19:25:52 GMT does not match "%a, %d %B %Y %H:%M:%S %Z" - do you have any idea why? Is there anywhere I can read more about the percent signs and letters?

Python Date / Time Regular Expression


firebase quota exceeded (per day?)

Question: Error: quota exceeded (Quota exceeded for quota group 'CPUMilliSecondsDailyNonbillable' and limit 'CPU allocation in function invocations per day' of service 'cloudfunctions.googleapis.com' for consumer 'project_number:221474907579'., Quota exceeded for quota group 'CPUMilliSecondsNonbillable' and limit 'CPU allocation in function invocations per day' of service 'cloudfunctions.googleapis.com' for consumer 'project_number:221474907579'.); to increase quotas, enable billing in your project at https://console.cloud.google.com/billing?project=samsungmap-xyz. Function cannot be executed.
my project still runs fine if i use firebase serve --only functions
but on deployment it shows the above error
It mentions somewhere "per day limit".
Does that mean i can deploy after 24 hrs and quota will reset or something?
Answer: You should be able to deploy whenever you want.  The functions just won't run until the daily quota resets.

firebase quota exceeded (per day?)


Laravel 5: Trying to get property of non-object through method injection

Question: I am using Route-Model-Binding with method injection to retrieve the $post->id of the post I am commenting on, but I keep getting this error

Trying to get property of non-object (View: C:\xampp\htdocs\reddit\resources\views\partials\post.blade.php) (View: C:\xampp\htdocs\reddit\resources\views\partials\post.blade.php)

This is the method I have, injecting Post $post then trying to get $post->id
dd($post) retrieves nothing at all even if I dump the model alone.
public function post_this_comment(Request $request, Post $post) {
    $post = Post::whereId($post->id)->first(); // this is where I'm getting the post

    $comment = new Comment;
    $comment->user_id = Auth::id();
    $comment->comment = $request->input('commenter_comment');
    $comment->parent_id = $request->input('commenter_parent');
    if($comment->parent_id > 0){
        $my_parent = Comment::find($comment->parent_id);
        $comment->parents = $my_parent->parents.'.'.$comment->parent_id;
    }else{
        $comment->parents = '0';
    }
    $comment->save();

    $per_page = $request->input('per_page');

    $comment_list = view('post/show')
        ->with('comments', $this->comment_list($per_page, $request))
        ->with('total_comments', $this->total_comments())
        ->with('per_page', $per_page)
        ->with('post', $post)
        ->render();

    $response = array(
        'status' => 'success',
        'msg' => 'Comment Saved!',
        'comment_list' => $comment_list
    );

    return Response::json($response);
}

This is the view, I have opened a form even though I don't need it because I'm submitting data via ajax.
{!! Form::open(['route' => ['post_this_comment', $post]]) !!}

                        <textarea id="commenter_comment" name="commenter_comment" class="form-control comment-field" title="User's comment" placeholder="Comment Text"></textarea>

                    <input type="hidden" id="commenter_parent" name="commenter_parent" class="commenter-parent" value="0">

                        Comment

  {!! Form::close() !!}

Routes
Route::resource('posts', 'PostsController');
Route::post('{post}/post_this_comment', ['as' => 'post_this_comment', 'uses' => 'PostsController@post_this_comment']);

RouteServiceProvider
$router->model('articles', 'App\Article');
$router->model('subreddit', 'App\Subreddit');
$router->model('posts', 'App\Post');
$router->model('moderators', 'App\Moderator');
$router->model('comments', 'App\Comment');

Answer: The parameter in your route needs to match the one you used for your route model binding. In your case you have defined posts: $router->model('posts', 'App\Post'); but you are using {post} (without the 's') as the parameter in your route. Instead your route should be:
Route::post('{posts}/post_this_comment', ['as' => 'post_this_comment', 'uses' => 'PostsController@post_this_comment']);
If you want to inject your Post model in to you method.
Comment: This gives `NotFoundHttpException in Router.php`
Comment: Changing the parameter name shouldn't make any difference to the actual route. This error occurs when the route cannot be found either because it doesn't exist or you are using the wrong method.
Comment: I am using a resource route for posts. I did `php artisan route:list` the only comment related route is `{post}/post_this_comment` - I managed to get the postId from a hidden input field value. But I am not able to `Input::get('commenter_post')` on `comment_list()` method, returns null.
Comment: Voted you up but I think he should change `posts` to `post` not the other way around, since it's a single Post object
Comment: @andrewtweber Thanks! I agree, I think the singular makes more sense, however, when you use resource routes Laravel generates the parameter using the specified path, so if you use `posts` in the resource route the parameter will be `{posts}`. I did take a look in the docs but I can't see anyway to override this behavior, which almost feels like something that has been overlooked.
Answer: You should bind the model using something like this:
$router->model('post', 'App\Post'); // 'post' parameter is used here

So that you can use the following:
Route::post(
    '{post}/post_this_comment', // post parameter is used here
     [
         'as' => 'post_this_comment',
         'uses' => 'PostsController@post_this_comment'
     ]
);

Bith parameters should match. When you bind some model using a parameter for example, $router->model('user', 'App\User') you said the framework to bind the appropriate User model when it sees a user parameter used in a route.
Comment: This gives me `No query results for model [App\Post].` on page load.
Comment: Then you are doing something wrong in your app not sure what but in the method parameters list `Post $post` souuld be the model and you don't need to `query` manually.
Comment: What could I be doing wrong? I access `$post->id` everywhere in my app and it works just fine on other methods in the same controller. Could it be my relations?


Group array to months and days

Question: I am looking for an elegant way to group or re-organize an array by month and then group nested days as well.
Example from:
[
  {
    "_id": "59d34fabe0a967636c7642f2",
    "date": "2017-02-12",
    "isActive": true
  },
  {
    "_id": "59d34fab9d1a05ca06ef9775",
    "date": "2017-02-12",
    "isActive": true
  },
  {
    "_id": "59d34fab4d49dc45357ab3a5",
    "date": "2017-02-16",
    "isActive": true
  },
  {
    "_id": "59d34fab5aa903089e1f9a44",
    "date": "2017-03-21",
    "isActive": true
  }
]

Example to:
{
  '2017-02': [
    {
      "day": "2017-02-12",
      "content": [
        {
          "_id": "59d34fabe0a967636c7642f2",
          "date": "2017-02-12",
          "isActive": true
        },
        {
          "_id": "59d34fab9d1a05ca06ef9775",
          "date": "2017-02-12",
          "isActive": true
        }
    },
    {
      "day": "2017-02-16",
      "content": [
        {
          "_id": "59d34fabe0a967636c7642f2",
          "date": "2017-02-16",
          "isActive": true
        }
    },
  ],
  '2017-03': [
    {
      "day": "2017-03-21",
      "content": [
        {
          "_id": "59d34fabe0a967636c7642f2",
          "date": "2017-03-21",
          "isActive": true
        }
    },
}

At first, I used groupBy: and I got the first part, but not sure how to get group days in an elegant way:
groupBy(array, (item) => {
  return item.date.substring(0,7);
};

How do group days now? Thanks in advance.
Answer: You could take a nested hash table for grouping by month and day.

var data = [{ _id: "59d34fabe0a967636c7642f2", date: "2017-02-12", isActive: true }, { _id: "59d34fab9d1a05ca06ef9775", date: "2017-02-12", isActive: true }, { _id: "59d34fab4d49dc45357ab3a5", date: "2017-02-16", isActive: true }, { _id: "59d34fab5aa903089e1f9a44", date: "2017-03-21", isActive: true }],
    result = {},
    hash = Object.create(null);

data.forEach(function (o) {
    var month = o.date.slice(0, 7),
        day = o.date.slice(-2);

    if (!hash[month]) {
        hash[month] = { _: [] };
        result[month] = hash[month]._;
    }
    if (!hash[month][day]) {
        hash[month][day] = [];
        result[month].push({ day: o.date, content: hash[month][day] });
    }
    hash[month][day].push(o);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: I'd suggest doing it the other way round: first group by days and then by months:

var array = [{ _id: "59d34fabe0a967636c7642f2", date: "2017-02-12", isActive: true }, { _id: "59d34fab9d1a05ca06ef9775", date: "2017-02-12", isActive: true }, { _id: "59d34fab4d49dc45357ab3a5", date: "2017-02-16", isActive: true }, { _id: "59d34fab5aa903089e1f9a44", date: "2017-03-21", isActive: true }];

result = _(array)
    .groupBy('date')
    .map((content, day) => ( {day, content} ))
    .groupBy($ => $.day.slice(0, 7))
    .value();

console.log(result)

Answer: You can do it this way with update, forEach and groupBy methods:

var arr=[
  {
    "_id": "59d34fabe0a967636c7642f2",
    "date": "2017-02-12",
    "isActive": true
  },
  {
    "_id": "59d34fab9d1a05ca06ef9775",
    "date": "2017-02-12",
    "isActive": true
  },
  {
    "_id": "59d34fab4d49dc45357ab3a5",
    "date": "2017-02-16",
    "isActive": true
  },
  {
    "_id": "59d34fab5aa903089e1f9a44",
    "date": "2017-03-21",
    "isActive": true
  }
]

var groupResult = _.groupBy(arr, item => {
 return item.date.split('-').splice(0,2).join('-')
});

_.forEach(
  groupResult,
  (dates, key) => _.update(
    groupResult,
    key,
    datesArray => _.groupBy(datesArray, item => item.date)
  )
);

console.log('groupResult ==> ', groupResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Group array to months and days


Django form for a model create object of another model

Question: Is there anyway to create an object of another model instance in a django form for a specified model? For instance when you'll add a new user using django admin you have the options to create another group ou add the user to an existing one.
@Edit
I will try to clarify better with another example ... I have a product form, to add a new product, the user can choose which category it belongs, but if there is no such category, it will have to create the corresponding category. And then add this product to new category and save the new product.
Comment: It's hard to follow. Can you explain in other words or bring abother example?
Answer: if form.is_valid():
    c = form.cleaned_data["category"]
    category = Category.objects.filter(name=c).first()
    if not category:
        category = Category.objects.create(name=c)
    product = form.save(commit=False)
    product.category = category
    product.save()

You could also consider using a pre_save signal to create the category object. But this is much simpler and easy to maintain.
Comment: Thanks. This helped me a lot.
Answer: I was able to achieve what a I wanted using karthikr answer and also this thread on stackoverflow Django form with choices but also with freetext option?


Call method from public class in running thread

Question: I split my program according to the Model-View-Controller pattern so far.
For my threads I created a new class:
public class MyThreadClass extends Thread
{
    public MyThreadClass()
    {

    }

    public void run()
    {
        //Call method from other class (public class Controller)
    }

}

In run()-method the thread shall call a method of another class, (e.g., public class Controller for my purpose).
I could instantiate the class controller but wouldn't that destroy the purpose of keeping to the MVC-principle?
How should I do that?
Answer: Well, since you haven't given much detail, please be patient with an answer that might not match your problem exactly.
Also, the way you're structuring and asking this question makes me uneasy about your use of threads. I think you should reconsider whether or not you need threads for what you're doing.
But, to the point of answering...
I'll give you two broad patterns to use while trying to call this Controller class method.

Give your thread a reference to your Controller when you create it.
public class MyThreadClass extends Thread
{
    private Controller controller;

    public MyThreadClass(Controller controller)
    {
        this.controller = controller;
    }

public void run()
{
    //Call method from other class (public class Controller)
    controller.someMethod();
}

Make the controller's method public and static (If you don't know how to do that, then don't try using this approach -- declaring something static has greater complexities/assumptions than you want to mess with if you're already having problems with method accessability.) Then call it like this:
public void run()
{
     Controller.someMethod();
}

And for your question about MVC:

I could instantiate the class controller but wouldn't that destroy the purpose of keeping to MVC-principle?

MVC requires that the View can connect to the Controller or communicate with it somehow. Instantiating a Controller generally has no effect on whether or not your design pattern is MVC. That being said, if you were asking about having each MyThreadClass instantiate its own version of the Controller... that would be poor MVC. Don't do that.


C, network programming - sockets. One socket for read, another for write - possible?

Question: I wrote a simple client to communicate with my echo server in C:
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>

#define SIZE 1024

int main(int argc, char **argv)
{
    char buffer[SIZE+1];
    int port = 6666;
    char msg[1000];

    int sockfd, recv_size;
    struct sockaddr_in server_addr;

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket");
        exit(1);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    inet_aton("127.0.0.1", &server_addr.sin_addr);

    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
    {
        perror("connect");
        exit(1);
    }

    while (1)
    {
        printf("> ");
        fgets (msg, 999, stdin);

        if ((send(sockfd, msg, strlen(msg), 0) < 0))
        {
            close(sockfd);
            if (errno != 0)
            {
                perror("recv");
                exit(1);
            }
        }

        if ((recv_size = recv(sockfd, buffer, SIZE, 0)) == 0)
        {
            close(sockfd);
            if (errno != 0)
            {
                perror("recv");
                exit(1);
            }
        }

        buffer[recv_size] = '\0';
        printf("FROM SERVER: %s\n", buffer);
    }

    close(sockfd);

    return 0;
</code>
}
And I'm wondering, if its possible to use one socket for reading only (on port, let's say 6666), and another socket (port 6667) for writing only?
How should I implement the server then?
Comment: if you need to restrict read/write - take a look at [shutdown](http://man7.org/linux/man-pages/man2/shutdown.2.html).
Comment: The `send()` and `recv()` don't necessarily send or receive the complete data in your program.
Answer: Just use two separate sockets bound to two different port on the server's side, no rocket science here. Question is: why would you like to do that?
Comment: `select`, `poll` and `epoll` are your friends. Also read about the reactor pattern: http://www.adamtornhill.com/Patterns%20in%20C%205,%20REACTOR.pdf
Comment: For fun I guess:) But I'm worried about the socket blocking issue. Because I would like to use one for reading ONLY, and another for writing ONLY. And what about the server then?
Comment: You're right to worry about socket blocking being an issue, it can be (because a thread that is blocked waiting for I/O can't do anything else; it can't even shut down cleanly when the user wants the app to quit!).  The solution to that problem is to use non-blocking sockets, though.  You can also use multiple sockets, of course, but that doesn't really solve the problem, because now you've got *two* sockets that are blocking for I/O.  (@alagner is right as well; once you're using non-blocking sockets, select()/poll()/epoll() will help you avoid spinning the CPU)


Smart switch not working with correct setting

Question: My house built just this year and it supposed to have neutral wires in the switch box.
So, I bought kasa smart switch.
Before connect supply-in wire, i used VOL detector to make sure that's the only one line makes the detector beeps.
After connecting all the wires... the switch doesn't have any signal.
Any idea?

https://www.amazon.com/dp/B079775ZZQ?ref=ppx_yo2_dt_b_product_details&th=1
Comment: What does "no signal" mean?  Does it operate the lights?  Does the switch have any indicator LEDs that show when it's getting power?  Also, what's with the tiny little pigtails for the load and supply wires?
Answer: I see a whole bunch of white in the back. I suspect you pulled one white neutral at random from a bunch and connected that to the switch. All neutrals need to stay together - i.e., in one wire nut or in two with a connecting wire.
Comment: Yep - and now there's also something else nearby which doesn't work anymore because its neutral isn't connected to that bundle like it was before.


General solution of a linear system of equations

Question: Any solution $p$ of $Ax = b$ can be written uniquely in the form $p = p_0 + h$ for some solution $h$ of the associated homogeneous system and $p_0$ the particular solution.
I have proven the existence part, but I am having a hard time proving the uniqueness part. Is it that simple? Just take $p=p_0+h_1=p_0+h_2$ and so $h_1=h_2$ or am I doing something wrong?
Answer: Yes it is that simple, suppose $p_0+h_1=p=p_0+h_2$, then by vector addition laws (subtracting $p_0$), we have $h_1=h_2$.
Answer: We have that
$$Ap_1=b \land Ap_2=b \implies A(p_1-p_2)=b-b=0$$
therefore
$$p_1-p_2=h \implies p_1=p_2+h$$
Comment: I don't understand what you are trying to do?
Comment: How does this show uniqueness of form?
Comment: @user330477 Yes sorry, it was very confusing. It should be fixed now. We can show that the solution is unique if an only if h=0. Otherwise we have infinitely many solutions.


pointer to next element of an array

Question: I am struggling with a problem in C. The problem is how to get pointer to an element in array if I know the pointer to the previous element in the array?
Suppose I have a string
s = "Hello World"

and I have a pointer to 'o' in the string
char *p = strchr(s, 'o')

How do I get pointer to o given I just know p?
Answer: If you know that the pointer to an array element is not pointing to the last element of the array, the expression p+1 will point to the next element of the array. This rule works regardless of the type of the array element, as long as the base type of the pointer is the same as the element type of the array: the compiler makes all the necessary adjustments when performing the addition.
Therefore, in your strchr example printing *(p+1) will print a space.
Demo.
Comment: @Lokesh This could happen if you are assigning a result of a pointer expression to a variable of numeric type.
Comment: Any idea why I might be getting this warning: "sumIt_dec.c:93:11: warning: assignment makes integer from pointer without a cast [enabled by default]
"?
Comment: Aha! Problem solved. Thanks! I was thinking the problem is in my manipulation of pointer to the next element.
Answer: As dasblinkenlight already put it you can use "Pointer Arithmetic"  for this.
If you have a pointer(p) and you add 'x' to it you get the 'xth' element from the location the pointer is at.

pointer to next element of an array


Combining pipes and the magrittr dot (.) placeholder

Question: I am fairly new to R and I am trying to understand the %>% operator and the usage of the " ." (dot) placeholder. As a simple example the following code works
library(magrittr)
library(ensurer)
ensure_data.frame <- ensures_that(is.data.frame(.))
data.frame(x = 5) %>% ensure_data.frame

However the following code fails
ensure_data.frame <- ensures_that(. %>% is.data.frame)
data.frame(x = 5) %>% ensure_data.frame

where I am now piping the placeholder into the is.data.frame method.
I am guessing that it is my understanding of the limitations/interpretation of the dot placeholder that is lagging, but can anyone clarify this?
Answer: The "problem" is that magrittr has a short-hand notation for anonymous functions:
. %>% is.data.frame

is roughly the same as
function(.) is.data.frame(.)

In other words, when the dot is the (left-most) left-hand side, the pipe has special behaviour.
You can escape the behaviour in a few ways, e.g.
(.) %>% is.data.frame

or any other way where the LHS is not identical to .
In this particular example, this may seem as undesirable behaviuour, but commonly in examples like this there's really no need to pipe the first expression, so is.data.frame(.) is as expressive as . %>% is.data.frame, and
examples like
data %>%
some_action %>%
lapply(. %>% some_other_action %>% final_action)

can be argued to be clearner than
data %>%
some_action %>%
lapply(function(.) final_action(some_other_action(.)))

Answer: This is the problem:
. = data.frame(x = 5)
a = data.frame(x = 5)

a %>% is.data.frame
#[1] TRUE
. %>% is.data.frame
#Functional sequence with the following components:
#
# 1. is.data.frame(.)
#
#Use 'functions' to extract the individual functions.

Looks like a bug to me, but dplyr experts can chime in.
A simple workaround in your expression is to do .[] %>% is.data.frame.
Comment: Thanks for the clarification that it might be an inconsistency in dplyr and for the workaround!


Power calculation problem

Question: Three machines perform together a certain job.  If only machine A works, to perform the job alone, it would require a hours more than the time required to perform the job by the 3 machines, when they work together. If only machine B works, to perform the job alone, it would require b hours more than the time required to perform the job by the 3 machines, when they work together. If only machine C works, to perform the job alone, it would require c times more hours more than the time required to perform the job by the 3 machines, when they work together. In how much time each of the machines would complete the work, if it were to work by itself? The solution must be expressed using a,b,c .
How do I even begin this?
Answer: Let $D$ be the number of hours  machine A would take to do the job.  Similarly $E$ for machine B and $F$ for machine $C$.  That means in one hour A can do $\frac 1D$ of the job.  How much can the three machines do together in one hour?  If you take the reciprocal of that, you have the number of hours the three machines take to do the job together, we will call it $H$.  Now write the three equations based on the text:  $D=a+H$  You are looking to express $D,E,F$ as an expression involving $a,b,c$
Comment: what you say here sounds logical but turns into an amazingly complex system of equations...is there any easier solution?
Comment: It will be three equations in three unknowns.  They tend to be a bit of a mess unless there are cancellations.  Naming recurring quantities, like $H$ above, can help.

Power calculation problem


How can I switch between two generator inlets?

Question: I recently pulled a permit and installed a 30A generator inlet and backfeed breaker w/ interlock. However, I actually would like to install a second inlet in an alternate location and be able to select from either one, as I have two different generators and they are kept in different locations on my property.
To do this safely, I need a switch that can cut off one inlet when the other is engaged; otherwise, the inlet would be live when the other one is being fed by a generator.
To do this to code, do I need to switch neutral as well as both hots? If so, where can I get a 30A triple poll, double throw switch? Leviton and the like only seem to make DPDT switches (which would be fine if I only need to switch the hots).
Comment: While [interlocks are code compliant](http://diy.stackexchange.com/a/25398/33). In my opinion, they are not the safest or best option available.
Comment: @Tester101 Perhaps if you don't know what you're doing as a user, but otherwise not overloading the generator is trivial. Also I wired in a current meter along with it in order to make sure I stay within a safe margin. I have way too many circuits to have to decide on only a handful to move over to a transfer switch.
Comment: The problem with installing anything that requires the user to know what he's doing (especially when used during stressful/emergency events like a power outage) is that in a residential situation, it's hard to ensure that the knowledgeable user is always the one to do it -- you may be away from home (or sick in bed) and it may be your wife, child,  or house sitter throwing the switch.
Answer: You're looking up parts with the wrong terms. What you want is a transfer switch. You don't need the kind that includes breakers, etc., since you're using an interlock; just a simple transfer switch.
In a transfer switch where the neutrals are bonded or overlapped during switching, the advantage is reduced arcing and transients during switching. The disadvantage of this situation is that the transfer switch can not protect your genset and other electrical system components from wiring problems, such as a neutral/hot reversal sending current along the neutral.
In your case, since you're using an interlock you will already be cutting off the electricity completely anyway before switching and starting your generator; neutral continuity is not needed. So you should use a transfer switch that switches the neutral along with the hots.
See http://ecmweb.com/content/switching-neutral-whats-controversy for more details.
Comment: I didn't think of this as a transfer switch application, but you're absolutely right.
Comment: There's another question you should see, too. I couldn't find it until just now. http://diy.stackexchange.com/questions/8682/how-can-i-get-a-standby-generator-with-gfi-to-work-with-a-2-pole-transfer-switch?rq=1
Comment: I've looked around but can't find transfer switches without breakers in them. Can you help point me in a good direction?
Comment: I was also thinking -- why *wouldn't* a DPDT toggle switch such as http://www.leviton.com/OA_HTML/ProductDetail.jsp?partnumber=1288-W&section=41455&minisite=10251 work? I was concerned earlier with switching neutral but it now occurs to me that the way the interlock kit is wired, neutral is not switched even at the panel anyway.


What is the resolution order for items?

Question: There has been a lot of discussion in games about the correct order that events are resolved in regards to items.
Specifically, what is the precedence for Using an item, Having it stolen from you, Having it stolen by a killer, or Passing it to someone else?
Hopefully this should then allow answers to: "Can I use an item before it gets stolen from me?" and "If I try to pass an item and someone tries to steal it from me, who out of the pass-target or the thief gets the item?"
Answer: It was recently confirmed by Kirschstein (one of the moderators) on Discord:

Use
Steal
Kill
Pass

"Can I use an item before it gets stolen from me?" -> Yes
"If I try to pass an item and someone tries to steal it from me, who out of the pass-target or the thief gets the item?" -> The thief will get the item.
Further clarification was also added: If two thieves (or thief + potion) are used on the same target that is also the target of a kill, the thefts will bounce and the killer would get the item.

What is the resolution order for items?


Python pickle weird behavior on using different file modes for the file where pickled object is stored

Question: I am pickling a dictionary with the following statement:
pickle.dump(paramsToSave, open('testvars.txt','wb'))

I am unpickling with the following:
vars = pickle.load(open('testvars.txt','rb'))

Now when I use file mode 'w' in pickling and 'r' in unpickling, it is fine. Same for wb-rb, wb-r combinations.
But when I use w-rb combination, I get an error:
ValueError: insecure string pickle

Can someone please explain this behavior? And which is the right file mode combination to use?
Edit: I am using Python 2.6.6 on Windows 7
Comment: Presumably you are on Windows or another platform with a standard line separator convention other than `\n`.
Comment: What Python version are you using? Python 3 switched the default protocol being used.
Answer: First of all, you should always use binary mode for pickle files. On platforms where this matters (e.g. Windows), opening a file in text mode means that all line terminators are translated; \n becomes \r\n on write, and \r\n becomes \n again on reading.
On Python 2 the default pickle protocol is ASCII-based, but that doesn't mean that the contents of the values are not going to be affected. For your w -> rb example, most likely a value with a \n embedded was written out as \r\n, then read as \r\n meaning the length of the data changed, triggering the error message because certain quoting expectations were not met (the closing quote was not read because the string length changed).
The fact that you didn't run into this specific exception with the other non-binary combinations does not mean you didn't have problems anyway. Values could still end up being corrupted.
All other protocol versions are binary based, meaning you can break the protocol in more creative ways still.


Possible to show two slides in the carousel at a time?

Question: I just started learning about Angular.js and I'm using the Carousel control in Angular-ui. Is it possible to display two slides at the same time instead of one?
I want to display the images like these -
< image 1 image 2 >
then
< image 3 image 4 >
then
< image 5 image 6 >

Here's a sample -
http://plnkr.co/edit/BnErmMDl8nPvXPrw3ULu?p=preview
Answer: You can group the images together and ng-repeat over those grouped images instead.  Aside from some needed styling fixes, here's how:
http://plnkr.co/edit/5JFeZgTup7abIsjxOeqi?p=preview
HTML:
<carousel interval="myInterval">
  <slide ng-repeat="slideCollection in groupedSlides" active="slide.active">

  </slide>
</carousel>

JavaScript:
$scope.$watch('slides', function(values) {
  var i, a = [], b;

  for (i = 0; i < $scope.slides.length; i += 2) {
    b = { image1: $scope.slides[i] };

    if ($scope.slides[i + 1]) {
      b.image2 = $scope.slides[i + 1];
    }

    a.push(b);
  }

  $scope.groupedSlides = a;
}, true);

Comment: You should be able to use the `:hover` selector in css to add the border, so like `img:hover { border: 1px solid red; }`.  And you don't need to download the bootstrap.css and modify it, you can edit your own css file locally and include it after bootstrap.css to overwrite whatever you want.
Comment: You sir, are awesome! It worked like a charm. I'm liking Angular so far. Quick question - how do I add a border when I hover over an image? Just use CSS? If I needed to tweak the existing CSS, do I need to download the bootstrap.css locally, and then make the changes (no more CDN)?
Comment: Will this answer help in general.. Like if i have n number of images in an array. As of now this answer shows just for 2 images(static). What if it is dynamic?
Comment: What if I need to display 4 slides?
Comment: @Serge add 4 <`img>` tags and change the logic inside the `$watch`


How to make md-select 100% width?

Question: I use last version angular. This is material design code:
<md-grid-tile>
 <md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food">
 </md-select>
</md-grid-tile>

I try to set width: 100%for `md-select. But it does not work.
Comment: See this [answer](https://stackoverflow.com/a/45356181/5556177)
Answer: This will solve your problem.
<md-grid-tile>
    <md-select placeholder="Favorite food"
               [(ngModel)]="selectedValue"
               name="food"
               [style.width]="'100%'">
    </md-select>
</md-grid-tile>

Comment: It does not work. I have empty/blank padding around select list
Comment: well it does, see tile 4, 8 and 9 in this plunk: https://plnkr.co/edit/rGahhd9yy62sQbDJpbED?p=preview
Comment: Yes, set please background and alsi I need height 100%. After margin: 5px;
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/150964/discussion-between-faisal-and-daniel).
Comment: Okay, then how to set margin?
Comment: Put the md-select inside a span. See tile 9 in the updated code on plunker and accept the answer if it helped you. Closing this discussion here.

How to make md-select 100% width?


Removing multi valued data from a table after normalization

Question: After going through guides for normalization, I have tables in what I believe are 4th normal form here below. These attributes were decomposed from one large table (student number, club, club cost, nickname etc). The problem is I still have repeating rows in STUDENT_CLUB_LIST and STUDENT_NAMES, and I get an error for repeating the primary key or entering redundant data.
From tutorials I've seen, repeating the primary key row is allowed even up to 4NF (for example if student number 100 attends two clubs, there would be two rows) so what am I missing? How can I avoid repeating multivalued attributes if I've already decomposed the attributes into small tables with unique keys.
CREATE TABLE STUDENT_CLUB_LIST(

        StudentNumber       Int         NOT NULL,
        Club                Char(25)    NOT NULL,

        CONSTRAINT      StudentNumberPK     PRIMARY KEY (StudentNumber)

                        );

CREATE TABLE CLUB_COST(

        Club            Char(25)            NOT NULL,
        ClubCost        Int                 NOT NULL,

        CONSTRAINT      ClubPK              PRIMARY KEY(Club)

                        );

CREATE TABLE STUDENT_NAMES(

        StudentNumber       Int         NOT NULL,
        Nickname            Char(25)    NOT NULL,

        CONSTRAINT          StudentNamesPK      PRIMARY KEY(StudentNumber)
);

Comment: Right now you are just asking for us to rewrite a textbook with a bespoke tutorial & you have shown no research or other effort at actually answering the question you pose. Please see [ask], hits googling 'stackexchange homework' & the voting arrow mouseover texts. Show the steps of your work following a textbook or other authoritative reference with justification & ask 1 specific researched non-duplicate question re the first place you are stuck. Quote the definitions, theorems, algorithms & heuristics you are relying on. All the steps are also SO faqs
Comment: What is your exact question--input & goal? PS There are many misconceptions & confusions here. "repeating the primary key row" makes no sense. "multivalued attributes" doesn't mean "repeating [sub]rows" & neither is a problem per se. 4NF is about multivalued dependencies. CKs matter, PKs don't. PS Normalizing a large table is not a good way to start designing. PS Follow a published academic textbook on information modelling, the relational model & DB design & querying. (Manuals for languages & tools to record & use designs are not such textbooks.) (Nor are wiki articles or web posts.)
Answer: You need to allow multiple rows per StudentNumber in STUDENT_CLUB_LIST, as well as multiple rows per Club. This is the way the many-to-many table works. Each pairing of student and club gets its own row.
You do this by making a compound primary key consisting of both columns that reference the other tables. That way each pairing of a given student in a given club is stored just once. But a given student may belong to multiple clubs, and a given club may have multiple student members.
CREATE TABLE STUDENT_CLUB_LIST(

    StudentNumber       Int         NOT NULL,
    Club                Char(25)    NOT NULL,

    PRIMARY KEY (StudentNumber, Club)

);

Comment: You make a compound key. Other factors might determine whether it, or a surrogate, were PRIMARY - or indeed UNIQUE


Ubuntu Server 12.04 start fails after update

Question: I did an system update on Ubuntu Server 12.04, which requested a reboot.
Since that, the system never reaches the login. It hangs on:
mount: mounting /dev on /root/dev failed: No such file or directory
done.
mount: mounting /sys on /root/sys failed: No such file or directory
mount: mounting /proc on /root/proc failed: No such file or directory
Target filesystem doesn't have requested /sbin/init.
No init found. Try passing init= bootarg.

BusyBox v1.18.5 (Ubuntu 1:1.18.5-1ubuntu4) build-in shell (ash)
Enter 'help' for a list of build-in commands.

(initramfs)

I tried already to repair it using a live system:

Mounting the filesystems (/boot ext, / btrfs)
fsck ran without problems.
/etc/fstab seems to be OK.
apt update/upgrade on chroot succeed.

Now, I have no more ideas.
Comment: See the answers here: [boot up fails. drops to initramfs prompt 12.04](http://askubuntu.com/questions/137655/boot-up-fails-drops-to-initramfs-prompt-12-04) and [Ubuntu - Boot failure ending with initramfs prompt](http://bernaerts.dyndns.org/linux/232-ubuntu-boot-failure-initramfs)
Answer: I had the same issue when I updated my system. The problem was that it updated the kernel from 3.2.0-48 to 3.5.0-34. I was able to boot using the new kernel by adding rootdelay=90 kernel option, but the system was unstable. So I uninstalled that kernel image and installed the linux-image-generic package, which in Ubuntu 12.04 is 3.2.0-48.
In the grub menu try selecting previous Linux versions if you can, and select the oldest kernel version, which might be 3.2.0-48. If you boot up successfully, open up a terminal and type in sudo apt-get remove --purge linux-image-3.5.0-34-generic this will also update grub.
If the above doesn't work, boot from a live CD or USB and install boot-repair. Once install, run boot-repair and select advanced options. Go over to the GRUB Options tab and check Purge kernels then reinstall last kernel.
If none of those work, then your probably have file system issues, and might need to risk fsck.ext3 -f /dev/(root partition) from a live CD, preferably alternate install.


Join two or more arrays of arrays

Question: Suppose I have two arrays like the following:
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));

And I want a result like this:
$arr4 =  array("first", "second", "third", "fourth", "fifth", "sixth", "seventh","eighth", "ninth","tenth", "eleventh" );

How to do that? in PHP
Comment: @JackManey your link is not what he's looking for.
Comment: [Documentation. Read it. Love it. Use it.](http://php.net/manual/en/function.array-push.php)
Comment: [http://stackoverflow.com/questions/2184997/combine-two-or-more-multi-dimensional-arrays-in-php](http://stackoverflow.com/questions/2184997/combine-two-or-more-multi-dimensional-arrays-in-php)
Answer: What you want to is flatten and combine the arrays. There's a nice function for flattening in the comments in the PHP manual of array_values, http://www.php.net/manual/en/function.array-values.php#104184
Here's the code:
/**
 * Flattens an array, or returns FALSE on fail.
 */
function array_flatten($array) {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten($value));
    }
    else {
      $result[$key] = $value;
    }
  }
  return $result;
}

Just run this on array($arr2, $arr3).
Answer: function flatten($ar,&$res) {
  if (is_array($ar))
    foreach ($ar as $e) flatten($e,$res);
  else
    $res[]=$ar;
}

$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));

$arr4=array();
flatten($arr2,$arr4);
flatten($arr3,$arr4);

Join two or more arrays of arrays