text:
Q: Creating a dataframe with scraped data I am trying to scraping data as follows:
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
import pandas as pd

daterange = pd.date_range('02-25-2015', '09-16-2020', freq='D')

def main(req, date):
    r = req.get(f"https://it.sputniknews.com/politica/{date.strftime('%Y%m%d')}")
    print(r, r.content)
    soup = BeautifulSoup(r.content, 'html.parser')
    tag=None
    print (soup.select("b-plainlist"))
    #for tag in soup.select(".b-plainlist "):
        #print(tag.select_one(".b-plainlist__date").text)
        #print(tag.select_one(".b-plainlist__title").text)
        #print(tag.find_next(class_="b-plainlist__announce").text.strip())

    return tag.select_one(".b-plainlist__date").text, tag.select_one(".b-plainlist__title").text, tag.find_next(class_="b-plainlist__announce").text.strip()

with ThreadPoolExecutor(max_workers=30) as executor:
    with requests.Session() as req:
        fs = [executor.submit(main, req, date) for date in daterange]
        allin = []
        for f in fs:
            allin.append(f.result())
        df = pd.DataFrame.from_records(
            allin, columns=["Date", "Title", "Content"])
        print(df)

trying to create a dataframe with the Date, Title and Content though time.
This code should be ok, but I cannot create a 'clean' dataframe so I think there is something wrong in the tags.
Can you please have a look? thanks

A: I wasn't exactly able to run your code as is, but to get a "clean" dataframe, you need to notice each news item is contained within a .b-plainlist__item element so you have to select all, iterate over them and get b-plainlist__date, etc.
The following worked for me:
import datetime

from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from dateutil import rrule
import pandas as pd
import requests

def get_items(session, date):
    url_template = 'https://it.sputniknews.com/politica/{}'
    r = session.get(url_template.format(date.strftime("%Y%m%d")))

    soup = BeautifulSoup(r.content, 'html.parser')
    items = soup.select(".b-plainlist__item")

    for item in items:
        date = datetime.datetime.strptime(
            item.select_one(".b-plainlist__date").text,
            '%H:%M %d.%m.%Y'
        )
        title = item.select_one(".b-plainlist__title").text
        content = item.select_one(".b-plainlist__announce").text

        yield {'Date': date, 'Title': title, 'Content': content}

daterange = rrule.rrule(
    freq=rrule.DAILY,
    dtstart=datetime.datetime(2015, 2, 25),
    until=datetime.datetime(2020, 9, 16),
)

with ThreadPoolExecutor(max_workers=30) as executor:
    with requests.Session() as session:
        fs = [
            executor.submit(get_items, session, date)
            for date in daterange
        ]

        result = []
        for f in fs:
            result.extend(f.result())

        df = pd.DataFrame.from_records(result, index='Date')

Output
df.head()
                                                                 Title                                            Content
Date
2015-02-25 18:21:00          Che cosa accadrà dopo la tregua di Minsk?  Nonostante il cessate il fuoco entrato nel vig...
2015-02-26 14:12:00       Renzi va a Mosca con un pacchetto misterioso  Il viaggio di Matteo Renzi a Mosca – previsto ...
2015-02-26 13:47:00       Turchia all'UE: non aspetteremo all'infinito  Lo scopo della Turchia è appunto quello di ade...
2015-02-26 11:24:00  Tutte le portaerei mediatiche sparano ad alzo ...  Riassumiamo le ultime vicende della crisi est-...
2015-02-26 11:01:00  Nel dopo Minsk gli ostacoli prevalgono sull'ot...  Nella ridda di intepretazioni dei risultati de...


text:
Q: Implementing global extendable / overridable ajax loader I'm currently displaying an ajax loading image whenever a jquery ajax request occurs like this:
$(document).ajaxStart(function () {
 $(".ajaxLoadingIndicator").show();
  });

$(document).ajaxStop(function () {
  $(".ajaxLoadingIndicator").hide();
 });

I can put this in a global JS file and have it on every page. Now it would be smart to make this behavior overridable at certain points. A sub-view or page might execute additional logic or replace the current logic entirely. Currently I'm doing something like this:
//global js file
var shsGlobal = new Globals();

function Globals() {

}

Globals.prototype.ajaxLoaderStart = function () {
    $(".ajaxLoadingIndicator").show();
}

Globals.prototype.ajaxLoaderStop = function () {
    $(".ajaxLoadingIndicator").hide();
}

$(document).ajaxStart(function () {
shsGlobal.ajaxLoaderStart();
});

$(document).ajaxStop(function () {
shsGlobal.ajaxLoaderStop();
});

And on a different page I might do sth like this:
   shsGlobal.ajaxLoaderStart = function () {
    //additional logic here...

    //base method
    Globals.prototype.ajaxLoaderStart.call();
}

Since I'm not doing that much javascript I'm not sure if this isn't a bit wonky. It works, though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: issue with autocomplete event with jquery I am using autocomplete event using a keyboard keypress event in the input

$(function() {
  var availableTags = ["Amsterdam, Netherlands"];

  function split(val) {
    return val.split(/,\s*/);
  }

  function extractLast(term) {
    return split(term).pop();
  }

  $("#tags")
    // don't navigate away from the field on tab when selecting an item
    .on("keydown", function(event) {
      if (event.keyCode === $.ui.keyCode.TAB &&
        $(this).autocomplete("instance").menu.active) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 0,
      source: function(request, response) {
        // delegate back to autocomplete, but extract the last term
        response($.ui.autocomplete.filter(
          availableTags, extractLast(request.term)));
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join(", ");
        return false;
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<input type="text" name="server_locations" class="form-control" placeholder="city" id="tags">

I am using this code to set autocomplete city name in my project
but when I use this code I have received

Uncaught TypeError: Cannot read property 'keyCode' of undefined

I don't know why is this happening.
can anybody help me with this

A: Your code snippet is not working !
I copied and changed to jquery ui 1.12.1.
it's working!
If you require any further information, feel free to comment.

$(function() {
  var availableTags = ["Amsterdam, Netherlands"];

  function split(val) {
    return val.split(/,\s*/);
  }

  function extractLast(term) {
    return split(term).pop();
  }

  $("#tags")
    // don't navigate away from the field on tab when selecting an item
    .on("keydown", function(event) {
      if (event.keyCode === $.ui.keyCode.TAB &&
        $(this).autocomplete("instance").menu.active) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 0,
      source: function(request, response) {
        // delegate back to autocomplete, but extract the last term
        response($.ui.autocomplete.filter(
          availableTags, extractLast(request.term)));
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join(", ");
        return false;
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" name="server_locations" class="form-control" placeholder="city" id="tags">


text:
Q: Adding an event handler to a specific children within a DOM tree that is created on runtime I'm trying to bind an event handler to an element that is a children in a DOM tree that is added to the HTML dynamic while runtime. The following HTML shows what I got. The table and its thead and tbody are static HTML. Later I'm adding the content of tbody (

) to it.

        Image

So now I want to bind an event handler on the image like:
$("#progData").on("click", "img", function(e){/*do sth in here*/});

But this doesnt work for some reason. I have to use
$("#progData").on("click", "tr", function(e){/*do sth in here*/});

to get it to work at least when clicking on the row.
Is there any way to bind the event to a dynamic element that is deeper in the DOM than the direct child element?

A: Ah, I'm sorry. I had a mistake within my callback function in the event handler. As I had to work with "tr" before I accessed some attributes that are only present within the "tr". So as I changed the handler to the "img" object I just forgot to access the attributes now by parent() functions... :/
So it was just my mistake. Problem solved :)

A: You can try doing  -
$("#progData").find("img").on("click", function(e){/*do sth in here*/});

If the HTML is already loaded before the code is hit.
OR
You could try adding a class to the dynamic content and then bind on its click event such as
HTML -

Javascript -
$(".jMyImage").on("click", function(e){/*do sth in here*/});

A: This should do what you are after if I understand correctly:
$(document).on("click", "#progData img", function(e){/*do sth in here*/});

or if you want just the first one:
$(document).on("click", "#progData img:nth-child(2)", function(e){/*do sth in here*/});

Because the element is added dynamically you need to attach to the document as the element isn't created yet or is created after the document is. More info can be found here: http://api.jquery.com/on/

A: I guess that you are trying to attach events to a tag which is still not there. I mean, you should check the moment where you add the event listener to be after the moment where the table row is inserted. For example this works for me:
var onImageLoaded = function() {
    $("#progData").on("click", "img", function(e){
        if(e.currentTarget.tagName == 'IMG') {
            console.log("clicked");
        }
    })
}

var table = $("#progData");
table.find("tbody").html("

");

JSFiddle -> http://jsfiddle.net/krasimir/ybavx/


text:
Q: for loop doesn't behave as expected, what did i forget? Just one time alert and it is only for 0. Any help will appreciated.
Thank you
Caglar
var ayIsimleri = new Array ( "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık" );

for (i = 0; i < 12; i++)
{
     alert(i);
     secenekAy = secenekAy + '<input type="checkbox" id="'+ i +'">'+ ayIsimleri[i] + '<br>';

}

A: Your javascript is breaking your code, its not a for loop problem.
Check the javascript console and let us know the error there.

A: Because you haven't defined variable secenekAy, exception aborts the loop. Just adding var secenekAy = "" will solve your problem.


text:
Q: python tkinter window going unresponsive and hanging MyButton1 =Button(master, text='Quit',bg="grey",width=20,
command=master.quit)
MyButton1.place(x=200, y=100)
MyButton2 =Button(master, text='Propagate', bg="grey",width=20,
command=mainmethod)
MyButton2.place(x=1000, y=100)
master.geometry("1500x1500")
master.mainloop( )

In the above code after pressing propagate button mainmethod is invoking..
I wrote my logic in main method where this method alone taking 2minutes to execute in the mean time GUI going unresponsive state for few min and later displaying all my required output on text box i inserted
whether any away to avoid the unresponsive issue apart from using multi threading
and i am looking such that after pressing propagate button button should disabled and window should not go unresponsive and display text.insert statements continuously which i added in main method ?????

A: To prevent hanging, you need to separate the calculations in the mainmethod from Tkinter's main loop by executing them in different threads. However, threading system in Python is not that well-developed as in other languages (AFAIK) because of GIL (Global Interpreter Lock), but there is an alternative - using processes just like threads. This is possible with multiprocessing library.
In order to just prevent hanging, you could create another function
from multiprocessing import Process
def mainmethodLaunch():
    global mainmethodProcess
    mainmethodProcess = Process(target=mainmethod)
    mainmethodProcess.start()

And bind this function to MyButton2 instead of mainmethod itself.
Docs: https://docs.python.org/2/library/multiprocessing.html#the-process-class
You can see p.join in the example. join method will cause your main process to wait for the other one to complete, which you don't want.
So when you press the button, mainmethodLaunch function will be invoked, and it will create another process executing mainmethod. mainmethodLaunch function's own run duration should be insignificant. Due to usage of another process, Tkinter window will not hang. However, if you do just this, you will not be able to interact with mainmethod process in any kind while it will be working.
In order to let these processes communicate with each other, you could use pipes (https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes)
I guess the example is quite clear.
In order to receive some data from the mainmethod process over time, you will have to poll the parent_conn once a little time, let's say, second. This can be achieved with Tkinter's after method
(tkinter: how to use after method)
IMPORTANT NOTE: when using multiprocessing, you MUST initialize the program in if __name__ == '__main__': block. I mean, there should be no doing-something code outside functions and this block, no doing-something code with zero indent.
This is because multiprocessing is going to fork the same Python executable file, and it will have to distinguish the main process from the forked one, and not do initializing stuff in the forked one.
Check twice if you have done that because if you make such a mistake, it can cost you hanging of not just Tkinter window, but the whole system :)
Because the process will be going to fork itself endlessly, consuming all RAM you have, regardless of how much you have.


text:
Q: PhpStorm автоматически сворачивает комментарии, если с них начать файл. Как это отменить? У меня есть файл .js. Начинается он с такого кода:
    // ---------------------------------------
    // Добавочная функция JQuery для изменения value, которая вызывает событие change
    // ---------------------------------------
    $.fn.changeVal = function (v) {
        return $(this).val(v).trigger("change");
    }

Когда я открываю его, PhpStorm прячет комментарий. Получается вот что:

Как мне это отменить? Сделать так, чтобы он не прятал комментарии?


text:
Q: MySQL how do I select only highest for each pair values from the following table? I have the following table:
+----+---------+---------+-------+
| ID | FARM_ID | GATE_ID | SCORE |
+----+---------+---------+-------+
|  1 |       1 |       1 |   100 |
|  2 |       2 |       1 |   100 |
|  3 |       5 |       5 |   100 |
|  4 |       4 |       1 |    16 |
|  5 |       4 |       3 |    16 |
|  6 |       4 |       5 |    23 |
|  7 |       5 |       1 |   100 |
|  8 |       4 |       1 |    95 |
|  9 |       4 |       3 |    91 |
| 10 |       4 |       5 |   100 |
| 11 |       5 |       1 |    20 |
| 12 |       4 |       1 |   100 |
| 13 |       4 |       3 |    95 |
| 14 |       4 |       5 |    95 |
| 15 |       4 |       6 |    91 |
| 16 |       5 |       1 |    16 |
| 17 |       4 |       1 |    95 |
| 18 |       4 |       2 |    91 |
| 19 |       4 |       3 |   100 |
| 20 |       4 |       5 |    91 |
| 21 |       4 |       6 |    95 |
| 22 |       4 |       1 |    91 |
| 23 |       4 |       2 |    95 |
| 24 |       4 |       3 |    95 |
| 25 |       4 |       4 |    91 |
| 26 |       4 |       6 |   100 |
| 27 |       4 |       2 |   100 |
| 28 |       4 |       3 |    91 |
| 29 |       4 |       4 |    95 |
| 30 |       4 |       6 |    95 |
| 31 |       4 |       2 |    95 |
| 32 |       4 |       4 |   100 |
| 33 |       4 |       6 |    91 |
| 34 |       5 |       3 |   100 |
| 35 |       5 |       6 |   100 |
| 36 |       5 |       2 |   100 |
| 37 |       5 |       4 |   100 |
| 38 |       3 |       1 |    91 |
| 39 |       3 |       5 |   100 |
| 40 |       3 |       1 |   100 |
| 41 |       3 |       3 |    91 |
| 42 |       3 |       5 |    91 |
| 43 |       3 |       1 |    91 |
| 44 |       3 |       3 |   100 |
| 45 |       3 |       6 |    91 |
| 46 |       3 |       2 |    91 |
| 47 |       3 |       3 |    91 |
| 48 |       3 |       6 |   100 |
| 49 |       3 |       2 |   100 |
| 50 |       3 |       4 |    91 |
| 51 |       3 |       6 |    91 |
| 52 |       3 |       2 |    91 |
| 53 |       3 |       4 |   100 |
| 54 |       8 |       1 |   100 |
| 55 |       7 |       1 |   100 |
| 56 |       6 |       1 |   100 |
+----+---------+---------+-------+

Desired results:
I wish to show only the highest score for each FARM_ID--GATE_ID pair.
(There should be 23 unique pairs present above and as a result).
Thanks greatly!

A: select farm_id, gate_id, max(score)
from table
group by farm_id, gate_id

?


text:
Q: Node reference is lost after modifying a class name I lost object reference after changing the class name through node.className = ...
var nodeName = 'my_div';
var subNode = document.getElementById(nodeName);
var nodes = subNode.getElementsByClassName('one');
alert (nodes[0]); // OK - [object HTMLSpanElement]
nodes[0].setAttribute('class','zzz');
alert (nodes[0]); // Undefined

How do I save a reference to the object in a variable?

A: Because the getElementsByClassName() returns a live collection, that means any changes to the original dom elements attributes will be reflected in the list.
You can use a method like querySelectorAll() which returns a non live set of elements
var nodes = subNode.querySelectorAll('.one');


text:
Q: Equilbrium points in dynamical systems I have been giving the following system of equations. From this system of equations I have determined the jacobian matrix, which i then worked out. However I am wondering what is the equilibrium points of this system? I assume $(0,0,0,0,0,0,0)$ is one. So my question are how do I evaluate this into my workings below and find out its stability? And is there another equilibrium point?
\begin{eqnarray}
\frac{dV_H}{dt} &=&- \left( \mu_H + \mu_{AVD} + \mu_{AND} + w \right)V_H  + \gamma e S_H \label{equation1}\\
\frac{dS_H}{dt}  &=& -bp_HI_M\frac{S_H}{N_H} + wV_H - \left( \gamma e  + \mu_H  \right)S_H  \label{equation2}\\
\frac{dI_H}{dt} &=&  - \left( \mu_H + \mu_{YF} + r \right)I_H + bp_H I_M \frac{S_H}{N_H}\label{equation3}\\
\frac{dR_H}{dt} &=& -\mu_HR_H  + rI_H \label{equation4}\\
\frac{dS_M}{dt} &=& -bp_MS_M\frac{I_H}{N_H} - \mu_M S_M + \alpha_M I_M + \alpha_M E_M \label{equation5}\\
\frac{dE_M}{dt} &=& - \left( \beta + \mu_M  \right) E_M + bp_M S_M  \frac{I_H}{N_H} \label{equation6}\\
\frac{dI_M}{dt} &=& -\mu_MI_M+\beta E_M \label{equation7}
\end{eqnarray}
From this system i have determine the jacobian matrix to be the following
\begin{bmatrix}
\frac{\partial V_H}{\partial V_H}    & \frac{\partial V_H}{\partial S_H} &  \frac{\partial V_H}{\partial I_H} &  \frac{\partial V_H}{\partial R_H} &  \frac{\partial V_H}{\partial S_M} &  \frac{\partial V_H}{\partial E_M} &  \frac{\partial V_H}{\partial I_M} \\
  \frac{\partial S_H}{\partial V_H}    & \frac{\partial S_H}{\partial S_H} &  \frac{\partial S_H}{\partial I_H} &  \frac{\partial S_H}{\partial R_H} &  \frac{\partial S_H}{\partial S_M} &  \frac{\partial S_H}{\partial E_M} &  \frac{\partial S_H}{\partial I_M} \\
   \frac{\partial I_H}{\partial V_H}    & \frac{\partial I_H}{\partial S_H} &  \frac{\partial I_H}{\partial I_H} &  \frac{\partial I_H}{\partial I_H} &  \frac{\partial I_H}{\partial S_M} &  \frac{\partial I_H}{\partial E_M} &  \frac{\partial I_H}{\partial I_M} \\
    \frac{\partial R_H}{\partial V_H}    & \frac{\partial R_H}{\partial S_H} &  \frac{\partial R_H}{\partial I_H} &  \frac{\partial R_H}{\partial R_H} &  \frac{\partial R_H}{\partial S_M} &  \frac{\partial R_H}{\partial E_M} &  \frac{\partial R_H}{\partial I_M} \\
        \frac{\partial S_M}{\partial V_H}    & \frac{\partial S_M}{\partial S_H} &  \frac{\partial S_M}{\partial I_H} &  \frac{\partial S_M}{\partial R_H} &  \frac{\partial S_M}{\partial S_M} &  \frac{\partial S_M}{\partial E_M} &  \frac{\partial S_M}{\partial I_M} \\
        \frac{\partial E_M}{\partial V_H}    & \frac{\partial E_M}{\partial S_H} &  \frac{\partial E_M}{\partial I_H} &  \frac{\partial E_M}{\partial R_H} &  \frac{\partial E_M}{\partial S_M} &  \frac{\partial E_M}{\partial E_M} &  \frac{\partial E_M}{\partial I_M} \\
    \frac{\partial I_M}{\partial V_H}    & \frac{\partial I_M}{\partial S_H} &  \frac{\partial I_M}{\partial I_H} &  \frac{\partial I_M}{\partial R_H} &  \frac{\partial I_M}{\partial S_M} &  \frac{\partial I_M}{\partial E_M} &  \frac{\partial I_M}{\partial I_M}
    \end{bmatrix}
Working out each partial derivative i have produced the following.
\begin{bmatrix}
    A    & \gamma e & 0 & 0 & 0 & 0 & 0 \\
    w      & B & 0 & 0 & 0 & 0 & -bp_H \frac{S_H}{N_H} \\
    0      & bp_H \frac{I_M}{N_H} & C & 0 & 0 & 0 & bp_H \frac{S_H}{N_H} \\
    0      & 0 & r  & D & 0 & 0 & 0 \\
        0      & 0 & -bp_H \frac{S_M}{N_H}  & 0 & E & \alpha_M & \alpha_M \\
        0      & 0 & bp_M \frac{S_M}{N_H}  & 0 & bp_M \frac{I_H}{N_H} & F & 0 \\
      0      & 0 & 0  & 0 & 0 & \beta & G
    \end{bmatrix}
where
\begin{align*}
A&=-\mu_H-\mu_{H-AVD}-\mu_{H-AND} - w \\
    B&=bp_H \frac{I_M}{N_H} - \gamma e -\mu_H\\
    C&= - \left( \mu_H + \mu_{H-YF} +  r \right)\\
    D&=-\mu _ H \\
    E&=-bp_M \frac{I_H}{N_H} - \mu_M\\
    F&=-\beta -\mu_M\\
    G&=-\mu _M
    \end{align*}

A: So far all these steps are reasonable.
To determine whether the zero equilibrium point is stable, you may have to find the spectrum of the linearization for special parameter values, or you could employ the Routh-Hurwitz criterion which will give you a set of algebraic equations for the coefficients.
There is indeed a second equilibrium point. All its components are proportional to $N_H$. For example,
$$
I_M = - \frac{(\gamma  e+\mu_H) (\mu_{AND}+\mu_{AVD}+\mu_H)+\mu_H
   w}{bp_H (\mu_{AND}+\mu_{AVD}+\mu_H+w)} \cdot N_H
$$
To find all other components, use a computer algebra system.
Note that if all parameters are positive, then $I_M < 0$ for this equilibrium.
Added: You can find the other components of the second equilibrium point as follows. Set all terms on the right hand side equal to 0. The last equation gives $E_M$. The second to last equation then tells you what $S_MI_H$ must be. The fifth equation then can be used to find $S_M$ and the value of $I_H$ follows. Next use the fourth equation to find the value of $R_H$. Then the third equation results in $S_H$, and the second equation finally gives you $V_H$.
The first equation can be used as a consistency check.
Added 2: The linearization of this system about the zero equilibrium point is block diagonal. Using your notation, the top left $2 \times 2$ block is
$\begin{pmatrix} A & \gamma e \\ w & B
\end{pmatrix}$.
This matrix has the characteristic polynomial $z^2 - (A + B)z + (AB - \gamma e \cdot w)$. Both coefficients are positive, therefore both eigenvalues of this matrix are in the left half plane. That's the Routh Hurwitz criterion for $2 \times 2$ matrices.
The second block is $\begin{pmatrix} C & 0 \\ r & D
\end{pmatrix}$ with characteristic polynomial $(z + C)(z+D)$, hence both eigenvalues of this matrix are also in the left half plane.
The third block is $3\times 3$, namely $\begin{pmatrix} E & \alpha_M & \alpha_M \\ 0  & F & 0 \\ 0 & \beta & G \end{pmatrix}$ and its characteristic polynomial is $(z+E)(z+F)(Z+G)$.  Again all its roots are in the left half plane.
The set of eigenvalues of the entire $7 \times 7$ matrix now is the union of the sets of eigenvalues of those three blocks, so they are all in the left half plane. That means that the zero equilibrium is always locally stable.


text:
Q: Compilation Error The type or namespace name could not be found I've recently been drafted onto a C# web based project.
I have a DLL file I wrote in C# that I'm trying to get working with a aspx page. It all works fine on my local machine. I upload the project to a 2008 server and get the following:

Server Error in '/' Application. Compiler Error Message: CS0246: The
  type or namespace name 'GNVHandler' could not be found (are you
  missing a using directive or an assembly reference?) Line 6:  using
  GNVHandler;

The contents of the site are:

*

*test.aspx

*test.aspx.cs

*Bin/GNVHandler.dll

The ASPX page is default as the aspx.cs apart from:
using GNVHandler;

and to test things are working:
protected void Page_Load(object sender, EventArgs e)
{
    GNVHandle GNV = new GNVHandle();
}

Now I've run:

regasm.exe GNVHandler.dll

The result of this was:

Types registered successfully

but still the error persists. Any help on this please?

A: We found the issue,
There were insufficient security privileges on the /Bin folder.
Problem solved!


text:
Q: Concerns related to neural network matlab toolbox I have some concerns related to the use of nntool in MATLAB toolbox. Following links like this, I have found that nntool by default normalizes the inputs to the range [-1 1]. So I am a bit concerned, I created a neural network with tansig activation in the first layer and logsig activation in the output layer. I manually normalized the outputs to the range of [0 1] in the data and fed it to nntool.
Now my question is does nntool further normalizes it to the range [-1 1]. If it does then it is not correct, the output of logsig cannot be in the range of [-1 1].
I am using the newfit function like this
load house_dataset;
net = newfit(houseInputs,houseTargets,20);

Any suggestions?

A: nntool has a large number of tunable parameters, refer to the documentation for more details. In particular section Preprocessing and Postprocessing deals with different types of pre- and postprocessing techniques which are available in the toolbox.
When you look at the newfit definition you can find such information:

Purpose Create fitting network
Syntax net = newfit(P,T,S,TF,BTF,BLF,PF,IPF,OPF,DDF)
Description newfit(P,T,S,TF,BTF,BLF,PF,IPF,OPF,DDF) takes the following:
(...)
IPF Row cell array of input processing functions. Default is
  {'fixunknowns','remconstantrows','mapminmax'}.
OPF Row cell array of output processing functions. Default is
  {'remconstantrows','mapminmax'}
(...)

So you can simply change them to IPF={'fixunknowns','remconstantrows'} and OPF={'remconstantrows'} to turn the min-max mapping off.


text:
Q: provide user defined value to scheduler at run time I have create xml file for scheduler but i am unable to do run time customization code.
below is my xml file
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <bean id="runMeTask" class="com.spring.server.tasks.ShareMeTask" />

    <bean name="runMeJob" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="com.spring.server.job.ShareMeJob" />
        <property name="jobDataAsMap">
            <map>
                <entry key="runMeTask" value-ref="runMeTask" />
            </map>
        </property>
    </bean>

    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
        <property name="jobDetail" ref="runMeJob" />
        <property name="repeatInterval" value="5000" />
        <property name="startDelay" value="1000" />
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="runMeJob" />
        <property name="cronExpression" value="* 0/10 * * * ?" />
    </bean>

    <bean id="scheduler"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!-- <property name="jobDetails">
            <list>
                <ref bean="runMeJob" />
            </list>
        </property>
 -->
        <property name="triggers">
            <list>
                <ref bean="cronTrigger" />
            </list>
        </property>
    </bean>
</beans>

.
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.spring.server.tasks.ShareMeTask;

public class ShareMeJob extends QuartzJobBean {
    private ShareMeTask shareMeTask;

    public void setRunMeTask(ShareMeTask shareMeTask) {
        this.shareMeTask = shareMeTask;
    }

    protected void executeInternal(JobExecutionContext context)
            throws JobExecutionException {
        System.out.println("ShareMeJob");
        shareMeTask.printMe1();

    }
}

.
public class ShareMeTask {

    public void printMe2() {

        System.err.println("Spring 3 + Quartz 1.8.6 ~");

    }
    public void printMe1() {

        System.err.println("Spring Job execution");

    }

}

when time reached the above class is call and the method is run. but if admin want to configure cron at run time then how can will he configure it and please tell me the code for run time configuration and starting the scheduler.
i found there are some methods in shecduler for shutdown and start but how can i use these method at run time.

A: We can store the Cron-Expression to a properties fil to configure it dynamically, so you can modify when ever you need without touching the application code and repacking.
Step(1): Create a File under as  /path/myFile.properties
cronExp.value=* 0/10 * * * ?
Step (2): Modify your spring xml as below:
<context:property-placeholder location= "file:/path/myFile.properties" />

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="runMeJob" />
        <property name="cronExpression" value="${cronExp.value}" />
</bean>


text:
Q: Can't get model binding to work in MVC2  <% using (Html.BeginForm("Create", "User", FormMethod.Post, new { id = "frmCreateUser", name = "frmCreateUser" })){%>

I am trying to send form data to controller where Create is method name and user is a method is a controller name.
syntax of the method
 [AcceptVerbs(HttpVerbs.Post)]
 public ActionResult Create(User UserToCreate)
 {
  //Controller action
 }

Syntax for the textbox
  <%: Html.TextBoxFor(model => model.UserName, new {id="UserName", size="30" })%>

Call goes fine on Create but User object give null why?

A: The TextBoxFor helper method assigns a unique id to the input box so MVC can map the properties over when you post it to the server. Your overridding the id therefore your mapping will fail, change your textbox code to:
<% Html.TextBoxFor(model => model.UserName, new { size = 30 }) %>

Just to clarify, MVC maps properties using the name property of the input fields. However, I suspect that overridding the id property is effecting this. You can check the HTML output to clarify this, the name should look something like user.username.
Edit
Sandboxed your code into a small MVC3 project and it worked fine for me (even with setting the id!). Looking at the tags your using it would appear your using MVC2 instead of 3?

A: You don't need to assing id property. Be sure that Your view is strongly typed (by User)
like:
@model User

A: Might be a stab in the dark, but remove the id="UserName" part.
If your controller, is mapped to a specific class. Something like this should be fine.
@model  SomeSite.ViewModels.VM_User

@Html.TextBoxFor(model => model.UserName, new { Class = "ui-corner-all FormElement ui-widget-content" })


text:
Q: Jenkins goes out of heap (OutOfMemoryError) when the tests print a lot of log messages to System.out I am using Jenkins to run some system tests.
Those tests write 18-20 MB printouts to the standard output.
Jenkins job is configured to run with 2048 MB max heap size.
Strangely enough, when these printouts are turned on, jenkins goes OutOfMemoryError (out of heap space).
It is definitely the printouts which cause the problem. Without them, all works fine.
What troubles me, how 20 MB of text cause the whole process to be OutOfMemory.
I already have increased the heap size from 1 GB to 2 GB, but without any result.
Without the prints, on 1GB max heap size all tests work fine.
Here the exception:
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2786)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:94)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:44)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:42)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:42)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:42)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:42)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:42)
    at java.io.PrintStream.write(PrintStream.java:430)
    at org.apache.maven.surefire.util.TeeStream.write(TeeStream.java:42)
    at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
    at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:263)
    at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:106)
    at java.io.OutputStreamWriter.write(OutputStreamWriter.java:190)
    at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
    at java.io.PrintStream.write(PrintStream.java:476)
    at java.io.PrintStream.print(PrintStream.java:619)
    at java.io.PrintStream.println(PrintStream.java:756)
    ...

Does anyone know some sort of configuration of Jenkins, that a lot of prints to the System.out (20 MB of them) won't cause the OutOfMemory to occur?
Clarification: I don't want to debug Jenkins, I am not a Jenkins developer. I use Jenkins to run system tests using JUnit on my application as CI.

A: Try starting jenkins with "-XX:+HeapDumpOnOutOfMemoryError" JVM argument, that should give you a dump file to analyze whenever you get the out of memory exception.
EDIT --
I think I may have something for you.
First of, the surefire plugin by default forks a new JVM for running tests, and this JVM does not inherit JVM properties of the maven JVM, i.e. if you've set the maven process to have 2048MB Max Heap, it will not be set for the JVM forked by the surefire plugin.
So for setting JVM args of the forked JVM, use the 'argLine' property of the surefire plugin. That way you'll be able to set the Max heap for the forked JVM and not the maven JVM.
Secondly,  It looks like the surefire plugin redirects the stdout/stderr and keeps the contents of stuff written to these 2 streams in memory, that's why you may be running out of memory.
So you can also try setting 'redirectTestOutputToFile' property to 'true', that way all sdtout goes to a file, may be that will avoid storing the stream contents in memory,Or try setting the forkmode='always', that way it will fork one JVM per test-class, keeping the memory consumption from piling up, one test after another.
Hope one of these helps you in your issue.

A: The OutOfMemoryError is caused by too much printed output of your test cases.
I had the same issue, where a single test seemed to print too much.
I don't know whether the same effect happens when several tests are fine for themselves but produce too much output overall when executed together. But I would guess that memory is freed after each test.
Analysis
My heapdump analysis had shown that the class in question TeeStream seems to fork an output to two streams (thus the "T"). I had a hierachy of TeeStreams, referencing each other while also holding an own Printer. Your stacktrace also indicates the same.
That means each output coming in is propagated through this hierachy and printed several times. Thus the size of the printers increased dramatically the lower in the hierachy they were. This is very leaky of course and explains the high memory consumption.
To me this seems to be a bug in Surefire.
Handy workaround
As a workaround I reduced the printed output of my tests.
More sustainable solutions
If this is no option for you, you should configure Surefire (in your .pom) to run in forked mode. I'm sure passing Xmx as an argument to increase the heap size is also possible there.

A: there is some very much memory consuming analysis of the output, scanning for errrors and warnings -  disable it


text:
Q: Summing up total amount from multiple models in Django The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code
class FurnitureItem(models.Model):
    fur_title = models.CharField(max_length=200)
    fur_price = models.FloatField()
    fur_discount_price = models.FloatField(blank=True, null=True)
    fur_pictures =  models.ImageField(upload_to='Pictures/', blank=True)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
    fur_descriptions = models.TextField()
    slug = models.SlugField()
    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.fur_title

class FurnitureOrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    fur_ordered = models.BooleanField(default=False)
    item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.quantity} of {self.item.fur_title}"
    ....

    def get_final_fur_price(self):
        if self.item.fur_discount_price:
            return self.get_total_discount_fur_price()
        return self.get_total_item_fur_price()

class FurnitureOrder(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    fur_items = models.ManyToManyField(FurnitureOrderItem)
    date_created = models.DateTimeField(auto_now_add=True)
    ordered_created = models.DateTimeField()
    fur_ordered = models.BooleanField(default=False)
    def __str__(self):
        return self.user.username

    def get_total_fur_everything(self):
        total = 0
        for fur_order_item in self.fur_items.all():
            total += fur_order_item.get_final_fur_price()
        return total

class GraphicItem(models.Model):
    graphic_title = models.CharField(max_length=200)
    graphic_price = models.FloatField()
    graphic_discount_price = models.FloatField(blank=True, null=True)
    graphic_pictures =  models.ImageField(upload_to='Pictures/', blank=True)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
    graphic_descriptions = models.TextField()
    slug = models.SlugField()
    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.graphic_title

class GraphicOrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    graphic_ordered = models.BooleanField(default=False)
    item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.quantity} of {self.item.graphic_title}"

    ....

    def get_final_graphic_price(self):
        if self.item.graphic_discount_price:
            return self.get_total_discount_graphic_price()
        return self.get_total_item_graphic_price()

class GraphicOrder(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    graphic_items = models.ManyToManyField(GraphicOrderItem)
    date_created = models.DateTimeField(auto_now_add=True)
    ordered_created = models.DateTimeField()
    graphic_ordered = models.BooleanField(default=False)
    def __str__(self):
        return self.user.username

    def get_total_graphic_everything(self):
        total = 0
        for graphic_order_item in self.graphic_items.all():
            total += graphic_order_item.get_final_graphic_price()
        return total

what i've tried as regards summing up the amount for furniture and graphics
class TotalAmount(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    graphic_items = models.ManyToManyField(GraphicOrderItem)
    fur_items = models.ManyToManyField(FurnitureOrderItem)
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.user.username

    def amount(self):
        return self.graphic_items.get_total_graphic_everything() + self.fur_items.get_total_fur_everything()

Then my views goes this way:
class Summary(LoginRequiredMixin, View):
    def get(self, *args, **kwargs):
        try:
            fur_order = FurnitureOrder.objects.get(user=self.request.user, fur_ordered=False)
            graphic_order = GraphicOrder.objects.get(user=self.request.user, graphic_ordered=False)
            amount = TotalAmount.objects.get(user=self.request.user)

            context = {
            'fur_order':fur_order,'graphic_order':graphic_order,'amount':amount}
            return render(self.request, 'business/home-order-summary.html', context)

Thanks for your time, I no the code is lengthy, but I wanted to expanciate better.


text:
Q: Build networkx directed graph or flow chart from more than one column of pandas dataframe I have pandas dataframe which consist of 10 columns.

*

*each row consist a step performed by a user to online. there are total of 10 columns so all 10 step process

*lets say first activity is booking a flight ticket so steps are
login website-->give src dest time-->select seats-->pay--review

so there are various permutations can happen at every step, I want to draw a directed graph out of all dataset.
currently networkx supports only 2 columns in
# libraries
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

# Build your graph
G=nx.from_pandas_dataframe(df, 'src', 'dest',create_using=nx.DiGraph())

# Plot it
nx.draw(G, with_labels=True)
plt.show()

can someone tell me how to d it for more than two column directed graph

A: networkx from_pandas_dataframe uses add_edges_from, you can do a similar thing:
# libraries
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

# Build your graph

df = pd.DataFrame(np.random.randn(2,4),columns=list('ABCD')) #Create a 4 column data frame

columns = list(df.columns.values)# Get columns name

g = nx.empty_graph(0, nx.DiGraph()) #initialize an empty graph

for i in range(len(columns)-1):
    g.add_edges_from(zip(df[columns[i]], df[columns[i+1]])) #Create edge between 2 values, between all consecutive coumns

# Plot it
nx.draw(g, with_labels=True)
plt.show()

With a result:


text:
Q: Can we create multiple trigger under After_Insert Event in MySql? I've a trigger in one of my table which is on After Insert Event, Now I need to create one more trigger on the same event After Insert but I'm unable to do that ! Is there any mysql limit or is there any way to create multiple trigger under After Insert event.
there is simple create trigger statement but I'm getting this :
This version of MariaDB doesn't yet support 'multiple triggers with the same action time and event for one table'
This version of MariaDB doesn't yet support 'multiple triggers with the same action time and event for one table'


text:
Q: Mysql sum on self table select I'm looking for the right sql query to do the following operation:
I need to display all record for today and for each make sum of price field for the curent user and date < today
Table Commandes: (today = 11/18/2022)

ID
username
date
price

1
user.1
11/21/2022
99.0

2
user.x
11/21/2022
99.0

3
user.1
11/18/2022
2.5

4
user.x
11/18/2022
10.0

5
user.1
11/17/2022
2.5

6
user.x
11/17/2022
20.0

7
user.1
11/16/2022
2.5

8
user.x
11/16/2022
30.0

I want:
| ID       | username | date       | price  | solde
| -------- | -------- |------------|------- |------
| 1        | user.1   | 11/18/2022 |  2.5   |  5.0
| 2        | user.x   | 11/18/2022 | 10.0   | 40.0

solde would be same as "backorder not yet payed". When Item is payed, field price is set to 0.
For now, i use this query:
SELECT * FROM Commandes WHERE (Date='11/18/2022')
And in each row I execute:
SELECT sum(price) as solde
FROM Commandes
WHERE (username=currentselecteduser) and (STR_TO_DATE(date, '%m/%d/%Y') < CURDATE());

That's working but really uggly !

A: Here is the solution
SELECT t1.* ,
(select sum(price) from Commandes where username = t1.username and date < CURDATE()) solde
FROM `Commandes` as t1
WHERE date = CURDATE()

Also would like the tell you something that,
You want the total for the dates < today, so As per your logic  your for user.x  total will be 50  nor  40

A: SELECT username,
       `date`,
       MAX(CASE WHEN `date` = CURRENT_DATE THEN price END) price,
       SUM(CASE WHEN `date` < CURRENT_DATE THEN price END) solde
FROM Commandes
WHERE `date` <= CURRENT_DATE
GROUP BY 1, 2;

The query assume that

*

*(username, `date`) is defined as UNIQUE;

*date is stored in the column which have DATE datatype.


text:
Q: Default text appearing in the password text box ..how to make it disappear? Even though "Text" property is set to Text=""
asp:TextBox MaxLength="256"  runat="server" ID="passwordTxt" TextMode="Password" Text=""

I also tried this on Page_load :-
passwordTxt.Text="";

I am still seeing 5 dots in the Password text box..How to make it go away ? Why is it there anyway ? like why ?
[EDIT]
I was not able to see Bold, Code tag buttons when posting this ques..so couldnt include my code lines inside of code tags..whats wrong with this website ??
[EDIT2]
ok I can see the buttons now

A: It's probably the browser auto-populating for you. View the source, it will be empty.

A: To stop firefox auto prompting to save this data in a form, add the following property to the form tag
autocomplete="off"
i.e. :
    form id="myForm" runat="server" autocomplete="off"


text:
Q: How to create excel file in sharepoint from java? I want to programmatically create an excel document and add it to the Sharepoint list. I didn't find any java libraries to create Excel files programmatically and works with SharePoint. I'm using graph-API to access the SharePoint documents.
Is there any way to do this and what's the best way to do it or even start researching about it?


text:
Q: Module not found: Can't resolve './PlatformColorValueTypes' I have just started learning React Native and wanted to add styleSheet it seems doesn't work, I'm trying to solve an issue but I'm still stuck please can someone help me to solve this issue. by the way I am using react native.
Console log

Browser result:

here is my code below :
 const styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop: 100,
        paddingTop: 20,
        paddingBottom: 30,
        justifyContent: 'center',
        alignItems: 'center',

      },
      tinyPic: {
        width: 90,
        height: 90,
        top: -10
      },

      gauge: {
        position: 'absolute',
        width: 140,
        height: 140,
        alignItems: 'center',
        justifyContent: 'center',
      },

      label1: {
        position: 'absolute',
        top:15,
        right: '115%',
        padding: 4

      },
      label2: {
        position: 'absolute',
        top:15,
        left: '115%',
        padding: 4

      },
      label3: {
        position: 'absolute',
        top: 145,
        left: '95%',
        padding: 4

      }

    });

A: I solve this issue by updating react-native :
npm i https://github.com/expo/react-native/archive/sdk-42.0.0.tar.gz --save -force

A: I encountered a similar issue in an Expo React Native (SDK 47) app, where Webpack told me,
Exporting with Webpack...
Failed to compile
ModuleNotFoundError: ./node_modules/react-native/Libraries/StyleSheet/normalizeColor.js
Cannot find module: './PlatformColorValueTypes'. Make sure this package is installed.

You can install this package by running: npm install ./PlatformColorValueTypes.

I looked into ./node_modules/react-native/Libraries/StyleSheet/normalizeColor.js and confirmed that it called require('./PlatformColorValueTypes').
When I looked inside ./node_modules/react-native/Libraries/StyleSheet/, I saw that Webpack was correct that normalizeColor.js did not have a sibling file named PlatformColorValueTypes.js. But there were sibling files named PlatformColorValueTypes.ios.js and PlatformColorValueTypes.android.js.
To resolve this, I edited my webpack.config.js file to include .ios.js, .android.js, and .web.js extensions as ones that would be resolved by Webpack:
resolve: {
  extensions: [".tsx", ".ts", ".js", ".ios.js", ".android.js", ".web.js"]
}


text:
Q: Why I cannot apply constraints to the photo in the UITableView header? In my storyboard I have a UITableView and above the dynamic cells I added a UIView to keep there a photo and some labels.
Currently, I want to apply constraints to the photo so that it reaches the top, left and right side of the screen and keeps the aspect ratio. However, the storyboard looks like this:

The constraints for photo are:

However, as you see, the constraints are marked in red and when I run the app the photo is not stretched properly.
What is causing this issue?

A: I would probably do this programmatically. It is pretty simple to create a custom view and set it as your header view. You can either create a UIView with a UIImageView inside of viewForHeader or by assigning it to the entire table with tableView.tableHeaderView = headerView.


text:
Q: flutter : Failed assertion: boolean expression must not be null i am tried to run my project and this error still appearing
Failed assertion: boolean expression must not be null

i was run it more than 30 times and it was worked but now it doesn't and i don't know the reason for this problem i am not change any thing in my code before the error , and i tried some solutions and it doesn't work also , so what should i do now !
this is my screen which has the problem
class _TourguideDetailesState extends State<TourguideDetailes>
    with TickerProviderStateMixin {
  AppProvider appProvider;
  ScrollController scrollController = ScrollController(initialScrollOffset: 0);

  AnimationController animationController;

  @override
  void initState() {
    animationController = AnimationController(
        duration: Duration(milliseconds: 2000), vsync: this);
    animationController.forward();
    super.initState();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    appProvider = Provider.of<AppProvider>(context);

    return Scaffold(
      backgroundColor: AppTheme.getTheme().backgroundColor,
      body: Stack(
        children: <Widget>[
           NestedScrollView(
            controller: scrollController,
            physics: NeverScrollableScrollPhysics(),
            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                SliverPersistentHeader(
                  pinned: true,
                  floating: true,
                  delegate: ContestTabHeader(
                    (MediaQuery.of(context).size.height),
                    appProvider.selectedTourguide,
                    () {
                      scrollController.animateTo(MediaQuery.of(context).size.height - MediaQuery.of(context).size.height / 5,
                          duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn);
                    },
                    getGuideDetails(),
                  ),
                ),
              ];
            },
            body: ListView(
              padding: EdgeInsets.only(top: 24),
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(left: 24, right: 24),
                  child: getGuideDetails(isInList: true),
                ),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Divider(
                    height: 1,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 24, right: 24),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(
                          "Biography",
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 18,
                            letterSpacing: 0.5,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                    padding:
                        EdgeInsets.only(left: 24, right: 24, top: 4, bottom: 8),
                    child: Text(
                      appProvider.selectedTourguide.bio == null
                          ? ""
                          : appProvider.selectedTourguide.bio,
                      style: TextStyle(
                        fontSize: 14,
                        color: AppTheme.getTheme().disabledColor,
                      ),
                    )),
                    Padding(
                  padding: const EdgeInsets.only(left: 24, right: 24),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(
                          "Native Language",
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 18,
                            letterSpacing: 0.5,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                    padding:
                        EdgeInsets.only(left: 24, right: 24, top: 4, bottom: 8),
                    child: Text(
                      appProvider.selectedTourguide.nativeLanguage == null ? "" : appProvider.selectedTourguide.nativeLanguage,
                      style: TextStyle(
                        fontSize: 14,
                        color: AppTheme.getTheme().disabledColor,
                      ),
                    )),
                Padding(
                  padding:
                      EdgeInsets.only(left: 24, right: 24, top: 4, bottom: 8),
                ),
                SizedBox(
                  height: 16,
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      left: 16, right: 16, bottom: 16, top: 16),
                  child: Container(
                    height: 48,
                    decoration: BoxDecoration(
                      color: AppTheme.getTheme().primaryColor,
                      borderRadius: BorderRadius.all(Radius.circular(24.0)),
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                          color: AppTheme.getTheme().dividerColor,
                          blurRadius: 8,
                          offset: Offset(4, 4),
                        ),
                      ],
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        borderRadius: BorderRadius.all(Radius.circular(24.0)),
                        highlightColor: Colors.transparent,
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => BookingScreen(
                                  index: appProvider.selectedTourguide,
                                ),
                                fullscreenDialog: true,
                              ));
                        },
                        child: Center(
                          child: Text(
                            "Book now",
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 16,
                                color: Colors.white),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: MediaQuery.of(context).padding.bottom,
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
            child: Container(
              height: AppBar().preferredSize.height,
              child: Row(
                children: <Widget>[
                  SizedBox(
                    height: AppBar().preferredSize.height,
                    child: Padding(
                      padding: EdgeInsets.only(top: 8, left: 8),
                      child: Container(
                        width: AppBar().preferredSize.height - 8,
                        height: AppBar().preferredSize.height - 8,
                        decoration: BoxDecoration(color: AppTheme.getTheme().disabledColor.withOpacity(0.4), shape: BoxShape.circle),
                        child: Material(
                          color: Colors.transparent,
                          child: InkWell(
                            borderRadius: BorderRadius.all(
                              Radius.circular(32.0),
                            ),
                            onTap: () {
                              if (scrollController.offset != 0.0) {
                                scrollController.animateTo(0.0, duration: Duration(milliseconds: 500), curve: Curves.easeInOutQuad);
                              } else {
                                Navigator.pop(context);
                              }
                            },
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Icon(Icons.arrow_back, color: AppTheme.getTheme().backgroundColor),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: SizedBox(),
                  ),

                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget getGuideDetails({bool isInList = false}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        Expanded(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                appProvider.selectedTourguide.name,
                textAlign: TextAlign.left,
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 22,
                  color: isInList == null
                      ? AppTheme.getTheme().textTheme.body1.color
                      : Colors.white,
                ),
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Text(
                    appProvider.selectedTourguide.address,
                    style: TextStyle(
                      fontSize: 14,
                      color: isInList == null
                          ? AppTheme.getTheme().disabledColor.withOpacity(0.5)
                          : Colors.white,
                    ),
                  ),
                  SizedBox(
                    width: 4,
                  ),
                  Icon(
                    FontAwesomeIcons.mapMarkerAlt,
                    size: 12,
                    color: AppTheme.getTheme().primaryColor,
                  ),
                ],
              ),
              isInList == null
                  ? SizedBox()
                  : Padding(
                      padding: const EdgeInsets.only(top: 4),
                      child: Row(
                        children: <Widget>[
                          Text(
                            " ${appProvider.selectedTourguide.review} Reviews",
                            style: TextStyle(
                              fontSize: 14,
                              color: isInList
                                  ? AppTheme.getTheme().disabledColor
                                  : Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
            ],
          ),
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Row(
              children: <Widget>[
                Text(
                  appProvider.selectedTourguide.tariffValue=  null ? '' : appProvider.selectedTourguide.tariffValue,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 22,
                    color: isInList == null
                        ? AppTheme.getTheme().textTheme.body1.color
                        : Colors.white,
                  ),
                ),
                Text(
                  appProvider.selectedTourguide.currency=  null ? '' : appProvider.selectedTourguide.currency,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 22,
                    color: isInList == null
                        ? AppTheme.getTheme().textTheme.body1.color
                        : Colors.white,
                  ),
                ),
              ],
            ),
            Text(
              "/per hour",
              style: TextStyle(
                fontSize: 14,
                color: isInList == null
                    ? AppTheme.getTheme().disabledColor.withOpacity(0.5)
                    : Colors.white,
              ),
            ),
          ],
        ),
      ],
    );
  }
}

class ContestTabHeader extends SliverPersistentHeaderDelegate {
  final Widget ui;
  final VoidCallback callback;
  final TourGuide tourguideData;
  final double heightValue;
  ContestTabHeader(
    this.heightValue,
    this.tourguideData,
    this.callback,
    this.ui,
  );

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    var minValue = (shrinkOffset < heightValue - heightValue / 5? shrinkOffset: heightValue / 5);
    return Container(
      height: heightValue - minValue,
      decoration: BoxDecoration(
        color: AppTheme.getTheme().primaryColor,
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: AppTheme.getTheme().dividerColor,
            blurRadius: 8,
            offset: Offset(4, 4),
          ),
        ],
      ),
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            top: 0,
            child: Container(
              width: MediaQuery.of(context).size.width,
              child: Image.network(
                tourguideData.photo == null
                    ? 'https://i.ytimg.com/vi/TWaReNkjTLk/maxresdefault.jpg'
                    : tourguideData.photo,
                fit: BoxFit.cover,
              ),
            ),
          ),
          Positioned(
            bottom: MediaQuery.of(context).padding.bottom + 16,
            left: 0,
            right: 0,
            child: Opacity(
              opacity: getOpValue(minValue, heightValue / 5),
              child: Column(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(left: 24, right: 24),
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(24)),
                      child: new BackdropFilter(
                        filter:
                            new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                        child: Container(
                          color: Colors.black12,
                          padding: const EdgeInsets.all(4.0),
                          child: Column(
                            children: <Widget>[
                              SizedBox(
                                height: 4,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 16, right: 16, top: 8),
                                child: ui,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 16, right: 16, bottom: 16, top: 16),
                                child: Container(
                                  height: 48,
                                  decoration: BoxDecoration(
                                    color: AppTheme.getTheme().primaryColor,
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(24.0)),
                                    boxShadow: <BoxShadow>[
                                      BoxShadow(
                                        color: AppTheme.getTheme().dividerColor,
                                        blurRadius: 8,
                                        offset: Offset(4, 4),
                                      ),
                                    ],
                                  ),
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(24.0)),
                                      highlightColor: Colors.transparent,
                                      onTap: () {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) =>
                                                BookingScreen(),
                                            fullscreenDialog: true,
                                          ),
                                        );
                                      },
                                      child: Center(
                                        child: Text(
                                          "Book now",
                                          style: TextStyle(
                                              fontWeight: FontWeight.w500,
                                              fontSize: 16,
                                              color: Colors.white),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Center(
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(24)),
                      child: new BackdropFilter(
                        filter:
                            new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                        child: Container(
                          color: Colors.black12,
                          child: Material(
                            color: Colors.transparent,
                            child: InkWell(
                              highlightColor: Colors.transparent,
                              splashColor: AppTheme.getTheme()
                                  .primaryColor
                                  .withOpacity(0.2),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(38)),
                              onTap: () {
                                try {
                                  callback();
                                } catch (e) {}
                              },
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    left: 16, right: 16, top: 4, bottom: 4),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      'More Details',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.only(top: 2),
                                      child: Icon(
                                        Icons.keyboard_arrow_down,
                                        color: Colors.white,
                                        size: 24,
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  double getOpValue(double minValue, double maxValue) {
    var data = (1.0 - (minValue / maxValue));
    if (data < 0.0) {
      return 0.0;
    } else if (data >= 0 && data <= 1) {
      return data;
    } else {
      return 1.0;
    }
  }

  @override
  double get maxExtent => heightValue;

  @override
  double get minExtent => heightValue / 5;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

A: Look at the Text Widget, hope it helps. Too lazy to read the whole thing carefully. By the way, you can replace a == null ? 'whatever' : a with a ?? 'whatever'. ?? is equal with if null
Row(
  children: <Widget>[
    Text(
      /// The problem is probably here, missing '='
      appProvider.selectedTourguide.tariffValue=  null ? '' : appProvider.selectedTourguide.tariffValue,
      textAlign: TextAlign.left,
      style: TextStyle(
        fontWeight: FontWeight.w600,
        fontSize: 22,
        color: isInList == null
            ? AppTheme.getTheme().textTheme.body1.color
            : Colors.white,
      ),
    ),
    Text(
      /// The problem is probably here, missing '='
      appProvider.selectedTourguide.currency=  null ? '' : appProvider.selectedTourguide.currency,
      textAlign: TextAlign.left,
      style: TextStyle(
        fontWeight: FontWeight.w600,
        fontSize: 22,
        color: isInList == null
            ? AppTheme.getTheme().textTheme.body1.color
            : Colors.white,
      ),
    ),
  ],
),


text:
Q: Azure multistage yaml pipeline how to substitute appsetting indexed value I have an issue relating to appsettings.json substitution in yaml variable.
app setting config
"Serilog": {
    "LevelSwitches": { "$controlSwitch": "Information" },
    "MinimumLevel": {
      "ControlledBy": "$controlSwitch",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "!FromSecret!",
          "apiKey": "!FromSecret!",,
          "controlLevelSwitch": "$controlSwitch"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "Properties": {
      "Application": ""
    }

in yaml I need to replace !FromSecret! with actual value
variables:
  - name: Serilog.WriteTo.0.Args.apiKey
    value: '$(Secret-AppSettings-Serilog-ApiKey)'
  - name: Serilog.WriteTo.0.Args.serverUrl
    value: '$(Secret-API-AppSettings-Serilog-Url)'

the above yaml substitution is now working as unable to find the index need a help
need expert help on this issue

A: You can use below yaml script to modify ARGS object in an array element and index like below:-
variables:
  - name: Serilog.WriteTo[0].Args.apiKey
    value: '$(Secret-AppSettings-Serilog-ApiKey)'
  - name: Serilog.WriteTo[0].Args.serverUrl
    value: '$(Secret-API-AppSettings-Serilog-Url)'

Complete YAML script with app settings and Azure Web app :-
trigger:
- main

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
  appSettingsFile: 'path/to/appsettings.json'
  serverUrlVariable: '$(Secret-API-AppSettings-Serilog-Url)'
  apiKeyVariable: '$(Secret-AppSettings-Serilog-ApiKey)'

steps:
- task: DotNetCoreCLI@2
  inputs:
    command: 'restore'
    projects: '$(solution)'

- task: DotNetCoreCLI@2
  inputs:
    command: 'build'
    projects: '$(solution)'
    arguments: '--configuration $(buildConfiguration)'

- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    projects: '$(solution)'
    publishWebProjects: true
    arguments: '--configuration $(buildConfiguration) --output $(build.artifactstagingdirectory)'
    zipAfterPublish: true

- task: AzureAppConfiguration@1
  inputs:
    azureSubscription: 'My Azure Subscription'
    action: 'SetKeyValue'
    Key: 'Serilog:WriteTo:0:Args:serverUrl'
    Value: '$(serverUrlVariable)'
    AppConfigurations: 'MyAppConfig'
    AppConfigurationEnvironment: 'MyAppConfigEnvironment'

- task: AzureAppConfiguration@1
  inputs:
    azureSubscription: 'My Azure Subscription'
    action: 'SetKeyValue'
    Key: 'Serilog:WriteTo:0:Args:apiKey'
    Value: '$(apiKeyVariable)'
    AppConfigurations: 'MyAppConfig'
    AppConfigurationEnvironment: 'MyAppConfigEnvironment'

- task: CopyFiles@2
  inputs:
    SourceFolder: '$(System.DefaultWorkingDirectory)'
    Contents: '**/appsettings.json'
    TargetFolder: '$(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'


text:
Q: Form keeps resetting I'm working on a form that has multiple stages inside  tags.
The problem is when the user gets to the 3rd stage and they click continue , it resets them back to the 1st stage.
I believe this to be an issue with the java script although I'm not sure. If I change the if() part to something like if(phone = 11) (if the number entered has 11 digits) then it works , but it wont work with the validation.
Here is the java script to process the 3rd stage:
    function processPhase3() {
var validmail = ( /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/.test(email) ); //JUST A TEST
//phone.length = 11 && validmail

phone = _("Ctelephone").value;
mobile = _("Cmobile").value;
email = _("Cemail").value;
if (validmail) {
_("phase3").style.display = "none";
_("phase4").style.display = "block";
_("progressBar").value = 99;
_("status").innerHTML = "Step 4";
} else {

}
}

A: You need to adjust your button to not submit the form by setting the type of the button to "button".
Like this:
<button type="button" onclick="processPhase3()">Continue</button>


text:
Q: Find absolute difference between 2 columns with dates of different formats as number of days I need to find the absolute difference in days between 2 columns which have dates in python.
This is pretty easy in excel but I want in python.
I have a xlsx file which I have read to a python dataframe(using pd.read_excel) with sample data reading as below:
The columns have the date details in the plain text format of ddmmyyyy/dmmyyyy.
A                   B
1102012
26071993        27122007
28062010        3122015
16012010        21022016
02082015        14092010
Now I need to create a new column C which contains the absolute number of days difference between A and B. A can be less than or greater than B.
If B is empty then it should consider current date for days calculation. But A will not have empty/NULL values.
So output will be the difference of number of days:
C
2432
5267
1984
2227
1783
The approach I followed was:

*

*Convert A and B to 8 digits as we have only 7 digits in some values of A and B - using df['A'].apply(lambda x: '{0:0>8}'.format(x))

*Convert A to datetime field using pd.to_datetime

*Create another temporary column say CC by copying B values and with all not NULL date values(that is replacing NULL/empty with current date)

*Then find the absolute difference between A and CC(number of days)

I am stuck in third step and not able to proceed. Is there any simpler way to do this?

A: First fomratting options is a good idea. Avoids confusion as to which is day or month.
# Recreate dataframe
df = pd.DataFrame([["1102012", pd.np.NaN],["26071993","27122007"],
                   ["28062010","3122015"],["16012010","21022016"],
                   ["02082015","14092010"]], columns=["A","B"])
print(df)
>>>
          A         B
0   1102012       NaN
1  26071993  27122007
2  28062010   3122015
3  16012010  21022016
4  02082015  14092010

print(df.dtypes)
>>>
A    object
B    object
dtype: object

So the dataframe we are working from is above. The data types are all object (string). Would be good if you can confirm this step as everything else stems from here.
# convert some datetimes
# Assumption is that column A is not sparse - there are no NaNs
# Column B can be NaN so make it today if so
m = df["B"].isnull()
df.loc[m, "B"] = pd.datetime.now().strftime("%d%m%Y")
print(df)
>>>
          A         B
0   1102012  03062019
1  26071993  27122007
2  28062010   3122015
3  16012010  21022016
4  02082015  14092010

# now we zero pad some numbers
df['A'] = df['A'].apply(lambda x: '{0:0>8}'.format(x))
df['B'] = df['B'].apply(lambda x: '{0:0>8}'.format(x))
print(df)
>>>
          A         B
0  01102012  03062019
1  26071993  27122007
2  28062010  03122015
3  16012010  21022016
4  02082015  14092010

Then use to_datetime:
df["A"] = pd.to_datetime(df["A"], format="%d%m%Y")
df["B"] = pd.to_datetime(df["B"], format="%d%m%Y")
print(df)
>>>
           A          B
0 2012-10-01 2019-06-03
1 1993-07-26 2007-12-27
2 2010-06-28 2015-12-03
3 2010-01-16 2016-02-21
4 2015-08-02 2010-09-14

print(df.dtypes)
>>>
A    datetime64[ns]
B    datetime64[ns]
dtype: object

Then the diff
df["Diff"] = (df["A"] - df["B"]).abs()
print(df)
>>>
           A          B      Diff
0 2012-10-01 2019-06-03 2436 days
1 1993-07-26 2007-12-27 5267 days
2 2010-06-28 2015-12-03 1984 days
3 2010-01-16 2016-02-21 2227 days
4 2015-08-02 2010-09-14 1783 days

# or
df["Diff"] = (df["A"] - df["B"]).abs().dt.days
print(df)
>>>
           A          B  Diff
0 2012-10-01 2019-06-03  2436
1 1993-07-26 2007-12-27  5267
2 2010-06-28 2015-12-03  1984
3 2010-01-16 2016-02-21  2227
4 2015-08-02 2010-09-14  1783

A: Edit: explain on error
As you said the error in comment. It means your column A is not dtype object. It is either int32 or int64. Run this command to confirm (I changed sample data column A dtype to demonstrate the error):
df.dtypes

Out[2866]:
A     int32
B    object
dtype: object

Before using str.zfill, you need to change your df to object as follows:
df = df.astype(str)

Out[2870]:
A    object
B    object
dtype: object

After converting dtype to object, everything will works.

zfill(8) to pad 0 to strings and convert them to datetime using pd.to_datetime with coerce, and filna on NaT with today date. Next, do subtraction A and B, make abs and get days from timedelta
Note: adding pre-process to convert df dtype to object using astype(str)
df = df.astype(str)
df1 = df.apply(lambda x: pd.to_datetime(x.str.zfill(8), format='%d%m%Y', errors='coerce')).fillna(pd.datetime.today().date())
df1.A.sub(df1.B).abs().dt.days

Out[2599]:
0    2432
1    5267
2    1984
3    2227
4    1783
dtype: int64


text:
Q: Creating and overriding an interface being put into a parameter Currently I'm converting code from Java to C# and using a function:
        eventManager.Listen(typeof(EntityCreateEvent),
        new EntityCreateListener()
        {
            public override void Create(Entity Entity)
            {
                //add(entity);
            }
        });

The problem is that, this is far from legal in C#. How do I go about doing this in C#? I'd prefer not to do a work-around as I have quite a few of these in the code I'm changing that have stuff in the override that needs to be dynamic.

A: Here you are creating an event listener.
Java provides anonymous interfaces as a way to subscribe to events.
C# doesn't have anonymous interfaces. However, there is an event framework baked into the language.
So instead of exposing a Listen method on EventManager, expose an event:
 class EntityCreatedEventArgs : EventArgs
 {
      public Entity Entity {get; set; }
 }

 class EventManager
 {
      public event EventHandler<EntityCreatedEventArgs> EntityCreate;

      private void FireCreateEvent(Entity entity)
      {
          if(this.EntityCreate)
          {
               this.EntityCreate(this, new EntityCreatedEventArgs { Entity = entity });
          }
      }
      // Rest of implementation
 }

Then your listening class can 'subscribe' to this event
 public class OtherThing
 {
       public OtherThing(EventManager eventManager)
       {
           eventManager.EntityCreate += this.EventManager_EntityCreate;
       }

       void EventManager_EntityCreate(object sender, EntityCreatedEventArgs args)
       {
       }
 }


text:
Q: Communicating between two processes This has been discussed before, but I've struggled with the responses, so was hoping for a clearer answer tailored to my situation:
I'm developing an application in C++ under 32-bit Windows (minimum requirement is WinXP) which need to communicate across two processes.
The remit is that process 1 (p1) needs to start process 2 (p2), then call various functions of p2. I need p1 to stop what it is doing until the p2 function that it calls has finished, and then continue where it left off.
What would be the best kind of methods for me to research so that I can do something like this?
All the best,
Chris

A: I know Remote Procedure Call sounds more sexy as it removes the need to design your own "communication protocol" and serialize your own requests and responses, but what about just writing two processes that communicate through an anonymous pipe or socket?
You can have the 2nd process inherit a handle to the pipe/socket.  Then, it can simply serve requests from the 1st process by blocking on the pipe for a request.  The 1st process can simply write a request on the pipe/socket and wait for the reply by blocking on the socket.

A: If it is only about calling functions/methods in the other process and only Windows you can also take a look at Microsoft Remote Procedure Call.
If you need to share lots of data you are better of with the named semaphores and shared memory.

A: Mutexes in Win32 are cross-process synchronization. You could also look into using a condition variable, but I'm not sure if cross-process varieties of those exist.

A: Try reading about Win32 semaphores, perhaps emphasizing semaphore-based Win3e2 events. Events allow p1 <--> p2 communication. If the two processes need to pass a lot of values back and forth, you can read about shared memory. Both of these mechanisms are very standard and usual ways of interprocess communication.


text:
Q: How to remove trailing zeros during deserialization? so, this question here states that removing trailing zeros is a bug... but what if I want that behavior? Is there a way to set this?
input (decimal): 1.99000

should be
output (json): 1.99


text:
Q: Change Windows Background from Python Does anyone know a way to change the Windows Desktop Wallpaper with python so that the change is permanent? I have found this code
import ctypes
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "myimage.jpg" , 0)

This code works, but once you log off and log on again, the background is back to the original image. I would prefer a solution that does not require any registry edit, and I would like something that works with Windows XP and 7 if it is possible.

A: This solution combines several of the comments made, and works for me:
import ctypes
import os
drive = "C:\\"
folder = "images"
image = "test.jpg"
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, image_path, 3)

(Note that you should determine the absolute path to your image, and change as needed.  Also convert the image to BMP if you need to use it on XP.  You can easily convert the image using Pillow)


text:
Q: Does RUBY on RAILS 4.0.2 work with MS SQL Server Express? I've googled this to death and I'm just going around in circles.
I'm on a Windows Server 2008r
I installed and put the following in my Gemfile
gem 'ruby-odbc' # I think the version is the.9999 one?

gem 'tiny_tds', "~> 0.6.1"

gem 'activerecord-sqlserver-adapter' # I've tried a few versions of this 3.2.8 and 4.0

I get varying errors depending on how many times i've bundle installed or updated
Errors include activesupport and activerecord versions not found. They are installed
Or I get alias_method errors.
Can someone just point me in the right direction of what I should do. Some discussions seem to think that there is nothing that works at the moment. Would downgrading to an older Rails work? If so how and which version?

A: activerecord-sqlserver-adapter hasn't been released for Rails 4.0 yet but the gem is 95% ready.  You can use put it in your Gemfile like this:
gem 'activerecord-sqlserver-adapter', github: 'rails-sqlserver/activerecord-sqlserver-adapter'

For a description of the outstanding work take a look at Failed Tests & Segfault on this pull request.


text:
Q: Extracting a list of unique text cells from a large, wide, headerless, mixed format table It should be a quickie to VBA/Excel experts. I have a large 60 to 2000 rows, wide 10,000 columns, table without headers in Excel, with the following format.

+---------+----------------+------------------+----------+
|         |    20110811    |      20110810    |  20110810|
+---------+----------------+------------------+----------+
| AA UN   | 4.0111         |  AA UN           |   5.0222 |
| AXP UN  | 3.0611         |  AXP UN          |   3.0217 |
| BA UN   | 3.997          |  BA UN           |   4.0532 |
| BAC UN  | 0.4924         |  BAC UN          |   0.478  |
| CAT UN  | 5.9259         |  CAT UN          |   5.8959 |
| CSCO UW | 1.0813         |  CSCO UW         |   0.9693 |
| CVX UN  | 6.3891         |  CVX UN          |   6.3943 |
| DD UN   | 3.1894         |  DD UN           |   3.165  |
| DIS UN  | 2.1815         |  DIS UN          |   2.2267 |
| GE UN   | 1.065          |  GE UN           |   1.0654 |
+---------+----------------+------------------+----------+

The question is how to get a unique list of text cells out from the whole table, I have been playing with advanced autofilter but it really doesnt give what i want. Im looking for smth like that below

╔═════════╗
║ AA UN   ║
║ AXP UN  ║
║ BA UN   ║
║ BAC UN  ║
║ CAT UN  ║
║ CSCO UW ║
║ CVX UN  ║
║ DD UN   ║
║ DIS UN  ║
║ GE UN   ║
╚═════════╝

Btw, thanks to GSerg for formatting, now i learnt a new trick

A: One solution is to dump the entire range into a variable array and then loop through it adding entries that aren't numbers into a dictionary object. That will eliminate all dupes and non-numeric data. Take the dictionary keys and transpose them back on the sheet.
UPDATE:
Here is code you can use.
How it works: You'll can adjust the range (right now it's all cells used), but it will dump every cell into a variant array in one shot. Then it goes through the array (much faster than going through cells) and if the entry is not empty, nor numeric, it adds it to a dictionary object. Since you can't put 2 keys that are the same into a dictionary, it just skips over all dupes automatically. Then I paste the unique list into sheet2 (you can adjust this as well).
Sub UniqueTextList()

Application.ScreenUpdating = False
Dim vArray As Variant
Dim i As Long, j As Long
Dim v As Variant
Dim dictionary As Object
Set dictionary = CreateObject("scripting.dictionary")

vArray = ActiveSheet.UsedRange.Value
For i = 1 To UBound(vArray, 1)
    For j = 1 To UBound(vArray, 2)
        If Len(vArray(i, j)) <> 0 Then
            If IsNumeric(vArray(i, j)) = False Then
                dictionary(vArray(i, j)) = 1
            End If
        End If
    Next
Next

Sheet2.range("a1").Resize(dictionary.count).Value = _
Application.Transpose(dictionary.keys)

Application.ScreenUpdating = True
MsgBox dictionary.Count & " unique cell(s) were found and copied."

End Sub

A: My Duplicate Master addin uses a similar approach to Issun
While the bulk of the functionality is aimed as dupes it includes option to extract

*

*Uniques (data that occurs at least once), or

*True Uniques (data that only occurs once)

And it can find uniques as single cells (your case), complete rows, or as a mix of columns
Lastly it has options to

*

*ignore all whitespaces (including CHAR 160)

*ignore Case

*apply TRIM and/or CLEAN functions

*Regexp string substitions


text:
Q: PHP preg_match - matching html elements Ok so I have a regular expression I'm trying to use to match a certain pattern in some html files. Here's the preg_match statement:
preg_match('@<'.$htmlElementType.' id\s*=\s*"{{ALViewElement_'.$this->_elementId.'}}".*>[\s\S]*</'.$htmlElementType.'(>)@i', $htmlString, $newMatches, PREG_OFFSET_CAPTURE)

To be clear, this is attempting to match an html element with an id of {{ALViewElement_.*}} but it also needs to end itself with a closing tag, for example  if $htmlElementType was "section" it would end in "/section>".
If my html looked just like this with nothing else in it, it works as expected:

The problem is when we have a section element later in the html and it ALSO has a closing /section>. Example:

            HEY THIS IS ME

In this case the full mach is everything above. But I want it to stop at the  that opens my first one. This is important because later on in my code I need the location of the last > in that ending tag.
Any ideas how I could change this regular expression a little bit?
Thanks for the help!

A: Yes, just use an ungreedy quantifier:
preg_match('@<'.$htmlElementType.' id\s*=\s*"{{ALViewElement_'.$this->_elementId.'}}".*?>[\s\S]*?</'.$htmlElementType.'(>)@i', $htmlString, $newMatches, PREG_OFFSET_CAPTURE)

another way: with DOMDocument:
$html = <<<LOD

    HEY THIS IS ME

LOD;
$doc= new DOMDocument();
@$doc->loadHTML($html);
$node = $doc->getElementById("{{ALViewElement_resume}}");

$docv = new DOMDocument();
$docv->appendChild($docv->importNode($node, TRUE));
$result = $docv->saveHTML();
echo htmlspecialchars($result);


text:
Q: Is there a way we can enhance the below query in Oracle 12C Is there anyway we can optimize the below query in Oracle 12c to give faster result.
TAB_C - is the main table -2947109424 count and we have index in place on TAB_C(act_id).But still it is taking 3 hours to run in production.
SELECT ta.email_addr_id
                       , ta.email_addr
                        , SUBSTR(ta.email_addr, INSTR(ta.email_addr, '@') + 1,
                           INSTR(ta.email_addr, '.', -1) - INSTR(ta.email_addr, '@')
                           - 1) AS email_domain
                         , mtr.max_email_response_date
                         , ta.add_date
                         , net.num_12mons
                         , net.num_3mons
                          , net.num_6mons
                          , net.num_9mons
                         , ta.hard_bounce_ind
                         , ta.email_addr_text_att_02 AS preference_birth_date
                          ,ta.source AS source
                     FROM Tab_A ta
                     LEFT JOIN (
                         SELECT tr.email_addr_id
                             , tcX(tr.email_response_date) AS max_email_response_date
                         FROM Tab_B tr
                         where tr.email_response_date = 'NEW'
                             AND tr.update_source <> 'EXP_EVENT'
                         GROUP BY tr.email_addr_id
                     ) mtr
                     ON ta.email_addr_id = mtr.email_addr_id
                     LEFT JOIN (
                         SELECT tc.email_addr_id
                             , COUNT(DISTINCT tc.m_act_id) AS num_12mons
                             , COUNT(DISTINCT CASE WHEN ROUND(tc.outbound_date, 'DD')
                                 > (ROUND(sysdate, 'DD') - 90)
                                 THEN tc.m_act_id ELSE NULL END) AS num_3mons
                              , COUNT(DISTINCT CASE WHEN ROUND(tc.outbound_date, 'DD')
                                  > (ROUND(sysdate, 'DD') - 180)
                                  THEN tc.m_act_id ELSE NULL END) AS num_6mons
                              , COUNT(DISTINCT CASE WHEN ROUND(tc.outbound_date, 'DD')
                                  > (ROUND(sysdate, 'DD') - 270)
                                  THEN tc.m_act_id ELSE NULL END) AS num_9mons
                         FROM Tab_C tc
                         INNtr JOIN act a
                         ON tc.act_id = a.act_id
                         where a.channel_code IN ('FM','RM')
                             AND ROUND(tc.outbound_date, 'DD') > (ROUND(sysdate, 'DD') - 365)
                         GROUP BY tc.email_addr_id
                     ) net
                     ON ta.email_addr_id = net.email_addr_id
                     where ta.email_addr_id <> 0 ;

Any insight will be highly appreciated.


text:
Q: Searching for key in a list of dicts in Ansible I've got a list of dictionary that looks similar to the following:
"subnets": [
        {
            "name": "subnet1-name34554",
            "address": "192.168.1.100"
            "id: "id1"
        },
        {
            "name": "subnet2-name67678",
            "addr": "192.168.1.200"
            "id":   "id2"
        },
        {
            "name": "subnet3-name23345",
            "addr": "192.168.1.300"
            "id":   "id3"
        }
    ]

I'm trying to search the dicts with a partial name and return the full name. E.g searching with subnet1 should return subnet1-name34554
If I do something like:
- name: test
  debug: msg="{{ subnets |  selectattr("name", "search", "subnet1") | list  }}"

I get a list with a single dict back:
 [
   {
     "name": "subnet1-name34554",
     "address": "192.168.1.100"
     "id: "id1"
    }
 ]

I'm unsure what the next step to pull just the "name" key is, or if there is a better approach?

A: You get list of dicts (single dict) as a result.
So feed it into first filter to get only first element and then address name property.
- name: test
  debug:
    msg: "{{ (subnets |  selectattr('name', 'search', 'subnet1') | list | first).name }}"