text:
Q: CSS table with fixed column widths and max height I'm trying to create a table with fixed column widths, and also a fixed maximum height, which scrolls beyond the maximum height.
Reading around, I would use table-layout:fixed and specify the column widths to accomplish the first task. I would set max-height, overflow:auto and display:block on the table to accomplish the second.
However, these don't seem to be working together. The columns are approximately half of the intended width.
My attempt:
https://jsfiddle.net/d3y5g9fq/

<colgroup>
  <col style="width: 30%">
  <col style="width: 50%">
  <col style="width: 20%">
</colgroup>

    Col A
    Col B
    Col C

1	2	3

table {
  table-layout: fixed;
  display: block;
  max-height: 100px;
  overflow: auto;
}

A: If you change the column widths from percentages to viewport width (vw) it should work as intended, but not quite as expected. Viewport sizes are supposed to size it according to the size of the full viewport, but if you wrap it in a div with a width of 70%, it will work like a percentage instead of a vw in this scenario.
Using vw with a parent width of 100%:

table {
  table-layout: fixed;
  display: block;
  max-height: 100px;
  overflow: auto;
}

p {
  background-color: blue;
  width: 100%;
}

table, td, th {
  text-align: center;
  border: 1px solid black;
}

Hi!

<colgroup>
  <col style="width: 30vw">
  <col style="width: 50vw">
  <col style="width: 20vw">
</colgroup>

    Col A
    Col B
    Col C

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

Using vw with a parent width of 70%:

table {
  table-layout: fixed;
  display: block;
  max-height: 100px;
  overflow: auto;
}

p {
  background-color: blue;
  width: 100%;
}

table, td, th {
  text-align: center;
  border: 1px solid black;
}

Hi!

<colgroup>
  <col style="width: 30vw">
  <col style="width: 50vw">
  <col style="width: 20vw">
</colgroup>

    Col A
    Col B
    Col C

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

Not quite what you would expect... why? There are a very tiny amount of scenarios where vw and vh do not work as intended. I've never quite found out why myself, but I would guess it is misinterpreting the viewport as a single element for some reason.
If you want to be syntactically correct, you could also use em instead of vw, which will give you the exact same results:
Using em with a parent width of 100%:

table {
  table-layout: fixed;
  display: block;
  max-height: 100px;
  overflow: auto;
}

p {
  background-color: blue;
  width: 100%;
}

table, td, th {
  text-align: center;
  border: 1px solid black;
}

Hi!

<colgroup>
  <col style="width: 30em">
  <col style="width: 50em">
  <col style="width: 20em">
</colgroup>

    Col A
    Col B
    Col C

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

Using em with a parent width of 70%:

table {
  table-layout: fixed;
  display: block;
  max-height: 100px;
  overflow: auto;
}

p {
  background-color: blue;
  width: 100%;
}

table, td, th {
  text-align: center;
  border: 1px solid black;
}

Hi!

<colgroup>
  <col style="width: 30em">
  <col style="width: 50em">
  <col style="width: 20em">
</colgroup>

    Col A
    Col B
    Col C

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3

1	2	3


text:
Q: Why does `xmodmap` not always load `.Xmodmap` on login? I've got the following in the file ~/.Xmodmap
! change CapsLock to Escape
clear Lock
keycode 0x42 = Escape

It remaps the CapsLock key to Escape, and works pretty well, when I issue the comman xmodmap ~/.Xmodmap. However, it does not always work when I boot my laptop. But sometimes it works!
Does anyone have a clue what's going on? How can I try to troubleshoot this?

A: I would look into ~/.xinitrc,
but there is a myriad of other possibilities depending on your window
manager or desktop environment (see, for example, How do I set Xmodmap on login?). There is not enough information in the question to find it out.
But remapping CapsLock to Escape is one of the canonical mappings provided
by the the XKB extension, as listed in man xkeyboard-config.
Just issue
setxkbmap -option 'caps:escape'

and voilà, CapsLock is an Escape. It can be made persistent
by editing the "XKBOPTIONS" line of /etc/default/keyboard:
XKBOPTIONS="caps:escape"

Debian and Ubuntu set the keyboard based on that very file, so it is a reliable solution. You can delete .Xmodmap then and just make sure no other program meddles with the keymap.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting multiple loads to an extension cord We have a garage at our house and whilst there is electricity going to it, it's basically just one outlet connected to our second fridge/freezer via a 15A extension cord.
I was wondering if it would be okay to plug the refrigerator (not sure what wattage it is), my soldering iron (90W and has a 500mA fuse), one 24 inch monitor and potentially a laptop charger?
Basically i am not allowed to solder inside the home and was hoping to have this as a set up. It's only temporary as i will hopefully move out this year. What can i do to make this a-little safer?
Edit: The Fridge/Freezer is 800 Watts, the soldering iron is 90W, the monitor is 25W, charger 90W and i'd like to connect a usb hub which is 90W also).
So considering my load is approximately 1100W. My extension being able to supply 230V at 15 A = 3450W. Does it mean it's adequate? Thanks!

A: Look at the nameplates of all the loads in question -- they should list current.  Add up the currents -- if it's less than 15A, then as far as the circuit goes, you're OK.  The more that it's less than 15A, the more OK you are.
At least in the US, extension cords can be rated for less than the current of the outlet they're plugged into.  This can cause problems.
The safe thing to do is to check the extension cord & see if it's rated (in the US, if it's new, there'll be a tag), then make sure you're not pulling more than it's rated for.  Better yet would be to run a second extension cord from that outlet to power your bench.  Extension cords cost a lot less than houses.
I'm the sort who regularly concerns my family and friends with my safety practices, so if I were at less than 15A of the circuit but suspect the extension cord of being on the edge of suitability, I'd go ahead and use it.  But I'd plug everything in and check the extension cord for heating (just hold it in your hand, or coil up some of it tight and hold that in your hand).  I'd also inspect the thing for wear.


text:
Q: Which dragon did hurt Thranduil? When Thorin and Thranduil discuss in Mirkwood, Thranduil said: ''Do not talk to me about the dragon fire. I know what's rage and ruin!'', and shows Thorin his destroyed face for a moment, then says: ''I have faced the great snakes from the north.'' Which dragons did hurt him and when?

A: Thranduil would also be very old, a survivor of Doriath in the First Age during the War of Wrath where a lot of dragons (named and unnamed) seen action. So presumably it was there where he encountered the dragon that scared him.
Depending on how you do the math it was roughly 6,000 years between the events of the Hobbit and the War of Wrath if I'm not mistaken. That's a long time for him to encounter something.


text:
Q: pchisq with right command but wrong answer Calculate the probability P(X > 20), when X is chi-squared distributed with 10 degrees of freedom. Use command pchisq() to calculate the probability.
Save probability P(X > 20) to the variable ans rounded to four decimal places. Note that with argument lower.tail in pchisq() we can define if we want to calculate probability P(X < 20) or probability P(X>20). Using lower.tail=TRUE gives the probability P(X < 20) and lower.tail=FALSE gives the P(X>20).
This is the question i have from an exercise. I am using following command:
 pchisq(20, df=10, lower.tail = FALSE)

and rounding it to four digit but it is still not giving the right answer. Is there anything wrong in my command?


text:
Q: Is it possible to detect idle time even across tabs? I have a script that sends a time-sensitive notification to users when there is a new question directed to them. However, I found that some people leave their computers open and go grab lunch, therefore missing notifications.
I'm looking to put together a script that detects if the user is idle for 5 minutes, and if so, it would show them as 'offline' and close down notifications.
I was curious if it is possible to detect inactivity even across tabs? (for example if a user switches to another tab to Facebook.com and stays active there, they would be seen as 'active' even though they are not on our webpage specifically).

A: Everything that happens when the user is NOT on your side is impossible to track (luckily).
So not this is not possible (think about the security).
UPDATE
Now that I think of it. It is possible, however very unlikely that you can do it. If your name would have been Google you would have come a long way, because lots of websites use Google analytics. But other than that: NO not possible for reasons mentioned.

A: Store their last activity in a database table when they are active.  You can use mouse movement, keypresses, or some other activity to update the timestamp.  Periodically poll that table with an ajax call on the page on which the user would see their online/offline status.  If the last active time is > 5 minutes, show them as offline or idle.

A: if I am on such a thing I use either the HTML5 Visibility API or fallback to blur and focus events observing when the user left the page and then returns... leaving means unfocus the browser window or tab (but still keeping the page open)
but since you wanna react on inactivity... hmmm you could start a timeout (of course that would need a global event delegation for many events to stop it if something happens like submit, click, change, mousemove and so on)

A: Code is:
var inactivityTime = function () {
    var t;
    window.onload = resetTimer;
    document.onmousemove = resetTimer;
    document.onkeypress = resetTimer;

    function logout() {
        alert("You are now logged out.")
        //location.href = 'logout.php'
    }

    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 3000)
        // 1000 milisec = 1 sec
    }
};

A: I wanted to implement this functionality on my clients website. Didnt find any idleal solution for this in web.Finally I had to twig my code,think of some logic and implement this.The code goes as below--
     `/*Put this code inside script tag whereever you want to execute the inactivity popup*/
     var t;
    //set the timeout period
    var timeoutPeriod = '${inactiveIntervalMillis}';
    //detect various events
    callUserEvents();
     `

//remove the logged Out storage after popup is closed by user
function removeLocalStorage() {
localStorage.removeItem("loggedOut");
}
//call this function whenever we detect user activity
function resetUserActivity() {
resetTimer();
}
//If the user is logged out and it clicks on other tabs,the popup will be               displayed there too
function checkIfUserLoggedOut() {
    if (localStorage.getItem("loggedOut")) {
        loadLoginModal("/includes/gadgets/popup-content.jsp", 400, 230,
            undefined);
    }
}

// Call this method when any window onloads,this helps to check if multiple         tabs are opened by same site
function incrementCounter() {
    checkIfUserLoggedOut();
    if (localStorage.getItem("counter") == "NaN") {
        localStorage.setItem("counter", "0");
    } else {
        var counter = parseInt(localStorage.getItem("counter")) + 1;
        localStorage.setItem("counter", counter);
    }
    resetTimer();
}
//after time interval,this method will be called
function handleIdleTimedOut() {
//get the current localStorage Object
    window.sharedCounter = localStorage.getItem("counter");
//If no tabs are opened,then popup will be shown here.
    if (window.localCounter == window.sharedCounter) {
        loadLoginModal("/includes/gadgets/popup-content.jsp", 400,               230,undefined);
        localStorage.setItem("loggedOut", "true");
    }
}

function resetTimer() {
//save counterin current Window object,and after timeout period you can     match   it,if by chance multiple tabs were opened,the counter will be     different,popup  wont be shown in current window at incorrect time.
    window.localCounter = localStorage.getItem("counter");
    clearTimeout(t);
    t = setTimeout(handleIdleTimedOut, timeoutPeriod);
}
function callUserEvents(){
window.onload=incrementCounter
window.onscroll = resetUserActivity;
window.onmousemove = resetUserActivity;
window.ondblclick = resetUserActivity;
window.oncontextmenu = resetUserActivity;
window.onclick = resetUserActivity;
window.onkeypress = resetUserActivity;
window.onpageshow = resetUserActivity;
window.onresize = resetUserActivity;
window.onfocus = incrementCounter;
window.ondrag = resetUserActivity;
window.oncopy = resetUserActivity;
window.oncut = resetUserActivity;
window.onpaste = resetUserActivity;
}

`


text:
Q: Django staticfiles_dirs not working correctly I'm working with this website http://fotokluczniok.pl/ now.
If You press F12 You will see the staticfiles do not work correctly.
Here is my seetings.py code:
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
    '/home/fotoklu/fotokluczniok/static/',
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')

Here is urls.py code:
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Project structure: CLICK HERE
How to solve this problem ?

A: I think you don't need to change something about the static files in the urls.py file. And also delete the variable STATIC_ROOT. In general your code in Settings.py file:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
     os.path.join (BASE_DIR, 'static'),
]

I also had this problem. It helped me.
NOTE: Always restart the server after changes in settings.py


text:
Q: Batch o Powershell para alinear particiones de un disco duro? Buenas. Me preguntaba si sería posible alinear las particiones mediante un script de batch o powershell en Windows 7 en adelante.
Se que hay software de terceros que lo hacen pero sería posible hacerlo mediante un script?
Supongo que llevaría tiempo.
No sé si sería factible, pero el procedimiento creo que podría ser el siguiente:

*

*Ver si hay espacio suficiente en el disco actual o un disco externo para hacer una copia temporal del contenido de las particiones a alinear.

*poner el conteido de la partición de sistema en C: por si acaso y borrar la particion de sistema (la de 100MB)

*hacer una copia del contenido de las particiones.

*Borrar particiones guardando la configuración previa de cada uan para crearlas igual después.

*Crear las particiones ya alineandolas debidamente.

*Volver a copiar el contenido de las particiones y copiar el contenido de "sistema" de nuevo en la partición si se quisiera.

Sería algo así posible? Existe algo parecido?


text:
Q: Filling 64 bit numpy array in Cython slower than 32 bit array I am trying to understand why filling a 64 bit array is slower than filling a 32 bit array.
Here are the examples:
@cython.boundscheck(False)
@cython.wraparound(False)
def test32(long long int size):
   cdef np.ndarray[np.int32_t,ndim=1] index = np.zeros(size, np.int32)
   cdef Py_ssize_t i

   for i in range(size):
       index[i] = i

   return indx

@cython.boundscheck(False)
@cython.wraparound(False)
def test64(long long int size):
   cdef np.ndarray[np.int64_t,ndim=1] index = np.zeros(size, np.int64)
   cdef Py_ssize_t i

   for i in range(size):
       index[i] = i

   return indx

The timings:
In [4]: %timeit test32(1000000)
1000 loops, best of 3: 1.13 ms over loop

In [5]: %timeit test64(1000000)
100 loops, best of 3: 2.04 ms per loop

I am using a 64 bit computer and the Visual C++ for Python (9.0) compiler.
Edit:
Initializing a 64bit array and a 32bit array seems to be taking the same amount of time, which means the time difference is due to the filling process.
In [8]: %timeit np.zeros(1000000,'int32')
100000 loops, best of 3: 2.49 μs per loop

In [9]: %timeit np.zeros(1000000,'int64')
100000 loops, best of 3: 2.49 μs per loop

Edit2:
As DavidW points out, this behavior can be replicated with np.arange, which means that this is expected:
In [7]: %timeit np.arange(1000000,dtype='int32')
10 loops, best of 3: 1.22 ms per loop

In [8]: %timeit np.arange(1000000,dtype='int64')
10 loops, best of 3: 2.03 ms per loop

A: A quick set of measurements (which I initially posted in the comments) suggests that you see very similar behaviour (64 bits taking twice as long as 32 bits) for np.full, np.ones and np.arange, with all three showing similar times to each other (arange being about 10% slower than the other 2 for me).
I believe this suggests that this is expected behaviour and just the time it takes to fill the memory. (64 bits obviously has twice as much memory as 32 bits).
The interesting question is then why np.zeros is so uniform (and fast) - a complete answer is probably given in this C-based question but the basic summary is that allocating zeros (as done by the C function calloc) can be done lazily - i.e. it doesn't actually allocate or fill much until you actually try to write to the memory.


text:
Q: Is the Alexander horned sphere a cofibration? The Alexander horned sphere is a closed embedding of $S^2$ into $S^3$ which is not flat because otherwise the Schoenflies Theorem would be true for it. However, not being flat is not  the same as not being able to find a neighborhood deformation retract. I suspect the answer to the question is no, but I have no valid argument. To be precise, let $\iota:S^2\hookrightarrow S^3$ be the embedding whose image is the Alexander horned sphere. Is $\iota$ a cofibration?

A: We'll make use of the following.

If $X$ is an ANR and $j:A\subseteq X$ is a closed subspace, then $A$ is an ANR if and only if the inclusion $j$ is a cofibration.

I don't know a good reference for this, although I suspect it may be in Borsuk's book in some form or another. A reference I do have which will cover the case at hand is found in chapter 3 of Daverman's book Decompositions of Manifolds, where Theorem 6 states that

If $A$ is a closed subset of a metric space $X$, then $A$ has HEP in $X$ with respect to every ANR $Y$.

The point is that if $A$ is itself an ANR, then so is $A\times I$, and in particular also the mapping cyclinder $M_j=A\times I\cup X\times 0$. In this case we see that $j:A\subseteq X$ is a cofibration by noticing that it satisfies the HEP with respect to $M_j$ (i.e. we show that $M_j$ is a retract of $X\times I$).
The point of course is that $S^3$ is an ANR, as is any closed subspace $A\subseteq S^3$ which is homeomorphic to $S^2$.


text:
Q: Calculate only distinct rows So I have a database table:
projectNo| process | studio     | requiredNo |
---------+---------+------------+------------+
16090001 | ANM     | APEX       | 10         |
16090001 | ANM     | BASECAMP   | 10         |
16090001 | BGD     | CANVAS     | 15         |
16090001 | BGD     | PALETTE    | 15         |

I want to calculate required number. But when I do
SELECT SUM(requiredNo) FROM process WHERE projectNo='$projectNo'

I get 50. But it should be 25 only, because process is the same but studio is defferent. However I need to calculate by process. So how can I calculate only distinct processes?

A: select sum(mreq)
from
(
    select max(requiredNo) as mreq
    from process
    where projectNo='$projectNo'
    group by process
) tmp

The inner select gets the highest requiredNo for each process. The outer select sums that up.


text:
Q: Javascript/Google Maps API - "TypeError: undefined is not an object (evaluating 'addresses[x][0]') I am trying to plot markers on a google map using an array of addresses. The markers are correctly plotting (I used the tips in this post: Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad) but I am getting this error when I try to add information from the addresses array into the marker and infowindow: "TypeError: undefined is not an object (evaluating 'addresses[x][0]')"
The problem appears to be that within the 'for' loop, x evaluates to the length of the array, 4, every time I loop.
The markers and infowindows are working; they show up when I use a string or I use addresses[0], addresses[1], etc., but everything breaks when I try to do addresses[x] because addresses[4] does not exist. Any pointers at how I can iterate through my addresses array to properly set my marker titles and infowindows?
Note: in case it's relevant, there is a reason the addresses variable is declared inside the calcRoute() function.
This is the code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  geocoder = new google.maps.Geocoder();
  var mapOptions = {
    zoom:7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var addresses = [["Beaver Creek Smokehouse","4.5",["601 Main St","Martinez, CA 94553"]],["Lemongrass Bistro","4.5",["501 Main St","Martinez, CA 94553"]],["Picnicky's Sandwich Shop","4.0",["3833 Sonoma Blvd","Vallejo, CA 94590"]],["LV Vietnamese Pho and Sandwiches","4.0",["2621 Springs Rd","Vallejo, CA 94591"]]];
      var infowindow = new google.maps.InfoWindow();
      var marker, x;

      //This is the problem area:
      for (x = 0; x < addresses.length; x++) {
        jQuery.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x][2]+'&sensor=false', null, function (data) {
          console.log(x); // logs the length of array, 4, every time
          var p = data.results[0].geometry.location;
          var latlng = new google.maps.LatLng(p.lat, p.lng);

          marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: 'this works' // markers don't show when I use addresses[x][0]
          });
          google.maps.event.addListener(marker, 'click', (function(marker, x) {
            return function () {
            infowindow.setContent(addresses[x][0]);
            infowindow.open(map,marker);

            };
          })(marker, x));
        });
      }
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

A: The geocoder is asynchronous.  Inside the callback function, x == addresses.length.  You are using function closure to capture its value for the infowindow, you need to do the same for instantiating the marker.
//This is the problem area:
for (x = 0; x < addresses.length; x++) {
    jQuery.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x][2]+'&sensor=false', null, function (data) {
        console.log(x); // logs the length of array, 4, every time
        var p = data.results[0].geometry.location;
        var latlng = new google.maps.LatLng(p.lat, p.lng);
        createMarker(latlng, x);
    });
}
function createMarker(latlng, x) {
    marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: addresses[x][0]
    });
    google.maps.event.addListener(marker, 'click', (function(marker, x) {
        return function () {
          infowindow.setContent(addresses[x][0]);
          infowindow.open(map,marker);

        };
    })(marker, x));
}


text:
Q: How can I set a constraint before plotting some curve (pgfplot) I'm trying to set some constraint for a predefined function (see code below) before the plotting, to avoid changes on the functions.
The constraint must be #6+#7=constant, so I can choose the constant.
As you can see on the code, my attempt to solve this was writing 'x' for the parameter #6 and '50-x' for #7. But I don't know if this is the right and the only way one can set this constraint without making any modifications on the \def functions.
(Sorry for the bad english)
\documentclass{standalone}
\usepackage[brazilian]{babel}
\usepackage{amsmath,amsfonts,physics,amssymb,mathtools,upgreek,bm}
\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.13,translate gnuplot=true}
\usepackage{xargs}
\usepackage{scalerel,relsize}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Definindo a Função IC50 %%%%%%%%%%%%%%%%%%%%

\def\g(#1,#2,#3,#4,#5,#6,#7,#8,#9){(#6)*exp(-(#2))+((#6)**2)*exp(2*(-(#2)))*(#9)*exp((#4))}%

\def\f(#1,#2,#3,#4,#5,#6,#7,#8,#9){1+2*(#6)*exp(-(#2))+((#6)**2)*exp(2*(-(#2)))*exp((#4))}%

\def\h(#1,#2,#3,#4,#5,#6,#7,#8,#9){2*(#7)*exp(-(#1)) +exp( (#3) )*( (#7)*exp(-(#1) ) )^2 + 2*(#6)*exp(-(#2))*(#7)*exp(-(#1) )*exp((#5)) }%

\def\v(#1,#2,#3,#4,#5,#6,#7,#8,#9){( \g(#1,#2,#3,#4,#5,#6,#7,#8,#9) + (#6)*exp(-(#2))*(#7)*exp(-(#1))*(#8)*exp((#5)) )/( \f(#1,#2,#3,#4,#5,#6,#7,#8,#9) + \h(#1,#2,#3,#4,#5,#6,#7,#8,#9) )}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}
\begin{tikzpicture}

\begin{axis}[
            tick label style={font=\scriptsize},
        label style={font=\scriptsize},
            xlabel=${[S](\upmu M)}$ / ${[H_2O]}$,
            ylabel=${ ({d[P]}/{dt})(2K_{cat}[E_{tot}])^{-1}}$,
            legend pos=north east,
            grid=major,
            ymax=1, ymin=0,
            xmax=50, xmin=1,
            x dir=reverse,
            ]

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 \addplot[red,mark=none,domain=0.0001:200,samples=250, line width=1]
  gnuplot { \v((-12),(-12),0,0,0,x/10^6,(50-x)/10^6,1,1) };
\end{axis}

\end{tikzpicture}

\end{document}


text:
Q: Angular2 - View updates for some values but not others when subscribing to observable I'm trying to set up a catalog of items that can be searched through. My catalog component has a few subscriptions to observables. Whenever the search term is updated, it will apply that query to a list of items and return the matching ones. The search function is located in a separate component which does the filtering and sends a value to the searchService to indicate when it starts and stops searching. I want to tap into this value change with a separate loader subscription and update the "isLoading" boolean to display a spinner when the search function is running.
catalog.cmp.ts:
ngOnInit(){
    this.dataService.getData().subscribe((res) =>{
        this.stock = res;
        this.allstock = res;
    });

    this.searchsubscription = this.searchService.termUpdate$.subscribe(
            (item) => {
                this.searchTerm = item;
                //the following searches through the allstock array and returns the list to be displayed with ngFor
                this.stock = this.search.transform(this.allstock,{query:this.searchTerm})
            },
            (err) => {console.log(err)}
     );

     this.loadsubscription = this.searchService.loadUpdate$.subscribe(
         (res) => {
            this.toggleLoader(res)
         },
         (err) => {console.log(err)}
     );
}

The toggleLoader() function looks like this:
toggleLoader(state){
    this.isLoading = state;
    console.log("ISLOADING",this.isLoading)
}

search.service.ts:
export class SearchService {
private isLoading;
private searchTerm = '';
private termSource = new BehaviorSubject<any>('');
termUpdate$ = this.termSource.asObservable();
private loadSource = new BehaviorSubject<boolean>(false);
loadUpdate$ = this.loadSource.asObservable();

constructor(){}

setTerm(term){
    this.searchTerm = term;
    this.termSource.next(term);
    console.log(this.searchTerm, 'term updated')
}
getTerm(){
    return this.searchTerm;
}
setLoadState(state: boolean){
    this.isLoading = state;
    this.loadSource.next(state);
    console.log(this.isLoading, 'loading status')
}
getLoadState(){
    return this.isLoading;
}

}
In my component template, I have this setup:
<div>{{isLoading}}, {{searchTerm}} <-- this part is for debugging
    <spinner *ngIf="isLoading"></spinner>
    <button (click)="toggleLoader(true)">true</button>
    <button (click)="toggleLoader(false)">false</button>
</div>
<span *ngIf="!isLoading">
    <div class="row"
    *ngFor="let item of stock| paginate: { itemsPerPage: 10, currentPage: p }">
    ...
    </div>
</span>

So every aspect of the view updates fine except for the isLoading value. But the correct value of isLoading displays in the console and at the right times (true when the search term is sent and the filter is running, and false when the new stock array is returned and ngfor updates). The change just isn't being detected in the view. My toggleLoader debugging buttons will update the view properly however.
I've tried many of the solutions posted in similar questions, such as wrapping the body of toggleLoader in zone.run() or calling change detection manually with ChangeDetectorRef. I can even try not using the loadsubscription and instead call toggleLoader before I call search.transform and again when it's done, like so:
this.searchsubscription = this.searchService.termUpdate$.subscribe(
        (item) => {
            this.searchTerm = item;
            this.toggleLoader(true); //the console is still updated at the correct times with this method
            this.stock = this.search.transform(this.allstock,{query:this.searchTerm})
            this.toggleLoader(false);
        },
        (err) => {console.log(err)}
 );

Minimal plunker:  https://plnkr.co/edit/lD4gZq
Note: In the full app, the searchbar is not a child component of the catalog, which is why the search term updating is going through an external service to being with.
I've been researching change detection and trying to fix this for a while now but I honestly can't figure out why this doesn't work. Any help would be appreciated. Thanks.


text:
Q: how to crop top,left,right and bottom portion of imageview in android In my application i am getting transparent pixels in my Imageview while taking screenshot.How to cut top,left,right and bottom portion of Imageview.I tried below code but not working
Bitmap bitmap = Bitmap.createBitmap(imgView.getWidth(),imgView.getHeight(),                   Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
imgView.draw(canvas);
Bitmap result =Bitmap.createBitmap(bitmap,imgView.getLeft()+10, imgView.getTop()+50,    imgView.getWidth()-20, imgView.getHeight()-100);
 bitmap.recycle();

please help me to solve this issue.

A: I am not very sure what are you referring with "not working", but from first sight I would suggest you to change from
Bitmap result =Bitmap.createBitmap(bitmap,imgView.getLeft()+10, imgView.getTop()+50,    imgView.getWidth()-20, imgView.getHeight()-100);

to
Bitmap result =Bitmap.createBitmap(bitmap, 10, 50, bitmap.getWidth()-20, bitmap.getHeight()-100);

But I would not recommend you to use this kind of approach which explicitly setting width and height value.


text:
Q: SQL sub queries error select(select SUM(HOME_SCORE) total from MATCH )
        +
(select SUM(AWAY_SCORE) total from MATCH)
as "GOALS SCORED"
From dual ;

this is meant to return the sum of HOME_SCORE and AWAY_SCORE I get the following error

Error starting at line : 242 in command -
  select(select SUM(HOME_SCORE) total from MATCH )
  Error report -
  Unknown Command
Error starting at line : 243 in command -
  +
  Error report -
  Unknown Command
Query Run In:Query Result

A: Maybe your lacking in parenthesis if you want that way please rewrite your script to this select((select SUM(HOME_SCORE) total from MATCH )
        +
(select SUM(AWAY_SCORE) total from MATCH))
as "GOALS SCORED"
From dual ;
or to simplify this you can try this select(select SUM(HOME_SCORE) + SUM(AWAY_SCORE) total from MATCH )
as "GOALS SCORED"
From dual ;


text:
Q: Generate redeem code In-app billing In my application the user should have the ability to buy a code that he is able to redeem on another device. The problem with this is that In-app billing doesn't automatically generate a code for you. However, it does generate a purchase token. I have come up with two possible solutions, but I don't know what to do. Here are my options:

*

*Use an algorithm to make the purchase token shorter and use that as the code. (Not sure if this will have security concerns as the code may be redeems from another device.)

*Use a server and the Purchase Status to generate a code and manage the available and used codes.

A: This is very bold to implement something like this. If you want to give users opportunity to give codes to others as a present, then you will need to have a server and keep your codes, as well as information on who and when redeemed it on the server. And this must be very secure and very reliable. This sounds as the option two.


text:
Q: Calling java -jar command using AWS lambda steps I have 4 shell scripts which I embedded in java code and converted into jar. I also have a lambda AWS function which brings up the EMR cluster. In lambda function, I should run the generated jar (java -jar /home/hadoop/aws.jar) using steps. I have bootstrap actions where I am setting few environmental variables when the cluster is bought up. So ideally, after the cluster is up the cluster should run the java -jar command which was specified in steps values in json events.
But the problem is the emr is terminating failing in the step jar command. Is there any other way to run the java -jar command from lambda using steps.
    "Steps":[
        {
            "Name": "Setup hadoop debugging",
            "ActionOnFailure": "TERMINATE_CLUSTER",
            "HadoopJarStep": {
                "Jar": "command-runner.jar",
                "Args": [
                    "state-pusher-script"
                ]
            }
        },
        {
            "Name": "Execute Step JAR",
            "ActionOnFailure": "TERMINATE_CLUSTER",
            "HadoopJarStep": {
                "Jar": "command-runner.jar",
                "Args":[
                    "java -jar /home/hadoop/lib/aws-add-step-emr-0.0.1-SNAPSHOT-shaded.jar"
                ]
            }
        }
    ],
    "BootstrapActions":[
        {
            "Name": "Custom action",
            "ScriptBootstrapAction": {
                "Path": "s3://aws-east-1/bootstrap/init.sh"
            }
        }]


text:
Q: display one2many values of a model in a wizard I have a class salesin which has a one2many field emidetails . Here i defined abutton that directs to a wizard saleswizard . What i need to acheive is when i click the button , the wizard that opens should contain the emidetails one2many field of salesin class .. How to
'''
     class Salesin(models.Model):

   _inherit = 'sale.order'

    amount = fields.Integer(string="Total Amount")
    product = fields.Char(string="Product")
    paymenttype = fields.Selection([('Full Payment', 'Full Payment'), ('EMI', 'EMI'), ],
    string=" Payment Type : ", default='Full Payment')
    emidetails = fields.One2many(comodel_name="emidetails",inverse_name="saleorder",string="Emi Details",onchange="restrict")

   @api.multi
   def cnfirm(self):
   result = {
    'view_type': 'form',
    'view_mode': 'form',
    'res_model': 'confirmbox',
    'name': 'Confirm the Quantities Currently Have',
    'type': 'ir.actions.act_window',
    'target': 'new',

      }
    return result

 class emidetails(models.Model):

_name = "emidetails"
saleorder = fields.Many2one( comodel_name="sale.order' ,string="SO")
 installment = fields.Selection([('Level 1', '1st Installment'), ('Level 2', '2nd
 Installment'), ('Level 3', '3rd Installment'), ],
                           string=" Installment : ",)
 amount = fields.Char(string="Amount:",onchange="calculate_med")
  date = fields.Date(string="Due Date")
 cust = fields.Many2one(comodel_name="sale.order")
  status = fields.Selection([('Pending', 'Pending'), ('Paid', 'Paid'), ],
                           string=" Status : ",)

 class saleswizard(models.TransientMOdel) :
  _name = saleswiz
 emidetails = fields.One2many
  (comodel_name="emidetails",inverse_name="saleorder",string="Emi
  Details",onchange="restrict")

A: Use a Many2many field:
emidetails = fields.Many2many("emidetails", string="EmiDetails")

And passe default values in context:
@api.multi
def cnfirm(self):
    self.ensure_one()
    emidetails = [(4, emit.id, 0) for emit in self.emidetails]
    result = {
        'view_type': 'form',
        'view_mode': 'form',
        'res_model': 'saleswiz',
        'name': 'Confirm the Quantities Currently Have',
        'type': 'ir.actions.act_window',
        'target': 'new',
        'context': {'default_emidetails': emidetails}

    }
    return result


text:
Q: How to install tkinter *properly*? I am following Matplotlib of this tutorial. Initially I ran

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

When I ran the following

plt.plot(x, y)

It threw the following
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/media/abhisek/np/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3307, in plot
    ax = gca()
  File "/media/abhisek/np/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 950, in gca
    return gcf().gca(**kwargs)
  File "/media/abhisek/np/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 586, in gcf
    return figure()
  File "/media/abhisek/np/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 535, in figure
    **kwargs)
  File "/media/abhisek/np/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/media/abhisek/np/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1818, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: Can't find a usable tk.tcl in the following directories:
    /usr/share/tcltk/tcl8.6/tk8.6 /usr/share/tcltk/tk8.6 /media/abhisek/np/lib/tk8.6 /usr/local/lib/tcltk/tk8.6 /usr/local/share/tcltk/tk8.6 /usr/lib/tcltk/x86_64-linux-gnu/tk8.6 /usr/lib/tcltk/tk8.6 /usr/lib/tcltk/tcl8.6/tk8.6 /usr/lib/tk8.6 /media/abhisek/lib/tk8.6 /media/abhisek/np/library

This probably means that tk wasn't installed properly.

I'm running ubuntu 16.04 LTS(64 bit) and I'm not finding any of the information found in google is usefull or may be it is just me. Can you tell how to solve this problem and what caused this problem to occur ?


text:
Q: How to able CI to continue working after it finishes e2e test I have this test running on CI but after it finishes it stall the whole process. How can I able to stop or allow to process to continue with Deploy?
[1]   Audit Log Viewer - Grid
[1]     ✓ should not show extra columns when moving from "asset/alert/cases" to other application
[1]
[1] Executed 1 of 20 specs INCOMPLETE (19 SKIPPED) in 20 secs.
[1] [12:14:11] I/launcher - 0 instance(s) of WebDriver still running
[1] [12:14:11] I/launcher - chrome #01 passed
[1] ng e2e -s false -pc proxy.conf.json exited with code 0

Stack:
 1. Angular 5.x
 2. Typescript
 3. Angular-Cli

A: Answer: I was using concurrently /dist/app.js && npm run e2e
I separated the calls and killing the /dist/app.js process after the tests are finished running.
That way it allows me to invoke npm run e2e without stalling the process.


text:
Q: "Zombie" file in ntfs drive In my Ubuntu 20.04 machine, I have an NTFS partition as main file storage, along with the Ubuntu partition and a third one with Windows 10. In the NTFS partition I have a file I cannot delete, rename or chown, although I can modify the contents of the file.
ls -la of the file:
-rwxrwxrwx 1 root root     5 mar  5 12:06 'the file'

fstab entry of the NTFS partition (mounted at startup)
/dev/disk/by-uuid/64DBF6E943285BF9 /media/user/the_drive auto nosuid,nodev,nofail,x-gvfs-show 0 0

How can I delete it?


text:
Q: Expressing any given number in terms of million I am looking for a jquery function to express  any given number in terms of million.
For eg
1,000,000 = 1,

450,0000 = 0.45,

25,000 = 0.025,

500,780,000 = 500.78

Without converting them to string is it possible to achieve this using jquery or javascript.
Thank you
Update: The comma is only for readability so these will be ignored during actual calculation.

A: Yes you can.
Just divide the number by 1000000 and use parseInt. Also you can keep the commas if you use parseInt
parseInt('1,000,000'.replace(/,/g, ''))/1000000 = 1
parseInt('450,000'.replace(/,/g, ''))/1000000 = 0.45
And so on...

Also if the numbers will be floats you can do
parseFloat('1,000,000'.replace(/,/g, ''))/1000000 = 1
parseFloat('450,000'.replace(/,/g, ''))/1000000 = 0.45

Update: Here is the Fiddle http://jsfiddle.net/E4UCL/1/


text:
Q: is it safe that multi elastic search client create the same index at the same time? is it safe that multi elastic search client create the same index at the same time?
An example is using date as index name, when a new day came, many clients will try to write to a not exist index, and this will lead to create a new index.
I didn't found related information from official documents.

A: The problem with writing to a non existing index is that it creates an index(probably without the mapping that you wish for). However you don't need to worry about creating another index with the same name because it won't happen.


text:
Q: Fold that's both constant-space and short-circuiting I'm trying to build a Haskell function that does basically the same thing as Prelude's product. Unlike that function, however, it should have these two properties:

*

*It should operate in constant space (ignoring the fact that some numeric types like Integer aren't). For example, I want myProduct (replicate 100000000 1) to eventually return 1, unlike Prelude's product which uses up all of my RAM and then gives *** Exception: stack overflow.

*It should short-circuit when it encounters a 0. For example, I want myProduct (0:undefined) to return 0, unlike Prelude's product which gives *** Exception: Prelude.undefined.

Here's what I've come up with so far:
myProduct :: (Eq n, Num n) => [n] -> n
myProduct = go 1
  where go acc (x:xs) = if x == 0 then 0 else acc `seq` go (acc * x) xs
        go acc []     = acc

That works exactly how I want it to for lists, but I'd like to generalize it to have type (Foldable t, Eq n, Num n) => t n -> n. Is it possible to do this with any of the folds? If I just use foldr, then it will short-circuit but won't be constant-space, and if I just use foldl', then it will be constant-space but won't short-circuit.

A: If you spell your function slightly differently, it's more obvious how to turn it into a foldr. Namely:
myProduct :: (Eq n, Num n) => [n] -> n
myProduct = flip go 1 where
    go (x:xs) = if x == 0 then \acc -> 0 else \acc -> acc `seq` go xs (acc * x)
    go [] = \acc -> acc

Now go has got that foldr flavor, and we can just fill in the holes.
myProduct :: (Foldable t, Eq n, Num n) => t n -> n
myProduct = flip go 1 where
    go = foldr
        (\x f -> if x == 0 then \acc -> 0 else \acc -> acc `seq` f (acc * x))
        (\acc -> acc)

Hopefully you can see where each of those pieces came from in the previous explicit-recursion style and how mechanical the transformation is. Then I'd make a few aesthetic tweaks:
myProduct :: (Foldable t, Eq n, Num n) => t n -> n
myProduct xs = foldr step id xs 1 where
    step 0 f acc = 0
    step x f acc = f $! acc * x

And we're all done! A bit of quick testing in ghci reveals that it still short-circuits on 0 as required and uses constant space when specialized to lists.

A: You might be looking for foldM. Instantiate it with m = Either b and you get short circuiting behavior (or Maybe, depends if you have many possible early exit values, or one known in advance).
foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b

I recall discussions whether there should be foldM', but IIRC GHC does the right thing most of the time.
import Control.Monad
import Data.Maybe

myProduct :: (Foldable t, Eq n, Num n) => t n -> n
myProduct = fromMaybe 0 . foldM go 1
  where go acc x = if x == 0 then Nothing else Just $! acc * x


text:
Q: Why Scheme requires apply in Y-combinator implementation, but Racket doesn't? Here is the Y-combinator in Racket:
#lang lazy

(define Y (λ(f)((λ(x)(f (x x)))(λ(x)(f (x x))))))

(define Fact
  (Y (λ(fact) (λ(n) (if (zero? n) 1 (* n (fact (- n 1))))))))
(define Fib
  (Y (λ(fib) (λ(n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2))))))))

Here is the Y-combinator in Scheme:
(define Y
  (lambda (f)
    ((lambda (x) (x x))
     (lambda (g)
       (f (lambda args (apply (g g) args)))))))

(define fac
  (Y
    (lambda (f)
      (lambda (x)
        (if (< x 2)
            1
            (* x (f (- x 1))))))))

(define fib
  (Y
    (lambda (f)
      (lambda (x)
        (if (< x 2)
            x
            (+ (f (- x 1)) (f (- x 2))))))))

(display (fac 6))
(newline)

(display (fib 6))
(newline)

My question is: Why does Scheme require the apply function but Racket does not?

A: Racket is very close to plain Scheme for most purposes, and for this example, they're the same.  But the real difference between the two versions is the need for a delaying wrapper which is needed in a strict language (Scheme and Racket), but not in a lazy one (Lazy Racket, a different language).
That wrapper is put around the (x x) or (g g) -- what we know about this thing is that evaluating it will get you into an infinite loop, and we also know that it's going to be the resulting (recursive) function.  Because it's a function, we can delay its evaluation with a lambda: instead of (x x) use (lambda (a) ((x x) a)).  This works fine, but it has another assumption -- that the wrapped function takes a single argument.  We could just as well wrap it with a function of two arguments: (lambda (a b) ((x x) a b)) but that won't work in other cases too.  The solution is to use a rest argument (args) and use apply, therefore making the wrapper accept any number of arguments and pass them along to the recursive function.  Strictly speaking, it's not required always, it's "only" required if you want to be able to produce recursive functions of any arity.
On the other hand, you have the Lazy Racket code, which is, as I said above, a different language -- one with call-by-need semantics.  Since this language is lazy, there is no need to wrap the infinitely-looping (x x) expression, it's used as-is.  And since no wrapper is required, there is no need to deal with the number of arguments, therefore no need for apply.  In fact, the lazy version doesn't even need the assumption that you're generating a function value -- it can generate any value.  For example, this:
(Y (lambda (ones) (cons 1 ones)))

works fine and returns an infinite list of 1s.  To see this, try
(!! (take 20 (Y (lambda (ones) (cons 1 ones)))))

(Note that the !! is needed to "force" the resulting value recursively, since Lazy Racket doesn't evaluate recursively by default.  Also, note the use of take -- without it, Racket will try to create that infinite list, which will not get anywhere.)

A: Scheme does not require apply function. you use apply to accept more than one argument.
in the factorial case, here is my implementation which does not require apply
;;2013/11/29

(define (Fact-maker f)
  (lambda (n)
    (cond ((= n 0) 1)
          (else (* n (f (- n 1)))))))

(define (fib-maker f)
  (lambda (n)
    (cond ((or (= n 0) (= n 1)) 1)
          (else
            (+ (f (- n 1))
               (f (- n 2)))))))
(define (Y F)
  ((lambda (procedure)
     (F (lambda (x) ((procedure procedure) x))))
   (lambda (procedure)
     (F (lambda (x) ((procedure procedure) x))))))


text:
Q: Cluster term added in clogit model summary when interaction term included in the model? I am running competing conditional logistic regression models using clogit in the survival package. If I run a base model with no interaction terms [case ~ temp + soilMoisture + CanopyCover + strata(strata) + cluster(ID)] the model summary is completely normal (the model runs, no errors, and summary(model) provides a normal model summary). However, if I introduce an interaction term into the model [case ~ temp + soilMoisture:warm + CanopyCover:warm + strata(strata) + cluster(ID)], the cluster term appears in the model summary with NAs for the coef, exp(coef), z, and Pr(>|z|) and 0 for the se and robust se. This model also fits just fine, no errors, or warnings. Consequently, however, you cannot calculate the QIC for these models because of the NAs and 0s in the model summary. This is new (I have older clogit models with interaction terms that I compared using QIC) so I am not sure what is up! Some example code is below.
I really just want to know why the cluster term is included in the model summary and if I can ignore this or not when calculating QIC.
dat <- data.frame(ID = rep(c("m1","m1","m1","m1","m2","m2","m2","m2","m3","m3","m3","m3","m4","m4","m4","m4","m5","m5","m5","m5"), times = 2))

dat$case <- rep(c(0,0,0,1), times = 10)

dat$temp <- runif(40, 5, 25)

dat$soil <- c("wet","dry","dry","wet","dry","dry","dry","wet","wet","dry","dry","dry","dry","dry","wet","wet","dry","dry","dry","dry","wet","wet","dry","dry","dry","dry","dry","wet","wet","wet","dry","dry","dry","dry","dry","dry","dry","wet","dry","wet")

dat$canopy <- c(75, 50, 100,    50, 50, 100,    75, 50, 100,    50, 0,  25, 75, 100,    0,  25, 0,  75, 50, 100,    0,  25, 0,  75, 50, 100,    0,  25, 75, 100,    0,  50, 100,    50, 50, 0,75,   50, 100,    0)

dat$warm <- c("cool","cool","cool","cool","warm","warm","warm","warm","cool","cool","cool","cool",  "warm","warm","warm","warm","cool","cool","cool","cool","cool","cool","cool","cool",    "warm","warm","warm","warm","cool","cool","cool","cool",    "warm","warm","warm","warm","cool","cool","warm","warm")

dat$strata <- rep(c(1,2,3,4,5,6,7,8,9,10), each = 4)`

mod <- clogit(case ~ temp + soil + canopy + strata(strata) + cluster(ID), data = dat, method = "efron")

summary(mod)

mod1 <- clogit(case ~ temp + soil + canopy:warm + strata(strata) + cluster(ID), data = dat, method = "efron")

summary(mod1)

There isn't a singularity issue here and I've gone back to old models that I've run and compared using QIC and the same issue is cropping up now (cluster terms in model summary with an interaction term in the model), so I assume something has been updated in the model.


text:
Q: Convert categorical rows to column header with string values (no aggregation) I would like to transform my categorical rows to columns, without any aggregation. I have tried it with pivot but I get NANs.
This is the data frame:
data = pd.DataFrame({'Art':['blue', 'red', 'blue', 'red', 'blue', 'red', 'blue', 'red'],

'Description':['Some text 1', 'Some text 2', 'Some text 3', 'Some text 4', 'Some text 5', 'Some text 6', 'Some text 7', 'Some text 8']})

When I try to pivot:
data.pivot(columns='Art')
I get:

And I have solved the NAN problem like this:
data.pivot(columns='Art').apply(lambda x: pd.Series(x.dropna().values))
This is the desired outcome:

However, I would like to know if there is a smarter way to simply get my classes as column headers.
Thank you!

A: your solution already seems pretty clear and concise.. with one line you have the result:
data.pivot(columns='Art').apply(lambda x: pd.Series(x.dropna().values))


text:
Q: Upsert a post in mongodb with c# save without removing old values that are non existing in the new item I am trying to upsert an existing document in mongoDB with the save method in c#.
This works well if the new item includes all the attributes of the old item. But if the new item does not contain all the old attributes, the attributes not included in the new item will be erased from the old item. Is there some way to keep the old values?
The behaviour I want is this:
If olditem contains attribute and new does not - keep old value
If olditem contains attribute and newitem  also - keep new value
If olditem does not contain attribute but newitem does - keep new value.
Is there any way I can achieve this?

A: I solved this in c# using omu.valueinjecter
protected override bool Match(ConventionInfo c)
        {
            bool retval = (
              c.SourceProp.Name == c.TargetProp.Name)
              && (c.SourceProp.Value != null
              && c.TargetProp.Value == null);
            return retval;
        }


text:
Q: Goutte crawl returns empty node I am using Goutte to crawl a set of URLS that contain href and price to extract data for my application. It works great, but some URLs give me this error:
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'The current node list is empty.'

And the following returns zero even if the element exist on the page:
$crawler->filter('.bp-2-show h3 a')->count()

Here is the code:
$crawler->filter("#serp-list-new ul li")->each(function (Crawler $node, $i){
                $u = $node->filter('.bp-2-show h3 a')->attr('href');
                $p = $node->filter('.bp-2-show .money')->text();
            });

I cannot make this work. It happens to some URLs.
Using Laravel 5.3
Package: dweidner/laravel-goutte


text:
Q: How can I spawn objects in a given volume/area 3d I was given a task by my teacher to make a script to spawn object RANDOMLY in a given AREA 3D either in a rectangle or in a sphere, I know how to do that  but have no idea how to make it choose random place in the area.
Thanks.

A: Measure the range (x-axis, y-axis, z-axis) in Unity, and then use time to control how often it is generated. These are randomly generated codes, don't forget to drag the prefab to the cube
public GameObject cube;//Define a cube to store the prefab to be randomly generated
private float t1, t2;// Control how often to generate by time

void Start()
{
    t1 = 0;//time when the game starts
}

void Update()
{
    t2 = Time.fixedTime;//The time when the game progresses to a certain position
    if (t2 - t1 >= 2)
    {
        x = Random.Range(-50,50);//Specify the range in the x-axis direction
        z = Random.Range(-50,50);//Specify the range in the z-axis direction
        //Specify the scope according to the actual situation of your own scene
        Instantiate(cube, new Vector3(x, 0.5f, z), Quaternion.identity);// Randomly generate objects (prefab, generated position, orientation).
        t1 = t2;//Every time it is generated, let t1=t2

    }
}


text:
Q: How to validate form on ajax submit I am able to validate form by using data-validation attribute that is working properly without ajax form submission.
Now I am trying to validate my registration form using ajax submit I an trying following code but this is not working.
I am using Jquery form validation
       $(document).ready(function () {
        $(document).on("click", '#submitbtn', function (f) {
         f.preventDefault();
          var formData = $("#register").serialize();
       $.validate({
        form : '#registration-form',
         onError : function($form) {
          alert('Validation of form '+$form.attr('id')+' failed!');
        },
        onSuccess : function($form) {
          alert('The form '+$form.attr('id')+' is valid!');
          return false; // Will stop the submission of the form
 $.post('register', formData, function (data) {
             if (data.st === 1) {
                $('.msg').html(data.msg);
             }
            else {
              $('.msg').html(data.msg);
            }
          }).fail(function (response) {
                 $('.msg').html("Error");
            });
        }

      });

   });
 });
     });

How to achive this?


text:
Q: Creating new Scala project using SBT? I can create a sbt project like so:
$ mkdir project1
$ cd project1
$ sbt
Loading /usr/share/sbt/bin/sbt-launch-lib.bash

> set name := "project1"
[info] Defining *:name
...

> set scalaVersion :="2.10.2"
[info] Defining *:scalaVersion
...

> set version :="1.0"
[info] Defining *:version
...

> session save
[info] Reapplying settings...

> exit

This creates build.sbt file for the project.
$ cat build.sbt
name := "project1"

scalaVersion :="2.10.2"

version :="1.0"

Now is there any command-line for doing the same? Something like:
sbt new_project "name" version scala_version

EDIT1
I figured out another way i.e. create project folder:
$ mkdir project1
$ cd project1/

Update project details:
$ sbt 'set name := "project1"' 'set scalaVersion :="2.10.2"' 'set version :="1.0"' 'session save'
Loading /usr/share/sbt/bin/sbt-launch-lib.bash
[info] Set current project to project1 (in build file:/tmp/scala/project1/)
[info] Defining *:name
[info] The new value will be used by *:description, *:normalizedName and 6 others.
[info]  Run `last` for details.
[info] Reapplying settings...
[info] Set current project to project1 (in build file:/tmp/scala/project1/)
[info] Defining *:scalaVersion
[info] The new value will be used by *:allDependencies, *:ivyScala and 10 others.
[info]  Run `last` for details.
[info] Reapplying settings...
[info] Set current project to project1 (in build file:/tmp/scala/project1/)
[info] Defining *:version
[info] The new value will be used by *:isSnapshot, *:projectId and 3 others.
[info]  Run `last` for details.
[info] Reapplying settings...
[info] Set current project to project1 (in build file:/tmp/scala/project1/)
[info] Reapplying settings...
[info] Set current project to project1 (in build file:/tmp/scala/project1/)

We have project generated and settings saved:
$ ls
build.sbt  project
$ cat build.sbt
name := "project1"

scalaVersion :="2.10.2"

version :="1.0"

I hope SBT to natively provide functionality like in Maven: mvn archetype:generate.

A: There is a np plugin for SBT that does something you are looking for. Usage:
$ sbt
$ np name:my-new-project org:org.myproject version:0.1.0-SNAPSHOT

A: you may want to check out my project skeleton
It can simplify the first steps when you need to get up and running quickly.

A: From sbt 0.13.13 on there's a built in command new:
sbt new scala/scala-seed.g8


text:
Q: OpenLayers measurment path in 31700 projection I have this code who works great for distance measurment on 900913 projection with 4326  display projection (bing maps + layer WMS):
measureDistanceControl = new OpenLayers.Control.Measure(
                  OpenLayers.Handler.Path, {
                    persist: true, // 1
                    immediate: true, // 2
                    displaySystem: 'metric', // 3
                    eventListeners: {
                        'measure': measure2,
                      'measurepartial': updateDisplay // 4
                    }
                  }
                );

                function updateDisplay( event ) { // 5
                    var mesaj= event.measure + ' ' + event.units;
                    document.getElementById('output').innerHTML=mesaj;
                };

                function measure2(event)
                {
                var mesaj= event.measure + ' ' + event.units;
                    document.getElementById('output').innerHTML=mesaj;
                }

    }

    function measure()
    {
        map.addControl( measureDistanceControl );
        measureDistanceControl.activate();
        document.getElementById("cancel").style.display = "inline";
    }
    function cancel_measure()
    {
        measureDistanceControl.deactivate();
        map.removeControl( measureDistanceControl );
        document.getElementById("cancel").style.display = "none";
    }

When I insert the code to a page with a layer and 31700 projection it sends NaN error. Code:
 map = new OpenLayers.Map({
    div: "map",allOverlays: true, projection: new OpenLayers.Projection("EPSG:31700"),
   allOverlays: true,maxResolution: 0.4651995555350368, maxExtent: bounds,
    layers: [

        data=new OpenLayers.Layer.WMS("data","http://127.0.0.1:8080/geoserver/data/wms",{layers: 'morino:<?php echo $data; ?>_space',transparent: true, format: 'image/png', <?php if ($tic!="") { ?>CQL_FILTER: "id_ddd=<?php echo $eras; ?>"<?php } ?>},{isBaseLayer: true, opacity: 0.9, singleTile: true }),
        wfs

    ],
    controls: [
        new OpenLayers.Control.Navigation({
            dragPanOptions: {
                enableKinetic: true
            }
        }),
        new OpenLayers.Control.PanZoom(),
        new OpenLayers.Control.Attribution()
    ],
    //center: new OpenLayers.LonLat(26.1473586305531, 44.4431676053183).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:31700")),
    zoom: 15
});

I've searched on Google but I didn't find anything to help me. I also read OpenLayers Cookbook - but the examples are only for 4326 projection. Or maybe OpenLayers doesn't support 31700 projection (or other then 4326)?
EDIT Solution found. Add this in header
<script type="text/javascript" src="js/proj4js/proj4js-compressed.js"></script>
    <script type="text/javascript">
     Proj4js.defs["EPSG:31700"] = "+proj=sterea +lat_0=46 +lon_0=25 +k=0.99975 +x_0=500000 +y_0=500000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m +no_defs";
    </script>

Use proj4js v1 because proj4js v2 has a problem with openlayers2. I used http://svn.osgeo.org/metacrs/proj4js/trunk/lib/proj4js-compressed.js


text:
Q: How to generate domain objects with annotations using hibernate tools I use Eclipse Hibernate Tools to create domain classes starting from my database and need to add JPA annotations.
Is there a way to add annotations? Possibly with reveng.xml and Reverse Engineering? How should this be done?
Generated domain code:
public class Country implements java.io.Serializable {

    private long id;
    private String description;
    private String identifier;
    private String futureuse;
    private Set accounts = new HashSet(0);

    public Country() {
    }

    public Country(long id, String description, String identifier) {
        this.id = id;
        this.description = description;
        this.identifier = identifier;
    }
    ...

Needed code:
@Entity
@Table(name = "COUNTRY")
public class Country implements java.io.Serializable {

    @Id
    @Column(name="CNTR_ID")
    private Long id;
    @Column(name="CNTR_FUTUREUSE")
    private String futureUse;
    @Column(name="CNTR_IDENTIFIER")
    private String identifier;
    @Column(name="CNTR_DESCRIPTION")
    private String description;
    private Set accounts = new HashSet(0);

    public Country() {
    }

    public Country(long id, String description, String identifier) {
        this.id = id;
        this.description = description;
        this.identifier = identifier;
    }
        ...

A: I personally don't use hibernate tools, because I'm pretty happy with Spring Roo. However, google search brought me to this.
As mostly there is a nice tutorial from mkyong.com. If you go to "Hibernate perspective" and click "Code generation configuration" in the "Export" tab there is a checkbox for "Generate EJB3 annotations".
http://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/
This was further confirmed in previous answers.
Can Hibernate tool generate JPA POJO?


text:
Q: How can I make room for the 2018/2020+ iPad Pro's iOS "home-screen-bar" / "swipe-up-bar" in Safari/WebKit? (My initial question is to ask what the official name is for the bar on the bottom edge of iPhone X and iPad Pro (2018 and later) devices? I've googled all variations of "ipad pro task switcher bar" "ipad pro 2018 home bar" etc and I can't find any official documents on Apple's website about it - it's maddening not to know the name of the most important UI component on a device!)

But my real question is:
Does WebKit expose any way for web-pages to automatically have their margins/padding adjusted to accounts for this task-switcher-bar?
I know that WebKit has the @-webkit-viewport feature, and has <meta name="viewport" content="viewport-fit=cover" />, but I understand that's for resizing the viewport to account for the iPhone X's "notch" and doing the same other Android devices that also feature display cut-outs - I can't find any mention on Apple's Safari Developer website about how this feature can be used for the iPad Pro's white bar.
In my case, my problem is an image editor component that's used in my application (which I load into an borderless <iframe> with height: 100vh; width: 100vw;) has buttons that run along the bottom edge of the viewport which are harder to use on an iPad Pro because of the white bar. Here's a photo:

The quick-fix is to add some fixed padding to the bottom of the page to force the buttons up somewhat, but this isn't a long-term solution and won't work for other devices - and it'll mean the UI will have weird spacing on desktops and other devices.

A: In your CSS use safe-area-inset-bottom to preserve space for the bar.
Eg: margin-bottom: env(safe-area-inset-bottom)


text:
Q: Drag and drop multiple images kineticjs I am trying to drag and drop multiple images into a canvas and they can be moved into the canvas. It works for one, but when doing multiples, the last one replaces all the others.
This is the code:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Canvas - test</title>

Canvas - The Cure

            <canvas id="my-canvas" width="700" height="600">I am canvas</canvas>

Any idea where the problem is?


text:
Q: Why is this 'obviously' positive semi-definite? Here is a snapshot from a book I am studying. I learned all about positive semi-definiteness, and in fact I know that this matrix they are showing is in fact PSD.

What I do not know is how they conclude it is PSD from the last part of the equation, when they factor the matrix into a vector times its transpose.
How is it 'obvious' from here that this is PSD?
Again, I know how to show the PSDness of this matrix, but I am not clear how/why they concluded the same thing, using the vector times vector^T in the end.
Thanks.

A: In general, let $a\in\mathbb R^n$ and $A=aa^T\in\mathbb R^{n\times n}$, as in the case of your matrix.
Clearly, $A$ is symmetric, as $A^T= (aa^T)^T=(a^T)^Ta^T=aa^T=A$.
$A$ is positive definite because of the fact that $(x,Ax)\ge 0$, for every $x\in\mathbb R^n$.
Indeed
$$
(x,Ax)=x^TAx=x^Taa^Tx=(x^Ta)(a^Tx)=(x^Ta)^2\ge 0.
$$
Note that $x^Ta$ is nothing but the inner product of $x$ and $a$.

A: This follows from the observation that any matrix of the form $A = B^T B$ is automatically positive semi definite and is positive definite if $B$ has linearly independent columns(equivalently $B^T$ has linearly independent rows).
Proof: Let $x$ be any vector of the right dimension, then
$$
x^T A x= x^T B^T B x = y^T y \ge 0 ~~~\text{where $y=B x$}
$$
This shows that $A$ is semi definite. It will be definite if $y=0 \Rightarrow x=0$ which is equivalent to requiring $B$ to have linearly independent columns.

A: Another perspective on this: suppose $A$ has the form $A = uu^T$ for some vector $u$.  Then for any real vector $v$, we have
$$
Av = uu^Tv = u(u^Tv) = (u\cdot v)u
$$
Where $u\cdot v$ represents a dot-product.
So, note that $Av$ will be $0$ if $v$ is perpendicular to $u$, and $Au = (u\cdot u)u$.  This determines all eigenvalues (and eigenvectors) of $A$.  Since all eigenvectors are non-negative, we conclude $A$ is PSD.
Moreover, it's probably good to know the following:

An $n \times n$ matrix $A$ is a rank-$k$ PSD matrix if and only if it can be expressed in the form $A = BB^T$ for some $n \times k$ matrix $B$.

A: I will just throw in another perspective. For a given matrix, if all the principle minors are non-negative, then the matrix is positive semi-definite. (Note: if you want positive definiteness, then you need to check only the leading principle minors.)
For the 2-by-2 matrix, this is easy to check. Here the principle minors are $x^2$, $y^2$, and $x^2 y^2 - x^2 y^2 = 0$. Clearly, $x^2$ and $y^2$ will always be positive, while the last one is zero. Hence the matrix is positive semi-definite.


text:
Q: How can I detect non-western characters? I want to disallow certain UTF-8 input (server-side), e.g. eastern languages, where example input might be " 伊 ".
However, I do want to continue supporting other latin or "latin-like" characters, such as the welsh ŵ and ŷ, so checking against latin-1 is not possible.
What are my options? (if language specific, PHP preferred)
Thanks very much.

Reasoning: browser support for a lot of non-western characters is often missing (e.g. on a different browser I just see a box in the question above), so for things like display names sometimes it's appropriate to restrict it even if it's not appropriate for message bodies

A: Just do
preg_match('/[^\\p{Common}\\p{Latin}]/u', $string)

where $string is an UTF-8 string. This will return "1" if there are non-latin characters and will return "0" otherwise.
Example:
var_dump(preg_match('/[^\\p{Common}\\p{Latin}]/u', 'sf..ŷaás??'));  //int(0)
var_dump(preg_match('/[^\\p{Common}\\p{Latin}]/u', 'sf..ŷݤaás??')); //int(1)


text:
Q: How to create a csv file from a list of tuples in python 2.7? I have list of tuples which I am trying to figure out how to create a csv file with the Keys as column headers and value as column values.
Below is sample list of tuples:
[('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)]
[('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)]
[('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]

The expected csv file should have:
converstion_rate,  sku_id, prev_1wk_uniq_purch_cnt
1,                  100088-02, 0.0
0,                  100088-03, 6.0
5,                  100088-04, 7.0

This is the code which I wrote:
import os
import sys
import csv
import string
import random

def import_data_to_csv(dict_d):
    with open('C:/Reports/SI_Reconciliation_Reporting/2015/output/2015-04-19/test_dump.csv', 'w') as outfile:
        fp = csv.DictWriter(outfile, dict_d[0].keys())
        fp.writeheader()
        fp.writerows(dict_d)

for row in sku_weekL:
                #print row.items()
                for key, value in row.items():
                    sku_weekTemp.append((key, value))
                print sku_weekTemp

            #print sku_weekL
            #print sku_weekL
            #print dir(sku_weekL)
            import_data_to_csv(sku_weekTemp)

But running the script I get an error that the tuple object has no attribute keys.
Any ideas how to solve this?

A: The error tries to tell you that dict_d[0] is a tuple object and therefore has no method keys() (only dicts have that).
First you should have a list of the column names in your preferred order:
column_names = ['d_conversion_rate', 'sku_id', 'prev_1wk_uniq_purch_cnt']

Since the rows are already dicts with those keys, you shouldn't need to transform them.
When you have all your value_rows you can use this together with column_names to write it:
def import_data_to_csv(value_rows, column_names):
    with open('C:/Reports/SI_Reconciliation_Reporting/2015/output/2015-04-19/test_dump.csv', 'w') as outfile:
        fp = csv.DictWriter(outfile, column_names)
        fp.writeheader()
        fp.writerows(value_rows)

edit: I missed that you use DictWriter, so converting the dicts to lists is unnecessary
edit2: an example:
given val_rows like that
val_rows = [
    {'sku_id': 1, 'd_conversion_rate': 2, 'prev_1wk_uniq_purch_cnt': 3},
    {'sku_id': 4, 'd_conversion_rate': 5, 'prev_1wk_uniq_purch_cnt': 6}
]

you can use the function above with it like this
col_names = ['d_conversion_rate', 'sku_id', 'prev_1wk_uniq_purch_cnt']
import_data_to_csv(val_rows, col_names)

# or dynamically

import_data_to_csv(val_rows, val_rows[0].keys())

If your data is not formatted as list of dicts, you'll have to do a transformation. Taking your list of lists of tuples from the question above, we can transform it to a list of dicts like this
list_of_list_of_tuples = [
    [('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)],
    [('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)],
    [('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]
]

val_rows = [{tup[0]: tup[1] for tup in row} for row in list_of_list_of_tuples]

Hope this makes it clear now.
edit3:
What you wrote in the comments is missing some information, so I have to guess
for i in List:
    sku_L = list()  # I'm assuming you're appending each sku_L to another list somewhere further down
    for row in insL:  # I'm assuming insL is calculated in the outer loop or is just i
        insertD = dict()
        # here I assign all the values to the keys of the dictionary
        sku_L.append(insertD)
        pprint(sku_L)

You don't want a new list for every dictionary, so I'd pull out the list instantiation from the loop. The purpose of pprint is to use it without a loop, so you can see the whole thing.
sku_L = list()  # only one list now
for i in List:
    for row in i:  # insL is probably just i
        insertD = dict()
        # here I assign all the values to the keys of the dictionary
        sku_L.append(insertD)

pprint(sku_L)  # printing the whole thing should be a list of dicts

I'm pretty sure your data is actually only a list of records with each record having data in fixed positions. If this is the case you can simplify this a lot:
input_list = [  # this is a list of records
    [1, 0.0, 0.0, '100088-01'],
    [1, 0.0, 6.0, '100088-02']
]

sku_L = list()
for row in input_list:
    insertD = {
        'd_conversion_rate': row[0],
        'prev_2wk_visit_count': row[1],
        'prev_1wk_uniq_purch_cnt': row[2],
        'sku_id': row[3]
    }
    sku_L.append(insertD)

pprint(sku_L)

A: Here is a solution based on what I understood about your problem.
If any question fell free to ask. I personally dislike the python standard library csv and always do without it when needing to write csv file.
def asDic(listOfTuple):
    """ Convert a list of tuple [(key,value)] into a dictionary """
    return {i:j for (i,j) in listOfTuple}

def exportLine(lineMembers, outputFile, separator):
    """
    exportLine(["lineMembers"foo", "bar", "foo"], file, "separator",")
        -> file.write("foo, bar, foo\n")
    """
    lineString = ""
    for i in range(len(lineMembers)-1):
        lineString += str(lineMembers[i]) + separator
    #Append the last element without a separator, instead add a end of line
    lineString += str(lineMembers[-1]) + "\n"
    outputFile.write(lineString)

def exportCSV(data, headers, outputFile, separator = ", "):
    """
    Exports the data into the outputFile using the given headers.
    It is possible to generate any separated value file by overriding the default separator.

    data : a list of dict object. Their content will be accesed using the values of headers as keys.
    """
    #export the headers
    exportLine(headers, outputFile, separator)

    for dataset in data :
        #Build the data line
        exportData = [ dataset[header] for header in headers ]
        #and export it
        exportLine(exportData, outputFile, separator)

if __name__ == "__main__":

    row1 = [('d_conversion_rate', 1), ('prev_2wk_visit_count', 0.0), ('sku_id', '100088-01'), ('prev_1wk_uniq_purch_cnt', 0.0)]
    row2 = [('d_conversion_rate', 0), ('prev_2wk_visit_count', 6.0), ('sku_id', '100088-02'), ('prev_1wk_uniq_purch_cnt', 0.0)]
    row3 = [('d_conversion_rate', 5), ('prev_2wk_visit_count', 7.0), ('sku_id', '100088-03'), ('prev_1wk_uniq_purch_cnt', 0.0)]

    data = [row1, row2, row3]

    #get the list of headers that will be exported
    columnHeader = [i for (i,j) in data[0]]
    #transform the data to allow access them by field
    data = [asDic(row) for row in data]

    #you may add here whatever code you want in order to sort/filter/remove some headers here.
    #Removing one header will remove the column from the final export.
    columnHeader.pop(1)#commenting this will add the column prev_2wk_visit_count to the file.

    outputFile = open("./output.csv", 'w')
    exportCSV(data, columnHeader, outputFile)
    outputFile.close()


text:
Q: Netbeans stop responding sometimes My Project has a large piece of code. Totally 5000-6000 lines now and has 100+ methods and 400+ components.
Sometimes working really hard in Netbeans because CPU goes %99 even small changes in codes.
I just paste 3 methods to my project has totally 100+ lines and Netbeans stop responding now. CPU always at %99 about 10-15 minutes.
Anyways disable Netbeans automatic checking whole codes when doing changes? Or any other idea why Netbeans stop responding?
Netbeans Version: 7.4
JDK Version: 64 Bit jdk1.7.0_45
CPU: Intel Core I7 950 3.07Ghz
RAM: 12GB RaM (DDR3 1066 MHz)
OS: Win7 Ultimate 64Bit

Regards.

A: re-factor your code so that it is not a monolith.
Separate your code so that it is in multiple classes.
Have a look at this page and remember "One class should have one and only one responsibility"


text:
Q: How to convert Moment.js moment to unix timestamp I see a lot in the Moment.js documentation about getting a Moment from a Unix timestamp. However, I am trying to convert a Moment to a Unix timestamp, and I am not sure how to do that. This is how my moment looks:
const myMomentObject = moment(str_time, 'YYYY-MM-DD');
And I need to convert it to a Unix timestamp.

A: Call unix() on moment object. Reference.
moment('2020-12-12').unix()

A: Unix timestamp can be obtaineded with or without the moment library.

//Moment
const myMomentObject = moment('2021-10-16', 'YYYY-MM-DD');
console.log(myMomentObject.unix());

//Vanilla
const d = new Date('2021.10.16');
console.log(d.getTime() / 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

A: To create a Unix timestamp (seconds since the Unix Epoch) from a moment, use the following,

console.log(moment('2021-10-16').unix());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Since your date format follows the ISO_8601 format, i.e. YYYY-MM-DD you do not need to provide the input date format to the moment constructor.


text:
Q: some Jquery code works on browser, but not on WebView Android and some does
*

*I have an Android Application containing a Webview.

*Webview contains html page that uses Jquery.

First i want to tell you that jquery works to some extent, let me prove you.
I have a html title with its proper id, when the document is ready i change the color of the title by adding a css color class with jquery.

Hardcoded Title

 ------------
 $("#title").css('color', 'red');

The Problem
I also have a html5 player, i retrieve it with jquery and get the currentSrc, which contains the Url to the video.
not so important but here is the player

        <video id="sourceVideo">
            <source type="video/mp4" src="http://view.vzaar.com/5456131/video" />
        </video>

Now using some more jquery and a js called flowplayer.min.js i call a method to retrieve the player and grab its src property.
var video = $('#sourceVideo')[0];
var currentSrc = video.currentSrc;

I then proceed to apend the currentSrc to the title of my application.
$("#tituloPrueba").append(" - CurrentSrc : "+currentSrc);

When i checked in chrome, this is the result.
As you can see the append and color change work fine, as well as the variable that stores the value of currentSrc.

Emulator
If i just append text or change the color, everything seems to work fine.

But as soon as i call this line of code
  var video = $('#sourceVideo')[0];
  var currentSrc = video.currentSrc;(this one is the problem)

it seems as if jquery stops working?
Any ideas?
Note
Loading external js seems to work, i created a new js with a document ready and inside jquery code to change color of title and it worked.

A: *

*First, check android webview version.

*Second, see what properties are available for the video tag.

Alternately, try to do this:
 alert( JSON.stringify(video) );

I assume the issue you have is that currentSrc is undefined, either because the tag video is not supported, or because that attribute is not present.
Even though, I am not quite clear what you are trying to achieve.


text:
Q: unicode for arrow keys? I am trying to make a game where you can instantly have the user's input be transmitted to the computer instead of having to press enter every time. I know how to do that, but I cannot seem to find the unicode number for the arrow keys. Is there unicode for that, or am I just going to be stuck with wasd?
class _GetchUnix:
    def __init__(self):
        import tty, sys
    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
class _GetchWindows:
    def __init__(self):
        import msvcrt
    def __call__(self):
        import msvcrt
        return msvcrt.getch()
class _Getch:
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()
    def __call__(self): return self.impl()
getch = Getch()

I using getch.impl() as a trial-or-error input, as in if there's a key being pressed when the function is called, it returns that key, and moves on. If there's no key being pressed, it just moves on.
I'm using Python 2.7.10

A: Start by reading the relevant doc for msvcrt.

msvcrt.kbhit()
Return true if a keypress is waiting to be read.
msvcrt.getch()
Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.

Notice that getch blocks and requires two calls for special function keys, which include arrow keys (they initially return b'\xe0).
Then use sys.platform and write two versions of a get_arrow function.
import sys
if sys.platform == 'win32':
    import msvcrt as ms
    d = {b'H': 'up', b'K': 'lt', b'P': 'dn', b'M': 'rt'}
    def get_arrow():
        if ms.kbhit() and ms.getch() == b'\xe0':
            return d.get(ms.getch(), None)
        else:
            return None
else:  # unix
...

I experimentally determined the mapping of keys to codes with the following code. ( This will not work when run in IDLE and maybe not in other GUI frameworks, as getch conflicts with GUI handling of the keyboard.)
>>> import msvcrt as ms
>>> for i in range(8): print(ms.getch())
...
b'\xe0'
b'H'
b'\xe0'
b'K'
b'\xe0'
b'P'
b'\xe0'
b'M'

I tested the function on Windows with
while True:
    dir = get_arrow()
    if dir: print(dir)


text:
Q: Pohlig-Hellman algorithm I'm trying to use the Pohlig-Hellman algorithm to solve for $x$ where $15^x=131(\bmod 337)$.  This is what I have so far:
prime factors of p-1: $336=2^4*3*7$
$q=2: x=2^0*x_0+2^1*x_1+2^2*x_2+2^3*x_3$
$x_0$: $131^{168}=15^{168*x_0}$, $-1(\bmod 337) = (-1)^{x_0}(\bmod 337)$, $x_0=1$
$x_1:$ $131*15^{-(1)}=131*45=166(\bmod 337)$, $166^{184}=15^{168*x_1}$, $148(\bmod 337)=-1^{x_1}(\bmod 337)$
However, from there, $x_1$ has no answer.  So I know I've done something wrong, I just don't see what.  I've double and triple checked every computation, so I assume I misunderstand something about the algorithm.


text:
Q: Why is the substr treating alpha numeric column value as string Not sure why I would be getting the following warning, giving the that data being used in this row column is alpha-numeric.
[20-Jan-2023 10:13:10 America/Chicago] PHP Warning:  strpos(): Offset not contained in string in /www/zendphp74/htdocs/IP Lookup/getIPAddress on line 345

$str = strval($row[TIME_IN_IP_ADDRESS]);

$timeInIP = substr($str, 0, strpos($str, '.', strpos($str, '.')+1));

if ($timeInIP === '10.390'){
                              return 'USA';
                           }

A: You could use explode() function instead of strpos() function to break the IP address into an array then you can add checks.
Use the following code.
$ipArr = explode(".", $row[TIME_IN_IP_ADDRESS]);

$timeInIP = $ipArr[0] . "." . $ipArr[1];
if ($timeInIP === "10.390") {
  return "USA";
}


text:
Q: How to push a branch back to a private github repo I've cloned a private repo in github to my local machine. After I'm done making some changes, I want to push the branch back to github to propose a merge  (or pull request, as github calls it).
How do I do that?
I'm absolutely new to github (I normally use bzr/launchpad, and the command was bzr push lp:~<username>/<master-branch>/<name of the new child branch>. What is the equivalence of this in git?).
[Edit: I found that my wording was confusing due to my little understanding of git's terminologies, I am going to re-describe what I did]
(bar is the private repo)
$git clone git@github.com:foo/bar.git
$cd bar
$touch <some file> # ie., make some changes
$git commit ...
$ <<<<< NOW I need to push this back to github here.

A: From your comments above and your original question, you want to do a pull request on github but you've modified master locally ... that's a problem. What you wanted to do is branch first, make the changes, commit locally, and push the branch. Then you could create a pull request on github from that branch.
First what you need to do to fix that is:

git branch mytopicbranch
  git reset --hard origin/master

You now have a branch and have reset master locally to what it is in the remote repo. You can now push your branch with:

git push origin mytopicbranch

Then on github you'll be able to create a pull request for that branch.
The normal flow would be to do the following:
git clone <remote repo>
<cd to directory>
git checkout -b mybranch
<make changes>
<commit changes>
git push origin mybranch
<create pull request on github>

Edit to add: This is for the reason you asked; wanting to do a "pull request". If you just want to push master you'd simply do:

git push origin master

And your changes will be committed to master remotely.

A:
The private master repo is NOT owned by me (ie., I don't have the permission to push my repo back to the master repo). I think I can only push my local repo back, and request the owner to merge it to the master

You seem to be confusing a lot things here. First of all, a repository is a single unit. When you clone a repository, you get a complete local copy of it.
If you cloned a repository, that is not owned by yourself and to which you have no write-rights, then you will not be able to push any changes to that repository. If that is the case, you will need to fork it first to your own GitHub account. To do that, click the fork button in the repository view. This will create a copy of the repository in your own account, which you will have push rights for.
So, if you have a local clone of the repository, you can do whatever you want. Nothing affects the remote repository, neither the original one, nor your GitHub fork. You can create as many branches as you want and commit whereever you want. Note here that branches are not some construct in Git. Branches are simple pointers to commits, so creating a branch is not doing much, and will have no impact on your structure unless you actually start committing.
If you have commits you want to push to a remote repository, you can do that by using git push:
git push <remote> <local-branch>:<remote-branch>

So if you want to push your local master branch into a branch test on the remote named origin, you can do git push origin master:test. As you pushed explicitely to the remote branch test (which does not need to exist previously), you will not touch the remote's master branch. The other variations of git push are just abbreviations of the above command. For example git push <remote> <branch> which is probably the the second to most common way to push things will push your local branch <branch> to the tracking remote branch (usually the othe with the same name). So it's more or less equivalent to <branch>:<branch>. The most common way would be just git push which will figure out the remote and branch on its own based on your configuration, but to be safe, you can just specify it explicitely.
So, coming back to your use case, I assume that you want to fork someone else's repository to make a change to it and propose that change to the original author as a pull request. To do that, you should follow these steps:

*

*Fork the repository on GitHub

*Clone your own repository (i.e. the fork)

*In your now local repository do your changes

*Push the changes into your fork (any branch is fine, although using a separate one is advised for clarity)

*When browsing your fork on GitHub, click the pull request button to create one based on your pushed branch


text:
Q: In a panel data of products (per store/week), identify products that are present in all store/week panels In the data set below, store/week is a panel. I would like to show that products 4, 5, 6 are present in all the panels. Binary variable present1 indicates it.
Similarly, I would like to recognize the presence of products in the corresponding number of occurrences. Categorical variable  present2 indicates it.
clear
input expbasedem price   product store  str7 l5 week present1 present2
      1.1  5.3 1   1   Ana 1 0
      1.1  2.5 3   1   Bob 1 0 3
      1.1  1   4   1   Brian 1 1 4
      2.1  12  5   1   Brian 1 1 4
      3.1  12  6   1   Suming 1 1 4

      12  4   2   2   Ana 1 0 2
      12  3.5 3   2   Bob 1 0 3
      10  2   4   2   Brian 1 1 4
      25  13  5   2   Brian 1 1 4
      35  13  6   2   Suming 1 1 4

      35.3  5.3 7   1   Bob 2 0 1
      12.3  2.5 8  1   Brian 2 0 1
      10.3  1   4  1   Brian 2 1 4
      35.3  12  5   1   Bobby 2 1 4
      35.3  12  6   1   Becky 2 1 4

      23.4  4   2   2   Icarus 2 0 2
      12.4  3.5 3   2   Xerox 2 0 3
      10.4  2   4   2   Yulia 2 1 4
      35.4  13  5   2   Zebra 2 1 4
      35.4  13  6   2   Ninjago 2 1 4
end

I think I know how to do present2:
bysort product: generate order = _n
drop tag
bysort product: egen tag=max(order)

present1requires loops, I think, but I don't go far:
sort week store product
egen joint1 = group (week store), label

gen long id = _n
su joint1, meanonly

forval i = 1/`r(max)' {
   su id if joint1 == `i', meanonly
   local jmin = r(min)
   local jmax = r(max)

...
...
   }

A: I interpret your first question about present1 as wanting an indicator that is
1 if and only if products 4, 5, 6 are all available in a given store and week AND the product is 4, 5, 6
0 otherwise
I suggest
gen byte wanted1 = 1

foreach p in 4 5 6 {
    bysort store week : egen byte work = max(product == `p')
    replace wanted1 = wanted1 * work
    drop work
}

replace wanted1 = wanted1 * inlist(product, 4, 5, 6)

So, the recipe is

*

*Assume all present. Indicator initialised to 1.

*Change our mind if any is absent. Principles documented at https://www.stata.com/support/faqs/data-management/create-variable-recording/
(We just need to multiply by 0 once, and the indicator as a logical product is necessarily zero.)

*Change our mind in respect of other products.
Here's a version without egen that should be faster in large datasets:
gen byte wanted1 = 1

foreach p in 4 5 6 {
    bysort store week : gen byte work = product == `p'
    bysort store week (work) : replace work = work[_N]
    replace wanted1 = wanted1 * work
    drop work
}

replace wanted1 = wanted1 * inlist(product, 4, 5, 6)

Sorry, I don't understand the definition of present2. Occurrences of what precisely?
However, your present code
bysort product: generate order = _n
drop tag
bysort product: egen tag=max(order)

could be just
bysort product : replace tag = _N


text:
Q: How to detect a click and manipulate element in my case I am trying to detect a document click when user clicks anywhere in the page . I also want to prevent clicking a div to trigger the document clicks.
I have something like
//Directive for page click
angular.module('myApp').directive('documentClick', ['$rootScope',
    function($rootScope) {
        return function(scope, element, attrs) {
            element.bind('click', function(e){
                $rootScope.$broadcast('pageClick');
            })
        }
}]);

controller JS

  //within a controller
  $scope.toggleDiv = function() {
      $scope.openDiv = !$scope.OpenDiv;
   }

  $scope.$on('pageClick', function($event) {
            $scope.openDiv = false;
  })

html

                    toggle div here

I don't want to trigger $scoep.openDiv = false when I click 'childDiv'. I only want to trigger $scope.openDiv = false when I click anywhere in the page.
Is there an angular way to do this?
Thanks!

A: You could pass down the event e and check the target.id:
$rootScope.$broadcast('pageClick', e);
$scope.$on('pageClick', function($event, e) {
    if(e.target.id !== 'childDiv')
        $scope.openDiv = false;
})


text:
Q: jQuery: selectors not working over ajax downloaded page I'm trying to extract an element from an ajax downloaded page to later append it to the DOM. I'm fetching the page like this:
    $.ajax({
        url: pagePath,
        success: function (data) {
            //data is correctly shown in debugger, all the elements exist.

            var $div = $(data).find("[data-custom-attr]").first();
            //$(data) has lenght > 0, however $div has length 0!
            //$(data).find("#ajaxpage") also has lenght 0!
        },
        dataType: "html"
    });

This is the fetched page:
    <!DOCTYPE html>

Ajax downloaded page!

I've tried with a few different selectors and everyone fails. I feel like there must be a really silly mistake somewhere in the code but can't see it.
What is the problem with those selectors?

A: The reason for this is that jQuery throws away all the nonsense you've given it, and only parses the div with h2:
$("<!DOCTYPE html>

Ajax downloaded page!

</html")

is exactly the same as
$("

Ajax downloaded page!

")

(jQuery's $("...") doesn't create full documents, it'll only build DOM fragments)
Since the first element is already your div, you cannot find [data-custom-attr] in its subtree, so the result will be []. If you do a find("h2"), that'll work fine, since it's in the subtree of your div, but you can't find the div itself.

A: var $div = $('
').html(data).find("[data-custom-attr]").first();

A: Try this:
var $div = $('

').html(data).find("[data-custom-attr]").first();


text:
Q: LocalStorage json array saving -> Prevent duplicates I just coded a small snippet to play a little bit with localStorage, pretty simple, you can add items to an json array, all these items will be saved under the localStorage key "saved"
However I was not able to prevent double entries in my json array and instead it should fire an alert.
$("#add").on("click", function(e){
    var items = localStorage.getItem('saved');
    var newitem = $('#theitem').val();

    if (items != null){
        var allitems = JSON.parse(localStorage["saved"]);
        allitems.push({"myitem":newitem});
        localStorage.setItem('saved', JSON.stringify(allitems));
    }else{
        var allitems = [{"myitem":newitem}];
        localStorage.setItem('saved', JSON.stringify(allitems));
    }
});

Here is the full code: http://jsfiddle.net/Janosch/f0j71/
What part of the '#add' click handler do I need to change in order to prevent duplicates?

A: This should work:
    ...
    var allitems = JSON.parse(localStorage["saved"]);
    var repeated=allitems.filter(function(a){ return a.myitem==newitem}).length;
    if(!repeated){
        allitems.push({"myitem":newitem});
        localStorage.setItem('saved', JSON.stringify(allitems));
    }else{alert('already added')}
    ...


text:
Q: How to override defined values in Objective-C I want to override the #define iAds @"@xyz".

A: It is the same as to override #define in c. In general, you should use this construction:
#ifdef iAds
    // Already defined - undefine
    #undef iAds
#endif
#define iAds @"@xyz"

But it will work only if your header compiles after the header where original iAds macro defined.