text:
Q: How to make a div fit 100% of a mobile screen When a user clicks the "burger nav" in the mobile version, whatever item they select, a popup will appear and my problem is that the popup doesn't fit there whole screen and scrolling. When you scroll down, it reveals a portion that isn't apart of the popup. It works fine when the users phone is position vertically because I added "height: 100vh" to the popup in the media query. But when the users phone is position horizontally, it doesn't work. I Tried everything and I cannot fix it. I added "position: fixed" which seemed to work but when you scroll down it would be there but does away when you keep scrolling which is not what I want.Ibasically want for when a user scrolls down on the mobile, for the popup to be responsive and stay 100% height. Here is my code which is uploaded to a code pen.
http://codepen.io/anon/pen/dWyKaE

CSS WHEN HORIZONTAL
@media screen and (max-width: 667px) {
    #burger-nav{
        display: block;
        width: 100%;
        height: 40px;
        background: url(burgerlogo.png) no-repeat 98% center;
        background-size: 30px 30px;
         background-color: white;

    }
    #burger-nav.show{
        background-color: #f97072;
    }
     #nav-menu{
        background-color: white;
        margin: 0;
        padding:0;
        width: 100%;
        height:auto;
        overflow: hidden;
         display: none;

    }
    #nav-menu.open{
        display: block;
        z-index: 100;
        position: absolute;
    }
    #nav-menu li{
        float: none;
        padding: 10px;
        position: relative;
        text-align: right;
        top:0;
        left:0;
        cursor: pointer;
        border-bottom: 0.1px solid #f8f9fb;
        display: block;
        font-weight: bold;

    }
    #nav-menu li:hover {
        background-color: #f8f9fb;
    }
    #name-div{
        position: absolute;
        top: 8%;
        left: 0%;
        z-index: 10;
        -webkit-user-select: none;
        -ms-user-select: none;
        -moz-user-select: none;
        -o-user-select: none;

            }
    #name.show{
        position: relative;
        bottom: 40px;
    }
        .bubbles li:nth-child(1) {
                top:100px;
                left: 300px;
            }
        .bubbles li:nth-child(2) {
                left: 100px;
                top:100px;

            }
    .bubbles li:nth-child(3) {
                left: 200px;
                top:0px;

            }
    .bubbles li:nth-child(4) {
                left: 150px;
                top:200px;
            }
    .bubbles li:nth-child(5) {
                left: 250px;
                top:200px;
            }
    .bubbles li:nth-child(6) {
                left: 250px;
                top:200px;
            }
         #job-popup{
                width: 100%;
                height: 100%;
             margin: 0;
             padding: 0;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

           #x-div1{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div1:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon1{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #job-box1{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #job-text1{
            text-align: center;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Job CSS --------------------------------------------------------------------------------------- */
        #contact-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

            #x-div2{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div2:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon2{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #contact-box2{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #contact-text2{
            text-align: center;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Contact CSS --------------------------------------------------------------------------------------- */

    #press-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

            #x-div3{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div3:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon3{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #press-box3{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #press-text3{
            text-align: center;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Legal CSS --------------------------------------------------------------------------------------- */
    #legal-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

            #x-div4{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div4:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon4{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #legal-box4{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #legal-text4{
            text-align: center;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Legal CSS ---------------------------------------------------------------------------------------  */
    #support-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

            #x-div5{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div5:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon5{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #support-box5{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #support-text5{
            text-align: center;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
}

CSS WHEN VERTICAL
@media screen and (max-width: 375px) {
    #burger-nav{
        display: block;
        width: 100%;
        height: 40px;
        background: url(burgerlogo.png) no-repeat 98% center;
        background-size: 30px 30px;
         background-color: white;

    }
    #burger-nav.show{
        background-color: #f97072;
    }
     #nav-menu{
        background-color: white;
        margin: 0;
        padding:0;
        width: 100%;
        height:auto;
        overflow: hidden;
         display: none;

    }
    #nav-menu.open{
        display: block;
        z-index: 100;
        position: absolute;
    }
    #nav-menu li{
        float: none;
        padding: 10px;
        position: relative;
        text-align: right;
        top:0;
        left:0;
        cursor: pointer;
        border-bottom: 0.1px solid #f8f9fb;
        display: block;
        font-weight: bold;

    }
    #nav-menu li:hover {
        background-color: #f8f9fb;
    }
    #name-div{
        position: absolute;
        top: 30%;
        left: 0%;
        z-index: 10;
        -webkit-user-select: none;
        -ms-user-select: none;
        -moz-user-select: none;
        -o-user-select: none;

            }
    #name{
        font-size: 4em;
    }
    #name.show{
        position: relative;
        bottom: 40px;
    }
        .bubbles li:nth-child(1) {
                top:100px;
                left: 300px;
            }
        .bubbles li:nth-child(2) {
                left: 100px;
                top:400px;

            }
    .bubbles li:nth-child(3) {
                left: 200px;
                top:0px;

            }
    .bubbles li:nth-child(4) {
                left: 150px;
                top:200px;
            }
    .bubbles li:nth-child(5) {
                left: 250px;
                top:200px;
            }
    .bubbles li:nth-child(6) {
                left: 250px;
                top:200px;
            }
         #job-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

            #x-div1{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div1:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon1{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #job-box1{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #job-text1{
            text-align: center;
            display: none;
            position: relative;
            top:6%;
            left:0;
            font-size: 1.2em;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Job CSS --------------------------------------------------------------------------------------- */
        #contact-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

            #x-div2{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div2:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon2{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #contact-box2{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #contact-text2{
            text-align: center;
            display: none;
            position: relative;
            top:6%;
            left:0;
            font-size: 1.2em;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Contact CSS --------------------------------------------------------------------------------------- */

    #press-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

           #x-div3{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div3:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon3{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #press-box3{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #press-text3{
            text-align: center;
            display: none;
            position: relative;
            top:6%;
            left:0;
            font-size: 1.2em;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Legal CSS --------------------------------------------------------------------------------------- */
    #legal-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

           #x-div4{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div4:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon4{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #legal-box4{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #legal-text4{
            text-align: center;
            display: none;
            position: relative;
            top:6%;
            left:0;
            font-size: 1.2em;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
/* End of Legal CSS ---------------------------------------------------------------------------------------  */
    #support-popup{
                width: 100%;
                height: 100%;
                position:absolute;
                top:0;
                left:0;
                z-index: 102;
                background: hsla(0,0%,97%,.7);
                display: none;
                }

           #x-div5{
                width: 70px;
                height: 40px;
                border-radius: 100%;
                 background: #1e1e1e;
                opacity: 0.3;
                border-radius: 0 25px 25px 0;
                position: relative;
                left:0px;
                top:1%;
                z-index: 1000;
                cursor: pointer;
                display: none;
            }
            #x-div5:hover{
                background-color: rgb(218, 85, 47);
            }
        #xicon5{
            color: white;
            font-size: 1.2em;
            position: relative;
            top:10px;
            left: 0;
            z-index: 1002;
            bottom: 20px;
            font-weight: bold;
            display: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
        }
        #support-box5{
            width: 100%;
            height: 100%;
            position: absolute;
            left:0;
            top:0;
            padding-right: 0;
            background-color: white;
            word-wrap: break-word;
            display: none;

        }
        #support-text5{
            text-align: center;
            display: none;
            position: relative;
            top:6%;
            left:0;
            font-size: 1.2em;
            -webkit-user-select: none;
            -ms-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;

        }
}

A: You can use the vh and vw units to do this. These units will size the content in relation to the size of the viewport. For example:
div {
    width: 100vw;
    height: 100vh;
}

If the vh and vw fields are not supported on the browser your working with, you will need to do it in javascript:
$(document).ready(function(){
    resizeDiv();
});

window.onresize = function(event) {
    resizeDiv();
}

function resizeDiv() {
    vpw = $(window).width();
    vph = $(window).height();
    $('#somediv').css({'height': vph + 'px'});
}

*You can check browser support here.


text:
Q: Coherency measurement using Sentinel data on Google Earth Engine I am new to GEE. I want to implement the following equation shown in fig on GEE using Sentinel 1 two images.
The first Sentinel 1 image amplitude is |u1| and the secondary image amplitude is |u2|, and E is the expected value of some random variable. Here, * is complex conjugate.
How do I implement the below syntax in Google Earth Engine?

A: Can't be done in Earth Engine; the Sentinel-1 data is already processed to GRD, and no longer contains the complex components.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Не знаю,как придумать проверку на не смежность вершин public void findDisconnectedNodes(int key)//key-это "вершина"
{
    List<int> disnodes = new List<int>();
    for (int i = 0; i < vertexes.Count; i++)//vertexes - список вершин
    {
        //neighbours - список смежных вершин с данной вершиной
        for (int j = 0; j < vertexes[i].neighbours.Count; j++)
        {
            //собственно здесь проверка должна быть)
        }
    }
    Console.Write("Nodes: ");
    foreach (var i in disnodes.Distinct())
    {
        Console.Write(i + "," + " ");
    }
}

A: Из всех узлов вам нужен те, которые не равны вашему ключу и у которых в соседях нет вашего ключа
public void findDisconnectedNodes(string key, List<Node> vertexes)  {
    var disnodes = vertexes.Where(x=> x.name != key && !x.neighbours.Contains(key))
                           .Select(x=>x.name).ToArray();

    Console.Write("Nodes: ");
    foreach (var i in disnodes.Distinct())
    {
        Console.Write(i + "," + " ");
    }
}

Но как общая рекомендация - пересмотрите ваши типы данных. Ключи лучше хранить как целые числа, а не строки.


text:
Q: Date in X-Axis (Matplotlib Plot) I am trying to plot a graph based on the data from Yahoo on Google Finance.
Just starting to learn data visualisation on Pandas, Matplotlib on Jupyter Notebook.
google['Date'] = pd.to_datetime(google['Date'])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(google['Date'], google['Rolling Mean'], color = (0,0,0), linewidth = 4, alpha = .9, label = 'Smoothed');
ax.plot(google['Date'], google['Open'], color = (1,0,0), label = 'Original');
ax.set_title('Original and Smoothed Price')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.legend(loc='lower right')

Converted the date to pd.datetime but the graph showed Year-Month. How can I make it show only Year on the X-axis so that it doesn't look as crowded
I have attached an image below.
My Plot
DataFrame

A: You can use matplotlib.dates:
import matplotlib.dates as mdates

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

fig = plt.figure(figsize=(16,4))
ax = fig.add_subplot(111)

ax.plot(google['Date'], google['Rolling Mean'], color = (0,0,0), linewidth = 4, alpha = .9, label = 'Smoothed');
ax.plot(google['Date'], google['Open'], color = (1,0,0), label = 'Original');
ax.set_title('Original and Smoothed Price')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.legend(loc='lower right')

## Format the X-axis
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)

To get what you want (don't mind the data, I randomly generated some to plot):

Reference : https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/date.html


text:
Q: UITableView Setting some cells as "unselectable" How can I set the UITableView's cell property to be unselectable? I don't want to see that blue selection box when the user taps on the cell.

A: Had this problem, too, tried everything already mentioned. The final trick, which got rid of the "blue flash" at selecting a table cell was adding this line:
self.myTableView.allowsSelection = NO;

Not sure whether it was this one line or everything combined, but as total grand result I get no more blue selection or even the blue flash. Happy!

A: Set cell.userInteractionEnabled = NO;

A: using IB is also an elegant way:

A: Apple says that the first thing you should do in didSelectRowAtIndexPath is to deselect the row
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:NO];

Then you can change the AccessoryType to be a checkmark, or none, etc. So when you enter didSelectRowAtIndexPath you could deselect the row, and if its not meant to be selected, simply don't check that row.
Table View Programming Guide

A: Another way is to add a couple category methods to UITableViewCell. I like this better than Sebastians (also good) answer because the way I'm building my table. I thought it might be helpful to someone else.
- (void)setSelectable:(BOOL)enabled {
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    [self setUserInteractionEnabled:enabled];
}

- (BOOL)isSelectable {
    BOOL disabled = [self selectionStyle]==UITableViewCellSelectionStyleNone &&
                     [self isUserInteractionEnabled];
    return ! disabled;
}

A: Swift 4:
You can prevent selection and highlighting by using the UITableViewDelegate: shouldHighlightRowAt
This answer assumes you have a custom cell created named: CustomTableViewCell
 And that you created a boolean inside that custom cell named: isSelectable
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
    if cell.isSelectable == false {
        return false
    } else {
        return true
    }
}

This is the Swift version of Sebastian Celis's objc answer.

A: To Prevent Row Selection
To completely prevent selection of the UITableViewCell, have your UITableViewDelegate implement tableView:willSelectRowAtIndexPath:. From that method you can return nil if you do not want the row to be selected.
- (NSIndexPath *)tableView:(UITableView *)tv willSelectRowAtIndexPath:(NSIndexPath *)path
{
    // Determine if row is selectable based on the NSIndexPath.

    if (rowIsSelectable) {
        return path;
    }
    return nil;
}

This prevents the row from being selected and tableView:didSelectRowAtIndexPath: from being called. Note, however, that this does not prevent the row from being highlighted.
To Prevent Row Highlighting
If you would like to prevent the row from being visually highlighted on touch, you can ensure that the cell's selectionStyle is set to UITableViewCellSelectionStyleNone, or preferably you can have your UITableViewDelegate implement tableView:shouldHighlightRowAtIndexPath: as follows:
- (BOOL)tableView:(UITableView *)tv shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Determine if row is selectable based on the NSIndexPath.

    return rowIsSelectable;
}

A: Swift 5
cell.isUserInteractionEnabled = false

A: use this:
cell.selectionStyle = UITableViewCellSelectionStyleNone;

A: Set the table cell's selectionStyle property to UITableViewCellSelectionStyleNone.  That should prevent it from highlighting, and you can also check that property in your tableView:didSelectRowAtIndexPath:.

A: For iOS 6+ only.
You can implement the method
tableView:shouldHighlightRowAtIndexPath: in your delegate.
Read more here : http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html

A: If you have designed your cell in Interface Builder, you can do this by removing the checkbox from 'User Interaction Enabled' for the tableViewCell.

A: There is another simple way to avoid the selection appearing as blue.
Select a cell you don't want to appear as blue.
Then select the attributes inspector (the shield icon next to the ruler icon on the properties view on the side).
Then change the 'Selection' field from 'Blue' to 'None'.
Note, presumably this is still selecting, it will just not appear as selected if all you want is to avoid the UI effect.

A: To make certain row unselected you have to make some changes in two methods of UITableView delegate.
In the method below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

after allocation of the cell, write the code below
if(indexPath.row == someCellNumber) cell.selectionStyle =UITableViewCellSelectionStyleNone;

The above code will prevent highlighting the cell, if somehow user tries to selects.
in this delegate method below
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.row == someCellNumber) return;

    //for other cells write the code below...
}

if you don't write if(indexPath.row == someCellNumber) return; row will still be selected and there is a chance of app crash

A: Use tableView: willDisplayCell: forRowAtIndexPath: instead of tableView: didSelectRowAtIndexPath: to get rid of the flash that appears first time you touch the cell.
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}

A: Swift 4:
In the cell class:
selectionStyle = .none


text:
Q: Qt Designer crashes with custom plugin Created custom designer plugin similar to Container Extension Example. After some modifications with QDesignerCustomWidgetInterface, QDesignerContainerExtension and QExtensionFactory classes and adding following methods to my container:
Q_OBJECT
  Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex)
  Q_PROPERTY(QString pageTitle READ pageTitle WRITE setPageTitle STORED false)

public:
  WidgetBox(QWidget *parent = 0);

  int count() const { return mTreeWidget->topLevelItemCount(); }
  QWidget* widget(int index) const;
  QString pageTitle() const;

public slots:
  void setCurrentIndex(int index);

  void addPage(QWidget *widget);
  void insertPage(int index, QWidget *widget);
  void removePage(int index);
  int currentIndex() const { return mTreeWidget->currentIndex().row(); }

  void setPageTitle(QString const &newTitle);

protected:
  QTreeWidgetItem * addCategory(QString pageName);
  QTreeWidgetItem * insertCategory(int index, QString pageName);

  PageButton *categoryButton(int index) const;

  void createContainerWidget(QTreeWidgetItem* page, QWidget *widget);
  void createCategoryButton(QTreeWidgetItem* page, QString pageName);

signals:
    void currentIndexChanged(int index);
    void pageTitleChanged(const QString &title);

Qt designer started to crash on start with my plugin. Any way do debug plugin (extension) and found the cause? Plugin build in release mode with same Qt and VS C++ versions as Qt Designer and Creator - Based on Qt 5.5.1 (MSVC 2013, 32 bit).
P.S. So method is following: commented out extension and factory classes - still crashes, sequentaly commented/uncommented methods in my widget class: problem appears in
Q_PROPERTY(QString pageTitle READ pageTitle WRITE setPageTitle STORED false)
and methods pageTitle and setPageTitle for current page when no pages available. Need think what to set/output here when no pages were added. Or add at least 1 page by default.
Now Qt Designer crashes on adding widget to a form. Will continue searching the cause.

A: Added index check to widget() method, works fine for now. So need to check all methods that Qt Designer can call for potential crash (for example, with no pages in this case).


text:
Q: how to use exec() to run a c program from another c program i've been trying to use execvp to run a c program but it always seems to fail.
from main.c
int main() {
char* args[] = {"2", "1"};
    if(execvp("trial.c", args) == -1) {
        printf("\nfailed connection\n");
    }

from trial.c
int main(int argc, char** argv){
printf("working");
return 1;
}

I think i tried every way to possibly represent that file location in the exec() and it always results in "failed connection".

A: The first parameter to execvp expects the name of an executable file.  What you've passed it is the name of a source file.  You need to first compile trial.c, then pass the name of the compiled executable to execvp.
Regarding the second parameter to execvp, the last element in the array must be NULL.  That's how it knows it reached the end of the list.  Also,  by convention the first parameter to a program is the name of the program itself.
So first compile trial.c:
gcc -g -Wall -Wextra -o trial trial.c

Then modify how to call it in main.c:
int main() {
    char* args[] = { "trial", "2", "1", NULL };
    if(execvp("trial", args) == -1) {
        printf("\nfailed connection\n");
    return 1;
}

A: First argument for execvp is path to executable.
You need to build the executable for trial.c and pass the path of the executable to execvp.
if(execvp("---path to executable---/ExecTrial", args) == -1) {
    printf("\nfailed connection\n");
}

If you don't pass the executable path, execvp will search the executable in the colon-separated list of directory pathnames specified in the
       PATH environment variable.

A: If you're trying to call execvp() on a source file then this is not what this function does. The first argument is expected to be a path of an executable. If you want to run the program which trial.c is the source of, you should build (compile and such) it first. For example like this:
$ gcc -o trial trial.c

Then call execvp() on the your newly created executable instead of the source file:
if(execvp("trial", args) == -1) { //...

A: trial.c is not a valid executable file.  C is not a scripting or interpreted language; you cannot run C source files directly.  A C program must be compiled and linked into an executable.


text:
Q: MySQL select query performance issue I'm using a table to do login, the table has a record of 2500. when i try to login it takes nearly 30-40 seconds to load. I'm using PHP and MySQL.I need to make the sql query faster to check the data. Solutions are welcomed thanks in advance pls help me out

A: When locating the causes of problems of performance issues, there are many things to consider in the your application stack:

*

*Database: Indexes, Joins, Query Formation

*Network in between: Routing issues, Bandwith, connectivity speed

*Code: Check if your code structure is not creating unecessary delays, forexample some people have their validations span over client and server both in a single method which increases method lifetime longer. Try to put validation's core logic on database side like in stored procedures. Try to use methods with lesser overheads.

A: You should have included your query so we can examine it.
Don't pull all your records (e.g. don't use Select * from users) and then loop through to find a match.
Instead, use WHERE clause to limit your records to (i.e. one row). That is
SELECT col1,col2,.. FROM Users
WHERE username='username' AND password='password'
You can try that and see the performance...


text:
Q: applications of (topological and algebraic) commutative diagrams in organic synthesis In algebraic topology, there are a lot of commutative diagrams and commutative diagrams up to homotopy. Different ways of compositions of maps in a commutative diagram are equal or homotopy equivalent.
An example of commutative diagrams in algebraic topology
In organic synthesis, there are some diagrams consisting of
synthetic routes. Different ways of chemical reactions produces the same product.
An example of diagrams of synthetic routes
Question:   are there any really useful research topics about the application of commutative diagrams in mathematics into organic synthesis?

A: John Baez's has recently worked on something related: he modeled Petri nets and chemical reaction inside the framework of category theory.
His work can be found on this link.
Hope this address your question.


text:
Q: Getting rid of random syntax highlighting I'm having a problem with Eclipse. It randomly highlights code in grey, usually as I type something. It doesn't always appear when I type, and goes away at random times too. It's really annoying. I can't seem to figure out what the color is attached to in preferences Either.
I have the Web package installed. Here's an example of the highlighting:

A: The highlighting you're seeing here is related to variable instances. You can disable its color highlighting from the preferences screen as a permanent solution, but I discourage that as highlighting instances is invaluable!
Instead, you can fairly easily resolve this each time by placing your caret on a different variable. It may require an intermediate save.
I've seen this sort of odd behavior fairly rarely; perhaps you should also make sure you're using recent version of Eclipse.


text:
Q: what is the best way to import high frequency updating data in python? I am trying to import some data from web, where the data is being updated every 1 second.
However, the problem is that when I try to soup this data, all data are not imported. When the data is not being updated, my code works well. But when the data is being updated(from 8 a.m. to 12 a.m.), some of those are not imported properly.
It's a table with 500 rows and 12 columns, where each column is stored in a separate variable. It is expected that the variables have the same length. This is true when data are not updated, but when I run the code from 8 a.m. to 12 a.m.(when data are being updated) the variables do not have the same length. Any advice or recommendation would be greatly appreciated.
I am using selenium to open the web page and execute some commands to read data with beautiful-soup.

A: Since there is no code and I don't know the website, here are some general thoughts:

*

*As Maxime suggested - Is there an API you could use?

*Can you ditch selenium? Using something like requests might be faster and will help you get the timings right.

*Is the stuff you want to scrape already loaded when you try to save it?

*Is your internet connection keeping up with the amount of requests you sent?


text:
Q: Swapping setTimeout to setinterval, Can anyone help me solve this issue Im currently in the middle of building test websites to help me understand coding more and try and get a better grasp of how it all comes together.
My problem is this -
I have a section of the site with a number of quotes, they fade in then slide up out of view revealing a new quote.
This is were is I have made the mistake. I have it set perfectly so that it will cycle through all the quotes...but then stop. I would love them to repeat. I know my mistake is using the.setTimeout function instead of the setInterval code.
My question is this, is there an easy solution to swapping the code, Its taken me a good while just to wrap my head around this lol
Here is the code for you to look at. Any help would be greatly appreciated.
$(function(){
setTimeout(function()
    {
    $("#jobs_1").slideUp(800);
    }, 4000);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_2").fadeIn(400);
    }, 4800);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_2").slideUp(800);
    }, 8000);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_3").fadeIn(400);
    }, 8800);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_3").slideUp(800);
    }, 12000);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_4").fadeIn(400);
    }, 12800);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_4").slideUp(800);
    }, 16000);
});
$(function(){
setTimeout(function()
    {
    $("#jobs_1").fadeIn(400);
    }, 16800);

});

Many Thanks

A: This should help you. How it works?
You set the current job counter to 0. Then, using setInterval, every 3 seconds you run the main function, which increments the job counter. If the counter exceeds 4 (your last job), hide job 4 and fade int he first one. Otherwise slide out the previous job and fade in the new one.
$(function(){
    count = 1;

    x = setInterval(function(){
        count++;
        if( count > 4) {
            $('jobs_4').hide(function(){
                $('#jobs_1').fadeIn();
            });

            count = 1
        } else {
            $('#jobs_' + (count-1)).slideUp(function(){
                $('#jobs_' + (count-1)).fadeIn();
            });
        }

    }, 3000);
}

A: You can move all your block names into a stack and use one single function:
var blocks = ['jobs_1', 'jobs_2', 'jobs_3', 'jobs_4'];
var curentBlockIndex = 0;
setInterval(function(){
    var nextBlockIndex = curentBlockIndex + 1;
    if (nextBlockIndex >= blocks.length) nextBlockIndex = 0;
    $('#' + blocks[curentBlockIndex]).slideUp(800, function(){
        $('#' + blocks[nextBlockIndex]).fadeIn(400);
    });

    curentBlockIndex = nextBlockIndex;
}, 4000);


text:
Q: How do you make arrows in Far Cry Primal? Just got to the point in Far Cry Primal where I get to explore on my own with out real restrictions. I am starting to run low on arrows, and it appeared at first you crafted them. Is there a way to craft more after the initial creation? Or do I have to loot them now? I have looked through the available menus and could not find anything.

A: Open your weapon wheel (depending on your key mapping on PC, L1 on Playstation 4, LB on XBOX ONE), and then highlight your bow. You will then have a "Craft" option showing up. Just press the corresponding control (depending on your key mapping on PC, X on Playstation 4 and A on XBOX ONE), and you will be able to craft arrows. Each one of those will cost you one piece of wood to make.

A: On the PC:
Hold Q to bring up the weapon menu.
Then left mouse click on the bow to craft an arrow.
Click additional times to craft more arrows.
Finally, release Q to close the weapon menu.
You must first have crafted the bow in the craft menu (I), which it sounds like you have.


text:
Q: Calculating derivatives with backpropagation using Sutskever's technique In "TRAINING RECURRENT NEURAL NETWORK" by Ilya Sutskever, there's the following technique for calculating derivatives with backpropagation in feed-forward neural networks.
The network has l hidden layers, l+1 weight matrices and b+1 bias vectors.
"Forward" stage:

"Backwards" stage:

Isn't there an index problem with l+1? for example, in the forward stage we calculate z_l+1 but return z_l.
(Since this is such a major paper, I guess I'm missing something)

A: There is no problem, some of the indices start at 0 (the variable z for instance), and some start at 1 (the variable x). Follow the algorithm as laid out more carefully, try writing it out by hand explicitly for say l=4.


text:
Q: mysql table get write lock blocked while show open table shows no lock is hold for the target table(In_use = 0) While trying to get write lock of some table with:
LOCK TABLE infoTable write;

My Python3 script is blocked, and show processlist indicates the script is blocked by waiting to get the write lock:
Waiting for table metadata lock

However, the target table infoTable is not locked by any session, as the result of show open table tells:
mysql> show open tables where In_use > 0;
Empty set (0.00 sec)

So how comes that getting the write lock is blocked while the table is not locked by any other session?
Follow up1:
As suggested by comment, I tried to get lock status of transaction, no transaction is locking the target table.
mysql> SELECT * FROM INNODB_LOCK_WAITS;
Empty set, 1 warning (0.00 sec)

Additional info for your reference:
mysql version: mysql Ver 14.14 Distrib 5.7.24, for Linux (x86_64) using  EditLine wrapper
OS info: Linux 4.15.0-42-generic #45-Ubuntu SMP Thu Nov 15 19:32:57 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux


text:
Q: c# if contains AND/OR Is there a variant of this?
if (blabla.Contains("I'm a noob") | blabla.Contains("sry") | blabla.Contains("I'm a noob "+"sry"))
    {
        //stuff
    }

like:
if (blabla.Contains("I'm a noob) and/or ("sry")
    {
        //stuff
    }

Help is appreciated!

A: You can't collapse it quite as far as you asked, but you can do:
if (blabla.Contains("I'm a noob") || blabla.Contains("sry"))
{
    //stuff
}

The "and" case is handled here because a string with both would actually pass both of the statements in the "Or".

A: As far as I'm aware, there are no built-in methods to do this. But with a little LINQ and extension methods, you can create your own methods that will check to see if a string contains any or all tokens:
public static class ExtensionMethods{
    public static bool ContainsAny(this string s, params string[] tokens){
        return tokens.Any(t => s.Contains(t));
    }

    public static bool ContainsAll(this string s, params string[] tokens){
        return tokens.All(t => s.Contains(t));
    }
}

You could use it like this (remember, params arrays take a variable number of parameters, so you're not limited to just two like in my example):
var str = "this is a string";
Console.WriteLine(str.ContainsAny("this", "fake"));
Console.WriteLine(str.ContainsAny("doesn't", "exist"));
Console.WriteLine(str.ContainsAll("this", "is"));
Console.WriteLine(str.ContainsAll("this", "fake"));

Output:

True
  False
  True
  False

Edit:
For the record, LINQ is not necessary. You could just as easily write them this way:
public static class ExtensionMethods{
    public static bool ContainsAny(this string s, params string[] tokens){
        foreach(string token in tokens)
            if(s.Contains(token)) return true;
        return false;
    }

    public static bool ContainsAll(this string s, params string[] tokens){
        foreach(string token in tokens)
            if(!s.Contains(token)) return false;
        return true;
    }
}

A: var arr = new[]{"I'm a noob" ,"sry", "I'm a noob +sry"};
if(arr.Any(x => blabla.Contains(x)))
{

}

A: You can use a regex:
Regex r = new Regex("I'm a noob|sry|I'm a noob sry");
if(r.IsMatch(blabla)) {
    //TODO: do something
}

Regular expressions have other advanced features like: a* matches with the empty string, a, aa, aaa,...
The funny part is that if you "compile" the regex (for instance using new Regex("I'm a noob|sry|I'm a noob sry",RegexOptions.Compiled), C# will turn it automatically into the fastest solution mechanism possible. For instance if blabla is a 100k chars string, you will only run once over the entire string. And for instance redundant parts like I'm a noob sry will be omitted automatically.


text:
Q: How do you do natural ordering for strings with negative numbers and characters? I have a list of file names that I need to open, however, the file names contain a hyphen "-" which neither os or Windows 10 naturally recognizes as a negative number. As an example, the list itself gets imported as
['-001.000ps.csv',
 '-100.000ps.csv',
 '0000.000ps.csv',
 '0001.000ps.csv',
 '0002.000ps.csv',
 '0003.000ps.csv',
 '0003.500ps.csv',
]

where -1 preceeds -100. The positions of -1 and -100 needs to be reversed and I need to preserve the leading zeros and "ps.csv" component because the files are named this way.
I attempted some solutions I found on this stackexchange, however, what most people wanted dealt with searching for positive numbers and ordering off of that. For the natsort package, what happens is that -1 and -100 are put at the bottom of the list.
Converting these strings to ints or floats fails, I guess because ps.csv is inside of the element.
I copy pasted the solution from the blogpost referenced here and the same issue occurs. I feel like I'm missing something obvious here, why are the negative numbers not working?

A: natsort can be used to sort signed numbers like so:
fnames = [
    '-001.000ps.csv',
    '-100.000ps.csv',
    '0000.000ps.csv',
    '0001.000ps.csv',
    '0002.000ps.csv',
    '0003.000ps.csv',
    '0003.500ps.csv',
]

natsort.realsorted(fnames)
natsort.natsorted(fnames, alg=natsort.ns.REAL)

Both of these produce the same output:
['-100.000ps.csv',
 '-001.000ps.csv',
 '0000.000ps.csv',
 '0001.000ps.csv',
 '0002.000ps.csv',
 '0003.000ps.csv',
 '0003.500ps.csv']

A: You can sort the list based on the first 6 characters of names:
a = ['-001.000ps.csv',
     '-100.000ps.csv',
     '0000.000ps.csv',
     '0001.000ps.csv',
     '0002.000ps.csv',
     '0003.000ps.csv',
     '0003.500ps.csv',
]

a.sort(key=lambda x: float(x[:6]))

Result:
['-100.000ps.csv',
 '-001.000ps.csv',
 '0000.000ps.csv',
 '0001.000ps.csv',
 '0002.000ps.csv',
 '0003.000ps.csv',
 '0003.500ps.csv'
]

A: Try:
lst = [
    "-001.000ps.csv",
    "-100.000ps.csv",
    "0000.000ps.csv",
    "0001.000ps.csv",
    "0002.000ps.csv",
    "0003.000ps.csv",
    "0003.500ps.csv",
]

import re

pat = re.compile(r"^(-?\d+\.?\d*)(.*)")

out = sorted(
    lst, key=lambda x: (float((v := pat.search(x)).group(1)), v.group(2))
)
print(out)

Prints:
[
    "-100.000ps.csv",
    "-001.000ps.csv",
    "0000.000ps.csv",
    "0001.000ps.csv",
    "0002.000ps.csv",
    "0003.000ps.csv",
    "0003.500ps.csv",
]


text:
Q: .type and .click selectors in Nightmare.js I have been working with nightmare.js to run tests using mocha. This is my first time working with these framework/libraries. I am currently creating a test that loads a login page on a web app im working on and attempts to sign in. This is the code I am using as a reference
Source: https://segment.com/blog/ui-testing-with-nightmare/
  describe('Login Page', function () {
describe('given bad data', () => {
  it('should fail', done => {
    nightmare
    .goto('https://gethoodie.com/auth')
    .on('page', (type, message) => {
      if (type == 'alert') done()
    })
    .type('.login-email-input', 'notgonnawork')
    .type('.login-password-input', 'invalid password')
    .click('.login-submit')
    .wait(2000)
    .end()
    .then()
    .catch(done)
  })
})

The main question I have about tis code is the .type and .click functions. Reading the nightmare api both of these functions work like so
.type(selector[, text])
Enters the text provided into the selector element. Empty or falsey values provided for text will clear the selector's value..type(selector[, text])
I have tried to implement this functionality using the code below
describe('/ (authentication)', () => {
    it('should pass by logging into the system', done => {
        // testing urls will be `http://localhost:port/path`
        nightmare.goto('http://localhost:4000/login')
            .on('page', (type, message) => {
                if (type === 'alert') done()
            })
            .type('input[id="username"]', 'admin')
            .type('input[id="password"]', 'toetagging')
            .click('button[data-reactid=".0.0.1.3.0"]')
            .wait(2000)
            .end()
            .then()
            .catch(done)
    })
})

My main question is, what exactly is the selector and how do I get it?

A: A selector is useful to match some node(s) in the DOM. Suppose, you have the following DOM:
<div class="login-submit">
  <input id='input-login' type="text" class="fancy" name="login" />
</div>

To select the input box, you can use the following selectors, as you would with CSS:

*

*input.fancy

*.login-submit input

*#input-login

*input[name=login]
Let's say that with nightmare you wanted to type into the input box, you could use the following code:
nightmare.type('input[name=login]', 'superwoman')
Here 'input[name=login]' is a selector, and 'superwoman' is the text that you want nightmare to type inside the input line.


text:
Q: Is there a sass version of bootstrap 3 with em font sizes? I'd like to stick to Bootstrap 3 for compatibility with older browsers. However I need to have all font-sizes in em.
Has anyone seen a sass version with em font sizes instead of px?

A: This might help you but it's a dirty solution by overriding the variables with em ones:
https://gist.github.com/jasny/9731895
You can still go through the main bootstrap file and change it localy.
Without knowing the reason for you to use em for font-sizes I suggest you go with rem if your browser version list can support it.


text:
Q: Why is switch_to_window() method not working for selenium webdriver in Python? I am trying to switch to a newly opened window using the Python selenium webdriver. The code worked fine before but now it is showing error. Surprisingly, the switch_to_window() method is not being recognized by Python and has no declaration to go to.
def process_ebl_statements(self, account_number):

    current_window = self.driver.current_window_handle
    all_windows = self.driver.window_handles

    print("Current window: ", current_window)
    print("All windows: ", all_windows)
    number_of_windows = len(all_windows)
    self.driver.switch_to_window(all_windows[number_of_windows - 1])

Error details:
'WebDriver' object has no attribute 'switch_to_window'

A: This error message...
'WebDriver' object has no attribute 'switch_to_window'

...implies that the WebDriver object no more supports the attribute switch_to_window()

switch_to_window
switch_to_window was deprecated in Selenium v2.41 :

Selenium 2.41

*

*deprecating switch_to_* in favour of driver.switch_to.*

Hence you see the error.

Solution
Instead of switch_to_window you need to use switch_to.
Examples:

*

*driver.switch_to.active_element

*driver.switch_to.alert

*driver.switch_to.default_content()

*driver.switch_to.frame()

*driver.switch_to.parent_frame()

*driver.switch_to.window('main')


text:
Q: Avoid circular reference for classes I have a function that creates and returns a "Person".  The "Person" has a "Spouse" property which is, of course, another "Person".  This causes an endless recursion since the "Person" being created is always a "new" one each time the function is called.  Is there a way to use the same function (as shown below) without causing an endless loop?
public PersonModel Load(int personID)
{
    PersonModel person = new PersonModel();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = Helpers.ConnectionDB;
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "LoadPerson";
        command.Parameters.Add(new SqlParameter("@PersonID", personID));
        conn.Open();
        SqlDataReader reader = command.ExecuteReader();
        if (reader.Read())
        {
            person.PersonID = int.Parse(reader["PersonID"].ToString());
            person.FirstName = reader["FirstName"].ToString();
            person.LastName = reader["LastName"].ToString();
            person.MiddleName = reader["MiddleName"].ToString();
            person.Age = reader["Age"] != DBNull.Value ? int.Parse(reader["Age"].ToString()) : (int?)null;
            person.SpouseID = reader["SpouseID"] != DBNull.Value ? int.Parse(reader["SpouseID"].ToString()) : (int?)null;
            if (person.SpouseID != null && person.Spouse == null)
            {
                person.Spouse = this.Load(person.SpouseID.Value);
            }
        }
        conn.Close();
    }
    return person;
}

A: Use a Dictionary<Int32,PersonModel> to keep track of loaded entities:
public PersonModel Load(Dictionary<Int32,PersonModel> dict, int personId) {

    PersonModel ret;
    if( dict.TryGetValue( personId, out ret ) ) return ret;

    // load from database here, but do not call recursively just yet
    ret = new PersonModel() { ... };

    dict.Add( ret.PersonId, ret );

    ret.Spouse = this.Load( dict, person.SpouseId.Value );
}

A: I can think of a couple different options:

*

*Add an optional parameter to Load() to indicate that you should not attempt to load the spouse. This is a bit of a hack but very simple.
public PersonModel Load(int personID, bool loadSpouse = true)
{
    ...
    if (loadSpouse && person.SpouseID != null && person.Spouse == null)
    {
        person.Spouse = this.Load(person.SpouseID.Value, false);
    }
    ...

    return person;
}

*Select the spouse's properties in the stored proc by using a left outer join. This would perform better and if you ever wanted to select all employees this would be much more efficient since it would be just one database access. You would add code like this in the if statement to build the spouse object:
person.Spouse = new PersonModel()
person.Spouse.FirstName = reader["SpouseFirstName"].ToString();
...

A: Not exactly per the OPs question, but since I landed here because of the title, it might be beneficial adding a general answer to this.
So in my scenario I needed to change a property in an entire graph setting all its sub properties to any depth.
In order to ensure I don't get an instance performed twice (thus allowing StackOverflowException), I'm passing a HashSet<T> along each call, so we know to skip the performed items:
//The executed parameter needn't ever be provided externally.
static void SetState(IObject obj, State state, HashSet<IObject> executed = null)
{
  if(executed == null) executed = new HashSet<IObject>(/* provide comparer if needed*/);
  if(!executed.Add(obj)) return;

  //safe to continue walking graph
  obj.State = state;
  var props = obj.GetObjectPropertyValues().OfType<IObject>();
  foreach (var prop in props)
    SetState(obj, state, executed);
}

Note, the items must implement proper equality and GetHashCode functions, or a comparer argument should be passed to the HashSet's constructor.


text:
Q: how to list an array with cgi.parse_qs in python? import cgi

data = 'next=/contact/200/106260296&next=/contact/200/106260296&next=/contact/200/106260296&next=/contact/200/106260296&'

x = cgi.parse_qs(data)

next_list = x['next']

I am stuck with how to get all the 'next' with something like for y in x or similar.
Any ideas?

A: import cgi

data = 'next=/contact/200/106260296&next=/contact/200/106260296&next=/contact/200/106260296&next=/contact/200/106260296&'

x = cgi.parse_qs(data)

next_list = x['next']

for i in range(len(x['next'])) :
    print x['next'][i]

A: Instead of importing another library, you can use plain old list slicing:
data = 'next=/contact/200/106260296&next=/contact/200/106260296&next=/contact/200/106260296&next=/contact/200/106260296&'

next_list = [x[:-1] for x in data.split('next=')[1:]]

Now next_list looks like this: ['/contact/200/106260296', '/contact/200/106260296', '/contact/200/106260296', '/contact/200/106260296'].

A: my_list = [j.split('/')[1:] for j in
           [e.split('/contact')[1] for e in cgi.parse_qs(data)['next']]
          ]

Then you can do something like:
for x, y in my_list:
    print x, y

Output:
200 106260296
200 106260296
200 106260296
200 106260296


text:
Q: How to ssh into system connected to same network switch? I have a few systems which are connected to the same network switch. All of them are running linux / Ubuntu 18.
I want to remotely access one machine to another through ssh.
That is, if I'm operating on one of the machines, I want to remotely access the other through ssh.
How can I go about it?
Assume I do not know the ip addresses of any of the machines and just have access to one of them. I would need the steps to obtain the ip addresses of the other machine. I'm ONLY allowed to operate a single machine on the same switch which I have access to
Eg. I have Machine A, B, C, D connected to switch S. I can only have access to A and nothing else.
I came across some SO answers which advised the use of arp -a but never went beyond that.
What are my options to do something like this?

A: Assuming its a simple switch and none of the machines have firewalld or iptabables blocking all inbound traffic I would use ping, tcpping, nmap or even just ssh and use a bash script to iterate over the available ip addresses in the network.
Assuming you know the netmask you can determine the ip range of the network and work from there.
Or you can use something like this:
#!/bin/bash

for destination in `arp -a | tail +5 | awk '{print $2}'`
do
    nslookup $destination 1>/tmp/arp$$ 2>/dev/null
    if [ `wc -l /tmp/arp$$ | awk '{print $1}'` -ge 4 ]; then
        tail -2 /tmp/arp$$ | grep Address | awk '{print $2}'
    fi
done

rm /tmp/arp$$

But that's only if you know they all have static ip addresses in the same network range or have dynamic dhcp addresses in the same range. If not only way to tell could to have a look in the switch and dump the arp table there.


text:
Q: MS Access - DateSerial? I apologize in advance because I don't know how to properly ask this question.
I am using access to pull in data from several tables and want to filter/query the data by the first 10 days in any month, in any year. I understand that I could use operators to say something like:

=#1/1/2017# and <=#1/10/2017 Or >=#2/1/2017# and <=#2/10/2017# Or....on and on

But that would be a long expression. Is there something easy I could do using DateSerial, or something else?

A: Use this:
SELECT *
FROM [MyTable]
WHERE DatePart("d", [MyColumn]) > DatePart("d", #01/01/2018#)
    AND DatePart("d", [MyColumn]) < DatePart("d", #01/11/2018#)

A: The Day Function Returns a Variant (Integer) specifying a whole number between 1 and 31, inclusive, representing the day of the month.
So use that function in your query's WHERE clause ...
WHERE Day(YourDateField) BETWEEN 1 AND 10


text:
Q: Birational map between product of projective varieties What is an example of a birational morphism between $\mathbb{P}^{n} \times \mathbb{P}^{m} \rightarrow \mathbb{P}^{n+m}$?

A: The subset $\mathbb A^n\times \mathbb A^m$ is open dense  in $\mathbb P^n\times \mathbb P^m$ and the subset  $\mathbb A^{n+m}$ is open dense in $\mathbb P^n\times \mathbb P^m$.
Hence the isomorphism $\mathbb A^n\times \mathbb A^m\stackrel {\cong}{\to} \mathbb A^{n+m}$ is the required birational isomorphism.
The astonishing point is that a rational map need only be defined on a dense open subset , which explains the uneasy feeling one may have toward the preceding argument, which may look like  cheating.
The consideration of "maps" which are not defined everywhere is typical  of algebraic ( or complex analytic) geometry, as opposed to other geometric theories like  topology, differential geometry,...


text:
Q: taskkill Mysql from .ASPX -- Permission Problems? Our mysql instance occaisionally locks up during backups. Currently we must VPN into the corporate network (to obtain work I.P.), remote desktop into the server, open the task manager, and manually kill the mysqld-nt.exe process.
Instead of doing all of this we are attempting to create a simple webpage that we can log into to kill and restart the service.
The following block of code is wired up inside our new .aspx page works as I intended on my local desktop (running in VS debug mode), but doesn't do anything when pushed to the server (no errors or anything):
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("taskkill");
myProcessStartInfo.Arguments = "/IM mysqld-nt.exe /F";
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.CreateNoWindow = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
myProcess.Close();

If I run "taskkill /IM mysqld-nt.exe /F" from the command prompt on the server it kills the service.  So I think it might be a permissions issue, but I'm not positive.
Can anyone spot something wrong with the code block above, or tell me how to adjust the permissions so .Net can stop/start this process?
Thanks for the help,
Sam

A: It sounds like your page is probably running as the IUSR_MACHINE account (with limited permissions).
On your development machine, it's your account which starts the dev web server process, and you're probably logged in as a local administrator.
Make IIS ask you for a password, and turn on impersonation Then try logging in as an administrator (or some account with privileges).

A: This might be late, but did u check the network port(s) on the remote machine?

A: Wasn't able to figure out a work around to get it to work via ASP.net. I'm pretty sure it is a permission issue of some sort. Ended up using a batch file that is triggered by Scheduled Tasks to stop/start/backup MySQL.


text:
Q: Structre of R in QR factorization for a matrix that its odd columns are orthogonal to its even columns Let $A$ be a full rank matrix with the property that columns $1 ,3 , 5 , 7 , ...\quad$ are orthogonal to columns $2 ,4 , 6 , 8, ...$. In a reduced $QR$ factorization $A=\hat{Q}\hat{R}$, what special structure does $\hat{R}$ possess?
Solving this manually leads to following matrix.
 $$R=
\begin{bmatrix} x_{1}&0&y_{1}&0&&&&...\\0&x_{2}&0&y_{2}&0&&&...\\0&0&x_{3}&0&y_{3}&&&...\\0&0&0&x_{4}&0&&&y_{4}\\ &&&...&&&&0\\0&...&&&&&&x_{5}\end{bmatrix} $$
I don't know how to prove this formally.
Does any one have an insight on this?
Thanks.
=====
I added the steps I have done to solve the problem manually:
I've tried the Gram-Schmidt orthogonalization as follow:
$ q_n = \frac{a_n- \sum_{i=1}^{n-1}r_{in}q_{i}}{r_{nn}}$
$ r_{ij} = q_i^{*}a_{j} \quad \quad i \neq j $
$ |r_{jj} |=  || a_{jj} - \sum_{i=1}^{j-1} q_{i}r_{ij} ||_{2}\quad \quad i = j $
$q_{1} = \frac{a_{1}}{||a_{11}||} \quad q_{2} = \frac{a_{2}}{||a_{22}||}\quad q_{3} = \frac{a_{3}-\frac{(a_{1}.a_{3})a_{1}}{||a_{1}||^{2}}}{|| a_{3}-\frac{(a_{1}.a_{3})a_{1}}{||a_{1}||^{2}}||} $
$r_{11} = ||a_1||\quad$
$r_{22} = ||a_2||\quad$
$r_{12}=0 \quad ....$
$q_{1}$ is a linear combination of $a_{1}$
$q_{2}$ is a linear combination of $a_{2}$
$q_{3}$ is a linear combination of $a_{1},a_{3} $
$q_{4}$ is a linear combination of $a_{2},a_{4} $
...
$$R=
\begin{bmatrix}
||a_{1}|| & 0 & \frac{a_1.a_3}{||a_{1}||} & 0 &... \\
0 & ||a_{2}||& 0 & val\neq0 &0 & ...\\ 0&0&||a_{3}-\frac{a_{1}.a_{3}}{||a_{1}||^{2}}{a_{1}||} & ...\\ .\\.\\.\end{bmatrix} $$
In matrix $R$:
If $i = j$: $r_{ij}\neq0$
If $i > j$ :$r_{ij}=0$
If $i<j$ &  both $i,j$ are either odd  or even then $r_{ij}\neq0$


text:
Q: Dinamically fill UITableViewCell with buttons side by side Continuing to resolve the task of UITableViewCell, I could fix all UIButtons side by side but they are not appearing properly in executing time. Sometimes the second row mix with the third.
I tryied with cell.layoutIfNeeded() but still wrong.

let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DetailViewCell
let array = sections[indexPath.section].filters

var hStackView = UIStackView()
var vStackView = UIStackView()
vStackView.axis = .vertical
vStackView.distribution = .fillEqually
vStackView.spacing = 12
vStackView.alignment = .top

for (index, item) in array.enumerated() {
    let btn = UIButton()
    btn.setTitle(item.title, for: .normal)
    btn.titleLabel?.font = .systemFont(ofSize: 12)
    btn.setTitleColor(.black, for: .normal)
    btn.backgroundColor = UIColor(red: 220, green: 220, blue: 220)
    btn.layer.cornerRadius = 15;
    btn.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
    btn.tag = index

    if index % 2 == 0  {
        hStackView = UIStackView()
        hStackView.axis = .horizontal
        hStackView.spacing = 12
        hStackView.alignment = .fill
        hStackView.distribution = .fillEqually
        hStackView.addArrangedSubview(btn)
        if (index + 1) == array.count {
            vStackView.addArrangedSubview(hStackView)
            hStackView.leadingAnchor.constraint(equalTo: vStackView.leadingAnchor).isActive = true
            hStackView.widthAnchor.constraint(equalTo: vStackView.widthAnchor, multiplier: 0.5).isActive = true
        }
    }
    else {
        hStackView.addArrangedSubview(btn)
        vStackView.addArrangedSubview(hStackView)
        hStackView.leadingAnchor.constraint(equalTo: vStackView.leadingAnchor).isActive = true
        hStackView.trailingAnchor.constraint(equalTo: vStackView.trailingAnchor).isActive = true
    }
}
cell.addSubview(vStackView)
vStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    cell.leadingAnchor.constraint(equalTo: vStackView.leadingAnchor, constant: -8),
    cell.trailingAnchor.constraint(equalTo: vStackView.trailingAnchor, constant: 8),
    cell.topAnchor.constraint(equalTo: vStackView.topAnchor, constant: -8),
    cell.bottomAnchor.constraint(equalTo: vStackView.bottomAnchor, constant: 8)
])
cell.layoutIfNeeded()
return cell

A: You should look up information about dequeueReusableCell
It works somehow like this: when you get a cell in tableView(_: cellForRowAt:) from dequeueReusableCell you are provided with a ready-made cell that was used somewhere. It follows from this that all content that the cells differ in must be placed in the cell only in this method
Note, the button with a label сссс is clearly from the top cell
I would advise you to declare in your UITableViewCell subclass a method in which you put content inside and call it every time inside tableView(_:cellForRowAt:)
You can use a storyboard if you like, but if you want to do it with code, I can suggest custom UITableViewCell subclass template:
class CustomTableViewCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    // MARK: - Public methods

    func setContent(_ content: <# ContentType #>) {

    }

    // MARK: - Private setup methods

    private func setupView() {

        makeConstraints()
    }

    private func makeConstraints() {
        NSLayoutConstraint.activate([

        ])
    }
}


text:
Q: getting 500 internal server error in different environment In one environment I am sending the web service request then I am getting 200 status. If I send the same web service request from another environment, then I am getting status like 500 internal server error.
May i know the reasons for getting status like that?
Thanks in advance.

A: Check Authentication and Authorization that you have access for another environment or not


text:
Q: Verify state of boolean variables in a dict I'm using some flags to keep track of actions like:
is_registered = True
has_paid = False
has_phone  = True

if (is_registered and has_phone and has_paid):
    do_something

But if the number of fields increase I prefer to store it in a dictionary
user_flags = {'is_registered':True,'has_paid':False,'has_phone':True}

if (user_flags['is_registered'] and user_flags['has_paid'] and user_flags['has_phone']):
    do_something

And again that might be ok for a small number of items but if I've gets say over 50 items it gets quite verbose

A: You can use all():
>>> user_flags = {'is_registered':True, 'has_paid':False, 'has_phone':True}
>>> all(user_flags.values())
False

>>> user_flags = {'is_registered':True, 'has_paid':True, 'has_phone':True, 'one_more_flag':True}
>>> all(user_flags.values())
True

Or, to inverse the logic with any():
>>> user_flags = {'is_registered':True, 'has_paid':False, 'has_phone':True}
>>> not any(not value for value in user_flags.values())
False

>>> user_flags = {'is_registered':True, 'has_paid':True, 'has_phone':True, 'one_more_flag':True}
>>> not any(not value for value in user_flags.values())
True

A: It depends on what kind of information you want to keep visible at the if line.
One "full visibility" option could be,
def check_flags(user, flags):
    return all([user[flag] for flag in flags])

user_flags = {'is_registered':True,'has_paid':False,'has_phone':True}

if check_flags(user_flags, ['is_registered', 'has_paid', 'has_phone']):
    do_something()

while if you don't mind possibly having to go search back for the flags you're checking, just embed the flags in a function and do if user_is_ready(): and you're done.


text:
Q: Python lambda functions connected to Qt signals don't run when created in a different thread When a QObject is created in a different thread and moved back to the main thread using QObject.moveToThread, lambda signals "disconnect" (they won't fire). My guess is that regular slots are linked to the QObject that is moved to the main thread, so they run in the main thread's event loop, but lambda functions aren't linked to the QObject, so there is no event loop for them to run.
This can be seen in the following short Python code:
if __name__ == "__main__":
    from traits.etsconfig.api import ETSConfig
    ETSConfig.toolkit = 'qt4'

import threading
from PySide import QtGui, QtCore

class MyObject(QtCore.QObject):
    def __init__(self, button):
        super(MyObject, self).__init__()
        button.clicked.connect(self.mySlot)
        button.clicked.connect(lambda: self.mySlot('lambda'))
    #
    def mySlot(self, printing='object'):
        print printing
#
myObj = None
# global variable to keep it in memory
def myThread(mainThread, button):
    global myObj
    myObj = MyObject(button)
    myObj.moveToThread(mainThread)
#
if __name__ == '__main__':
    appQT = QtGui.QApplication([])
    #
    myWidget = QtGui.QWidget()
    myButton = QtGui.QPushButton('Press to see output')
    myLayout = QtGui.QVBoxLayout(myWidget)
    myLayout.addWidget(myButton)
    myWidget.show()
    #
    mainThread = QtCore.QThread.currentThread()
    if True:
        # run myThread in a new thread
        # prints only the first slot (object slot)
        threading.Thread(target=myThread, args=[mainThread, myButton]).start()
    else:
        # run myThread in this thread
        # prints both slots (object and lambda slots)
        myThread(mainThread, myButton)
    #
    appQT.exec_()

You can see how the results differ from expected by changing the conditional from True to False.
When it is set to True, the output after clicking the button is:
object

When it is set to False, the output after clicking the button is:
object
lambda

My question is, can someone explain more precisely why it behaves in this way, and is there an easy way to keep the lambda slots working when moving the QObject back to the main thread?

A: Okay, I figured out some details about what is going on. It's still a partial answer, but I think it's more suitable as an answer rather than update to the question.
It seems that I was correct in my original question that the slots are linked to their instance object's QObject event loop (thread), but only if that slot is a bound method (has an object instance).
If you look into the PySide source code on Github, you'll see that it defines the receiver (the QObject that receives the signal) based on the type of slot it receives. So if you pass the QtSignal.connect() function a bound object method, the receiver is defined as the slotMethod.__self__ (which is PyMethod_GET_SELF(callback)). If you pass it a general callable object (for example a lambda function) which is not bound (no __self__ property), the receiver is simply set to NULL. The receiver tells Qt which event loop to send the signal to, so if it's NULL, it doesn't know to send the signal to the main event loop.
Here's a snippet of the PySide source code:
static bool getReceiver(QObject *source, const char* signal, PyObject* callback, QObject** receiver, PyObject** self, QByteArray* callbackSig)
{
    bool forceGlobalReceiver = false;
    if (PyMethod_Check(callback)) {
        *self = PyMethod_GET_SELF(callback);
        if (%CHECKTYPE[QObject*](*self))
            *receiver = %CONVERTTOCPP[QObject*](*self);
        forceGlobalReceiver = isDecorator(callback, *self);
    } else if (PyCFunction_Check(callback)) {
        *self = PyCFunction_GET_SELF(callback);
        if (*self && %CHECKTYPE[QObject*](*self))
            *receiver = %CONVERTTOCPP[QObject*](*self);
    } else if (PyCallable_Check(callback)) {
        // Ok, just a callable object
        *receiver = 0;
        *self = 0;
    }

    ...
    ...
}

Does this help us fix our problem with the lambda functions? Not really... If we bind the lambda functions using the following (with types.MethodType), the behavior does not change:
import types

class MyObject(QtCore.QObject):
    def __init__(self, button):
        super(MyObject, self).__init__()
        button.clicked.connect(self.mySlot)
        thisLambda = lambda self=self : self.mySlot('hello')
        self.myLambda = types.MethodType( thisLambda, self )
        button.clicked.connect(self.myLambda)
    #
    def mySlot(self, printing='object'):
        print printing

Output:
object

This binding is definitely part of the problem since I have demonstrated below that the same behavior occurs with non-bound global methods, and by binding them using types.MethodType(), it fixes the problem:
import types

def abc(self):
    print 'global1'

def xyz(self):
    print 'global2'

class MyObject(QtCore.QObject):
    def __init__(self, button):
        super(MyObject, self).__init__()
        button.clicked.connect(self.mySlot)
        self.xyz = types.MethodType( xyz, self )
        button.clicked.connect(abc)
        button.clicked.connect(self.xyz)
    #
    def mySlot(self, printing='object'):
        print printing

Output:
object
global2

Anyways, it seems the simplest solution is just to not create the QObject in a separate thread in the first place, but this answer is a step towards understanding why it doesn't work properly.


text:
Q: Finalizar la recogida de datos al escribir un texto Me piden que cree un programa que lea 10 números enteros tanto positivos como negativos ingresados por el teclado y presente su máximo, mínimo y promedio al finalizar.
Esto es lo que tengo hasta el momento:
#include <stdlib.h>
#include <stdio.h>

int main() {
    int num, mayor, menor, suma=0;
    float promedio=0;

    for (int i=0; i<10; i++){
        printf("Ingrese un  nùmero: " );
        scanf("%d", &num);
        suma= suma + num;
        if (i==0) {
            mayor = num;
            menor = num;
        }
        else {
            if (num > mayor) mayor = num;
            if (num < menor) menor = num;
        }
    }

    promedio = suma/10;
    printf("El numero mayor es: %d\n", mayor);
    printf("El numero menor es: %d\n", menor);
    printf("El promedio es: %.2lf\n", promedio);

    return 0;
}

Luego me piden hacer que modifique el programa para que al ingresar el texto "salir" termine de inmediato sin presentar resultados; y al ingresar el texto "resultados" termine presentando los resultados. Esto ya no se como hacerlo, busque y busque por internet pero no comprendo muy bien, si es necesario cambiar todo el codigo para lograr esto lo hago, pero necesito ayuda porfavor! muchas gracias!

A: Tan solo tienes que leer una cadena de texto con scanf y luego ver si dice resultados. Si no, sales.
Para leer una cadena de texto:
char comando[15];
scanf("%s", comando);

Y para comparar el contenido de una cadena sería:
strcmp(comando, "resultados") == 0
strcmp devuelve 0 si las cadenas son iguales. Devuelve un número negativo si la primera cadena es menor que la segunda, y un número positivo si la primera cadena es mayor que la segunda.
El final de tu código quedaría así:
char comando[15];

printf("Escriba 'salir' para salir o 'resultados' para mostrar los resultados: ");
scanf("%s", comando);

if (strcmp(comando, "resultados") == 0) {
    promedio = suma/10;
    printf("El numero mayor es: %d\n", mayor);
    printf("El numero menor es: %d\n", menor);
    printf("El promedio es: %.2lf\n", promedio);
}

Si necesitas otras cosas como añadir un bucle que repita hasta que el usuario diga "salir" o "resultados", pues habría que poner todo desde el printf hasta el final del if dentro de un bucle do { ... } while((strcmp(comando, "resultados") != 0) && (strcmp(comando, "salir") != 0).

A:
Luego me piden hacer que modifique el programa para que al ingresar el texto "salir" termine de inmediato sin presentar resultados; y al ingresar el texto "resultados" termine presentando los resultados.

Lo que te están pidiendo aquí es que modifiques el programa para que pida números sin parar hasta que se introduzca salir o resultados.
Este resultado lo puedes conseguir de varias maneras.
Una forma es la que te muestro a continuación: Se lee un caracter de la entrada estándar y se comprueba:

*

*Si es un caracter de control o que no nos interesa (espacio, salto de línea, ...) se descarta, en caso contrario el caracter leído se reingresa en el buffer de entrada.

*Si es un dígito numérico se lee el número introducido por el usuario.

*Si es una letra, se lee el texto correspondiente y se comprueba con los esperados.

Dicho con código:
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>

int main()
{
  int mayor = INT_MIN;
  int menor = INT_MAX;
  int suma = 0;
  int total_numeros = 0;

  while( 1 )
  {
    char c = getchar();

    if( c == EOF ) // Detectamos CTRL + C
      break;
    if( c < '0' )  // descartamos caracteres de control, espacios, saltos de línea, ...
      continue;

    ungetc(c, stdin); // volvemos a poner el caracter en el buffer de la entrada estándar

    if( isdigit(c) )
    {
      int numero;
      scanf("%d", &numero);
      suma += numero;
      total_numeros++;
      if( numero > mayor ) mayor = numero;
      if( numero < menor ) menor = numero;
    }
    else
    {
      char texto[100];
      scanf("%s", texto);
      if( strcmp(texto, "salir") == 0 )
        break;

      if( strcmp(texto, "resultados") == 0 )
      {
        printf("El numero mayor es: %d\n", mayor);
        printf("El numero menor es: %d\n", menor);
        printf("El promedio es: %.2lf\n", suma / (double)total_numeros);
        break;
      }
    }
  }
}


text:
Q: I keep getting segmentation fault :11 errors and i can't figure out why... c++ This program compiles alright but sometimes it creates segmentation errors.
The program should let the user to input student names, marks obtained for theory(70%) and practical papers(30%). These data should be saved into a file and finally the program should display/store student's name and marks.
#include <iostream>
#include <fstream>

void disp(int);
using namespace std;
void stunames(int n) {

    int count = 0;
    string names;

    cout << "Input student names :" << endl;
    ofstream na("names.txt");

    while( count <= n ) {

        getline(cin,names);
        na << names << endl;
        count++;
    }
    na.close();
}
void theomarks(int size) {

    double marks;
    int count = 0;
    ofstream tho("T.txt");

    while( count < size ) {
        cin >> marks;
        if((marks > 100) ||(marks < 0)){
            cout << "Invalid marks, Re-enter" << endl;
            count = count-1;
        }
        else
            tho << marks*.7 << endl;
        count++;
    }

    tho.close();

}
void pracmarks(int size) {

    ofstream pr("P.txt");
    double marks;
    int count = 0;

    while( count < size ) {

        cin >> marks;
        if((marks > 100) ||(marks < 0)){
            cout << "Invalid marks, Re-enter" << endl;
            count = count-1;
        }
        else
            pr << marks*.3 << endl;
        count++;
    }
    pr.close();
}

void calc(int size) {

    ifstream na("names.txt");
    ifstream readr("T.txt");
    ifstream mo("P.txt");
    string x;
    double pracc[1][size];
    double theory[1][size];
    cout << "NAME\t\tMARKS" << endl;

    for(int row = 0; row < size; row++) {

        for(int col = 0; col < 1; col++) {

            mo >> pracc[row][col];
            readr >> theory[row][col];
            na >> x;
            cout << x << "\t\t" << theory[row][col]+pracc[row][col];
        }
        cout << endl;
    }
    readr.close();
    mo.close();
    na.close();
}

int main() {

    int no;
    cout << "Input the number of student: " << endl;
    cin >> no;
    stunames(no);
    cout << "Input Theory Paper Marks" << endl;
    theomarks(no);
    cout << "Input practical Paper Marks" << endl;
    pracmarks(no);
    calc(no);

    return 0;
}

A: In expression pracc[row][col]; row and col ranges are messed up. Row must be less than 1;
It would be better to use ::std::array instead of C-style arrays. It would give you a proper debug assertion at corresponding moment instead of sudden segmentation fault.

A: You're doing
mo>>pracc[row][col];

But your array is defined:
double pracc[1][size];

and row goes above 1. So you're going past the boundary of the array. You probably want
double pracc[size][1];


text:
Q: Консоль отображает у объекта новое значение ключа раньше, чем ключ получает это значение Написал простой пример с изменением объекта в функции при передаче по ссылке.
https://plnkr.co/edit/kR9zRc0Y...
var salaries = {
    "Вася": 100,
    "Петя": 300,
    "Даша": 250
};

function changeObject(object) {
    for (var key in object) {
        object[key] += 100;
    }
}

console.log(salaries);
changeObject(salaries);
console.log(salaries);

В итоге результат:
Object {Вася: 100, Петя: 300, Даша: 250}
Object {Вася: 200, Петя: 400, Даша: 350}

Передача по ссылке происходит, но console.log() отрабатывает не так как ожидается, как будто Chrome (Version 49.0.2623.110 (64-bit)) фиксирует состояние объекта на момент console.log(), хотя вроде должен ссылаться на один и тот же измененный объект.
Кто знает в чем может быть дело?

A: Суть заключается в том, как работает консоль в хроме. И конкретно, функция log.
Она выводит значение объекта в момент вывода, при этом, если для вывода всех свойств требуется много места, появляется возможность развернуть объект.

При этом можно заметить, что в свернутом виде будет показываться информация актуальная на момент вывода, но если развернуть

будет показано состояния объекта на момент разворачивания.
Чтобы избежать такой неоднозначности, можно использовать
console.dir


text:
Q: Subtract a vector to each row of a dataframe My dataframe looks like this :
fruits = pd.DataFrame({'orange': [10, 20], 'apple': [30, 40], 'banana': [50, 60]})

   apple  banana  orange
0     30      50      10
1     40      60      20

And I have this vector (its also a dataframe)
sold = pd.DataFrame({'orange': [1], 'apple': [2], 'banana': [3]})

   apple  banana  orange
0      2       3       1

I want to subtract this vector to each row of the initial dataframe to obtain a dataframe which looks like this
   apple  banana  orange
0   28.0    47.0     9.0
1   38.0    57.0     19.0

I tried :
print fruits.subtract(sold, axis = 0)

And the output is
   apple  banana  orange
0   28.0    47.0     9.0
1    NaN     NaN     NaN

It worked only for the first line. I could create a dataframe filled with the vector for each row. Is there a more efficient way to subtract this vector ? I don't want to use a loop.

A: convert the df to a series using squeeze and pass axis=1:
In [6]:
fruits.sub(sold.squeeze(), axis=1)

Out[6]:
   apple  banana  orange
0     28      47       9
1     38      57      19

The conversion is necessary as by design arithmetic operations between dfs will align on indices and columns, by passing a Series this allows you to subtract from each row in the df the row from the other df.

A: Try:
fruits.sub(sold.iloc[0, :])

What you tried before didn't work because sold is a dataframe and the subtraction will try to align both columns and index.  sold.iloc[0, :] gets at the first row and is a series thus will work as you intended.


text:
Q: Check if string contains only letters in javascript So I tried this:
if (/^[a-zA-Z]/.test(word)) {
   // code
}

It doesn't accept this : "   "
But it does accept this: "word word", which does contain a space :/
Is there a good way to do this?

A: Try this
var Regex='/^[^a-zA-Z]*$/';

 if(Regex.test(word))
 {
 //...
 }

I think it will be working for you.

A: The fastest way is to check if there is a non letter:
if (!/[^a-zA-Z]/.test(word))

A: With /^[a-zA-Z]/ you only check the first character:

*

*^: Assert position at the beginning of the string

*[a-zA-Z]: Match a single character present in the list below:

*

*a-z: A character in the range between "a" and "z"

*A-Z: A character in the range between "A" and "Z"

If you want to check if all characters are letters, use this instead:
/^[a-zA-Z]+$/.test(str);

*

*^: Assert position at the beginning of the string

*[a-zA-Z]: Match a single character present in the list below:

*

*+: Between one and unlimited times, as many as possible, giving back as needed (greedy)

*a-z: A character in the range between "a" and "z"

*A-Z: A character in the range between "A" and "Z"

*$: Assert position at the end of the string (or before the line break at the end of the string, if any)

Or, using the case-insensitive flag i, you could simplify it to
/^[a-z]+$/i.test(str);

Or, since you only want to test, and not match, you could check for the opposite, and negate it:
!/[^a-z]/i.test(str);

A: You need
/^[a-zA-Z]+$/

Currently, you are matching a single character at the start of the input. If your goal is to match letter characters (one or more) from start to finish, then you need to repeat the a-z character match (using +) and specify that you want to match all the way to the end (via $)

A: try to add \S at your pattern

^[A-Za-z]\S*$

A: Here is the code to check the string:
/**
 * Check null, should contain only letters, allowed space, min length is minLength.
 * @param minLength
 * @param string
 * @returns
 */
export const isStringInValid = (string: string, minLength: number) => {
    return !string || !string?.trim() || !/^[a-zA-Z ]+$/.test(string) || string.length < minLength
}


text:
Q: How to hide/collapse main menu in a win32/mfc application I always been interested on how we can accomplish this (hide/show the main menu using the alt key), and now some applications do this very often. One that really please me is the visual studio 2010 with this plugin:
http://visualstudiogallery.msdn.microsoft.com/bdbcffca-32a6-4034-8e89-c31b86ad4813?SRC=VSIDE
(firefox also do this, but i think that is in a different way)
Can anyone explain me how this can be achieved or if you known of any sample project that demonstrate this please tell me.
(what i can see in some replies here in stack is that we have to destroy the menu when is to hide and create it when is to show?! but this seems a bit bad solution...)
Thanks

A: The SetMenu function lets you add/remove the menu from the window. It does not destroy the menu.
Note that most applications which have the dynamic menu hide/show behavior are not really showing a menu. They're showing a custom control that looks like a menu.

A: You might also take a look at MFC support for auto hiding menus. I used this technique and it worked really well.

A: in CMainFrame::OnCreate I did
m_wndMenuBar.ShowWindow(SW_HIDE);
which actually works fine in our project

A: I stumbled across a related pit fall that will show a hidden main frame without your consent:
Whenever the focus for a child window in an MDI application changes (e.g. due to right clicking in it), the function CMDIChildWnd::OnMDIActivate will be called, which in turn shows the main menu (even if it was removed or destroyed previously) of the MDI application.
This works basically by adding the saved main manu from the underlying's CMDIChildWnd m_hMenuShared variable.
A quick&dirty hack to prevent this, is setting m_hMenuShared to NULL (it's protected in CMDIChildWnd so this needs a custom derived child class of CMDIChildWnd) for all child frames.


text:
Q: how duplicates work in sharepoint results I have a search results webpart that in test mode it shows 6 results, in render mode it shows 5 results.
When I used the search query tool there is one duplicate.
When I check the 2 files, the names are similar but not equal, and the content of the pdf file is also similar, but not equal.
The only workaround I found is this one
http://thesharepointlife.com/2013/04/sharepoint-2013-search-not-display-all-results-2/
but I wonder if this can be changed in a different way, it would be very annoying if I have to this for all my search webparts.

A: Here is a way of changing it with powershell (still needs to be done per webpart though..)
# Author: Mikael Svenson - @mikaelsvenson
# Company: Puzzlepart
# Date: December, 2013
# Reference: http://www.sharepointnutsandbolts.com/2013/12/Using-CSOM-in-PowerShell-scripts-with-Office365.html

# replace these details (also consider using Get-Credential to enter password securely as script runs)..
$username = "username@something.onmicrosoft.com"
$password = "password"
$url = "https://company.sharepoint.com/search"
# the path to the SharePoint Client dlls'
$dllPath = "D:\SP2013-dll\ISAPI\"

$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force

Add-Type -Path "$($dllPath)Microsoft.SharePoint.Client.dll"
Add-Type -Path "$($dllPath)Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "$($dllPath)Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "$($dllPath)Microsoft.SharePoint.Client.Taxonomy.dll"

# connect/authenticate to SharePoint Online and get ClientContext object..
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)

#$credentials = New-Object System.Net.NetworkCredential($username, $securePassword)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

if (!$clientContext.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint site: '$Url'" -ForegroundColor Green
}

$web = $clientContext.Web
$clientContext.Load($web.AllProperties)
$clientContext.ExecuteQuery()
# get guid of the default Pages library to cater for localization
$pagesGuid = $web.AllProperties.FieldValues["__PagesListId"]
$clientContext.ExecuteQuery()
$clientContext.Load($web.Lists)
$list = $web.Lists.GetById($pagesGuid)
$clientContext.Load($list)
$clientContext.Load($list.RootFolder)
$clientContext.ExecuteQuery()
# get localized server relative url
$url = $list.RootFolder.ServerRelativeUrl

$page = $web.GetFileByServerRelativeUrl($url +"/results.aspx");

try{
$page.CheckOut()
$clientContext.ExecuteQuery()
Write-Host "Checking out page" -ForegroundColor Green
}
catch{ Write-Host "Page already checked out" -ForegroundColor Yellow}
$wpm = $page.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)
$clientContext.Load($wpm.WebParts)
$clientContext.ExecuteQuery()
for ($i=0; $i -lt $wpm.WebParts.Count; $i++)
{
    $item = $wpm.WebParts.Item($i)
    $clientContext.Load($item.WebPart)
    $clientContext.ExecuteQuery()
    if( $item.WebPart.Title -eq "Search Results" ) {
        Write-Host "Found result web part" -ForegroundColor Green
        break;
    }
}

$clientContext.Load($item.WebPart.Properties)
$clientContext.ExecuteQuery()
Write-Host "Turning off trimming of duplicates" -ForegroundColor Green
# Read JSON properties and convert to an object
$dataProvider = ConvertFrom-Json $item.WebPart.Properties["DataProviderJSON"]
$dataProvider.TrimDuplicates = $false
# Convert the object back to a JSON string
$item.WebPart.Properties["DataProviderJSON"] = ConvertTo-Json $dataProvider -Compress
$item.SaveWebPartChanges()
$clientContext.ExecuteQuery()
Write-Host "Checking in and publishing page" -ForegroundColor Green
$page.CheckIn("Modified Search Core Results web part", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
$page.Publish("Modified Search Core Results web part")
$clientContext.ExecuteQuery()

From http://techmikael.blogspot.se/2013/12/duplicate-trimming-in-sharepoint-2013.html
This script can work both on premise and in the cloud!