text:
Q: How do I use pdf.js close PDF? I'm using pdf.js as an embedded PDF viewer in a web application I'm building.  I have an iframe that I use as the 'viewer' by setting (via javascript) the SRC attribute to the following:
$('#fileViewer-1').find('iframe').attr('src', 'js/pdfjs-1.4.20/web/viewer.html?file%2FMYFOLDER%2FIMAGES%2FPDFdocs%2F' + filename + '#zoom=page-width');

so I'm basically just calling this URL as the SRC of my iframe:
js/pdfjs-1.4.20/web/viewer.html?file=MYFILENAMEHERE.pdf

and now I see memory increasing with each subsequent PDF load (where I change the SRC url attribute to a new PDF document).
QUESTION:  how can I call the pdfViewClose() function / method I see on line #6432 of viewer.js?
As I understand it, without calling this, memory in the browser may not be de-allocated.
Currently I'm seeing memory increase steadily and eventually the browser (Firefox) crashes after a number of PDF changes.

A: EDIT
Here is a related answer: https://stackoverflow.com/a/16017576/6828657

Is this the pdf viewer you're using?
https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#user-content-can-i-specify-a-different-pdf-in-the-default-viewer
As it says there, can you try to use PDFViewerApplication.open(file) to open a new pdf?


text:
Q: Problem involving Markov matrices. The question is:

Cecil Sagehen is either happy or sad. If he is happy one day, then he is happy the next day three times out of four. If he is sad one day, then he is sad the next day one time out of three. During the coming year, how many days do you expect Cecil to be happy?

I construct the transition matrix corresponding to this problem,
$$M = \begin{pmatrix} \frac{3}{4} & \frac{1}{4} \\
\frac{2}{3}&  \frac{1}{3}
\end{pmatrix} $$
We have that the eigen values of $M$ are $1$ and $\frac{1}{12}$ with corresponding eigen vectors $v_1 = (1,1)$ and $v_2 = (-3,8)$. I know that we can diagnolize $M$ and then compute $M^{365}$, but is there a way to solve this problem without diagonalizing; as in, can we solve this problem just using the eigen vectors $v_1$ and $v_2$? Any help would be appreciated. Thanks!

A: I strongly suspect that you are meant to use the following approximation of the result: the final distribution of the Markov chain is the eigenvector of $M^T$ associated with the eigenvalue $1$, with non-negative entries normalized to have sum $1$. In this case, we find that eigenvector to be $(8/11,3/11)$. Correspondingly, we find that after a sufficiently long time amount of time, the probability of being happy at that moment is given by $8/11$.
Correspondingly, we should expect that out of $365$ days, Cecil should be happy on $365 \cdot 8/11 = 265.45 \approx 265$ days.

If we were to compute the exact result, then given an initial distribution $\pi = (\pi_1,\pi_2)^T$, we would need to compute
$$
\pi^T[I + M + M^2 + \cdots + M^{364}].
$$
Using your eigenvalues, we have $M = PDP^{-1}$ where
$$
P = \pmatrix{1&3\\1&-8} \implies P^{-1} = \frac 1{11} \pmatrix{8&3\\1&-1}, \quad D = \pmatrix{1&0\\0& \frac 1{12}}.
$$
We note that for $r \neq 1$, we have $1 + r + \cdots + r^{364} = \frac{1-r^{365}}{1-r}$, and for $r = 1$ this sum is equal to $365$. Putting all that together, we have
$$
\pi^T[I + M + M^2 + \cdots + M^{364}] = \\
\pi^T P [I + D + D^2 + \cdots + D^{364}]P^{-1}\pmatrix{1\\0}  = \\
\pi^T P \pmatrix{365 & 0\\0 & \frac{1 - (1/12)^{364}}{1-(1/12)}}P^{-1}\pmatrix{1\\0} \approx\\
\pi^T P \pmatrix{365 & 0\\0 & \frac{1}{1-(1/12)}}P^{-1}\pmatrix{1\\0} =\\
 \pi^T P \pmatrix{365 & 0\\0 & \frac{12}{11}}P^{-1}\pmatrix{1\\0} =\\
\frac 1{11}\pi^T\pmatrix{1&3\\1&-8} \pmatrix{365&0\\0&\frac{12}{11}}\pmatrix{8&3\\1&-1}\pmatrix{1\\0} =\\
\pi^T\left(\begin{matrix}265.75 & 99.25\\264.66 & 100.34\end{matrix}\right) \pmatrix{1\\0}
\\
265.75\,\pi_1 + 264.66\,\pi_2
$$
If we start with the initial distribution $(1/2,1/2)$ (i.e. Cecil is equally likely to be happy or unhappy on the first day), this leads to the answer $265.21 \approx 265$. So, it indeed seems that the final distribution yields a close approximation to the true answer.
Based on the coefficients of the answer given above, we can see that whatever the initial distribution, the answer will lie within the interval $[264.66, 265.75]$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unknown module(s) in QT: webkitwidgets I am new with qt5 and have installed from scratch using this tutorial here:
http://www.linuxfromscratch.org/blfs/view/svn/x/qt5.html
Qt5 is installed in /opt/qt5/qt-5.4.1.
I have also done sudo apt-get install libqt5webkit5-dev.
However, when I tried to include webkitwidgets in my .pro file, the error is returned: Unknown module(s) in QT: webkitwidgets
Here is a snippet of my .pro:
QT       += core gui

QT += widgets webkitwidgets

INCLUDEPATH += /opt/lib/eigen-eigen-10219c95fe65 \
               /opt/qt5/qt-5.4.1/lib

What am I missing here?
Thanks.


text:
Q: Error when using an inner variable of a component I am using Thermal Power Library from Modelon. There is a condenser component in the Thermal Power Library which is used for the modeling of power plants.
The default heat transfer area for the wall_2 in the condenser component is 0.8*A_heat_tot, the variable of A_heat_tot is an inner variable in the condenser component, but when I try to use this variable, there is an error showing that this variable isn't defined.
My question is that If I can use the inner variable directly. If not, how should I use it?

A: Short answer: You need to address the variable with its full path, i.e. wall_2.A_heat_tot.
A_heat_tot is define in StandardWall and can thus be referred to directly inside the class. However, when you are making changes to A_heat from outside the instance of StandardWall (i.e. outside wall_2) you must point to the origin of A_heat_tot since it is otherwise not known in the scope from which you are trying to use it.
Likewise, if you are making the modification in you simulation model (Preheater_Model_Validation2) you must use the full path, i.e. hex.wall_2.A_heat = hex.A_heat_tot
By the way, this has nothing to do with the inner qualifier in the Modelica language.


text:
Q: curl_easy_getinfo undefined symbol error I am using asterisk version 13.5.0. In utils directory, I created a new module called curl_util with source code as below:
#include "asterisk/curl_utils.h"
HttpResponse * httpResponseNew()
{
    HttpResponse * response = calloc(1, sizeof(HttpResponse));

    return response;
error:
    return NULL;
}

HttpResponse * httpRequestPost(char *url, char *post_body, size_t size)
{
    struct MemoryStruct chunk;
    CURL *curl = curl_easy_init();

    chunk.memory = malloc(1);
    chunk.size = 0;

    HttpResponse *response = httpResponseNew();
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_body);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, size);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HttpResponseMemoryWriter);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

    response->res = curl_easy_perform(curl);

    if (response->res != CURLE_OK)
    {
        response->OK = 0;
    }
    else
    {
        response->OK = 1;
        response->size = chunk.size;
        response->body = chunk.memory;
    }

    curl_easy_cleanup(curl);

    return response;

error:
    free(chunk.memory);
    if (curl) curl_easy_cleanup(curl);
    return response;
}

In chan_sip.c, I call above mentioned httpRequestPost function.
Executing make and make install are OK.
But, when starting dahdi and asterisk, I got the following error:
Error loading module chan_sip.so: undefined symbol: httpRequestPost
loader.c: module chan_sip.so could not be loaded.
Could you please give hints or advices to fix this error?
Thank you in advance.

A: Doesn't need to edit the makefile. You just need to use the ASTLDFLAGS compiler option like :
./configure
make ASTLDFLAGS="-lcurl"
make install
make samples
make config

A: I fixed the error by doing followings:
Remove libcurl4-openssl-dev
Download CURL from http://curl.haxx.se/, unzip, run commands ./configure, make, make install
Edit Makefile of asterisk, adding -lcurl for compile flags.


text:
Q: isomorphism of in space of section of a vector bundle In this notes Lecture 2 they have at page 29

One defines
$$
\mathcal{E}(M ; E):=\Gamma(E),
$$
the space of all smooth sections of $E$ endowed with the following local convex topology. To define it, we choose a cover $\mathcal{U}=\left\{U_{i}\right\}_{i \in I}$ of $M$ by opens which are domains of "total trivializations" of $E$, i.e. both of charts $\left(U_{i}, \kappa_{i}\right)$ for $M$ as well as of trivializations $\tau_{i}:\left.E\right|_{U_{i}} \rightarrow U_{i} \times \mathbb{C}^{p}$ for $E$. This data clearly induce an isomorphism of vector spaces
$$
\phi_{i}: \Gamma\left(\left.E\right|_{U_{i}}\right) \rightarrow C^{\infty}\left(\kappa_{i}\left(U_{i}\right)\right)^{p}
$$

Where $E$ is a vector bundle.
Suppose that $s$ is a section of this vector bundle. In coordinates $X$ the section is given by $$s(x)=(x^m,c^p(x))$$
Is this isomorphism $\phi$ given by $\phi(s)=c^p(x)$ ?


text:
Q: Button showing/hiding parametr LWC Hi :) I am new in programming and salesforce.
and now i have a problem with buttons. I want to one click it and show a param from js (data).
(company.date schould show just when I will click button)
Can u help me write a right method?
Place of parametr data
<lightning-datatable data={companys.data} columns={columns} key-field="Name"></lightning-datatable>

Button

<div class="slds-col">
                        <lightning-button
                        label="Search"
                        onclick={}
                        variant="brand"></lightning-button>
                     </div>

A: Your JavaScript controller needs a property to show/hide the element:
showCompanies = false

Elements can use that controller property, so they will be shown only when showCompanies is true:
<lightning-datatable if:true={showCompanies} ...

The button has a number of events it can dispatch. An event is just a message from where an event originates, such as a button click or typing on the keyboard, letting another component know that something interesting happened. In this case, we use onclick:
<lightning-button onclick={showSearchResults} ...

Which is then written in your controller class:
showSearchResults(event) {
  this.showCompanies = true;
}


text:
Q: Web api variables with numbers is not working I try to use this API: https://api.coinmarketcap.com/v1/ticker/bitcoin/ .
Everything worked well until I tried to get the 24h_volume_usd variable. Javascript is having trouble with the "24" at the beginning of the variable.
This is my first problem and the second one is that I can't display the market_cap_usd / available_supply / total_supply / max_supply / price_btc. I tried to find the reason but I have no idea. 4 of this 5 variables are really "high" numbers. Something with this?
Here is my code: http://gg.gg/8psga (jsfiddle link).

A: try this,updated a little problem
https://jsfiddle.net/xianshenglu/rj8cqLa8/5/

$('.cmc-last_updated').append(data[0].last_updated);/*change last_updated to cmc-last_updated*/


text:
Q: JQuery: Show child element that is within a hidden parent element I have a series of menus and submenus (nested uls). I want to display a ul that is nested within another parent ul, without displaying the parent. I would normally do this as:
$('#menu ul li ul').show(300);

but because the original, parent ul has display:none css, the child ul does not show.
I have tried adding:
$('#menu ul:first').addClass('nodisplay');

But this doesnt really work either.
Can anyone suggest a way to to do this?

A: I would clone it with jQuery and append it to a visible parent, then destroy it when it was no longer needed.


text:
Q: How to get RGB channel using Wand? I want to get a channel (Red, for example) from an Image using Wand in Python.
I already know how to get channel using ImageMagick itself but I want to do the same but using Wand
It seems to me that it is not implemented in Wand, or I miss something?

A:
It seems to me that it is not implemented in Wand, or I miss something?

This was implemented in Wand version 0.3.0, but not well documented.
from wand.image import Image

with Image(filename='wizard:') as img:
    with img.channel_image['red'] as red_channel:
        red_channel.save(filename='red_channel.png')

A: Found a workaround using color_matrix :
img.color_matrix([
    [1, 0, 0],
    [1, 0, 0],
    [1, 0, 0],
])


text:
Q: How to query 'sell' attribute of rails model with groupdate I have a Price model that has a buy and a sell attribute. I am trying to graph this, but I can't seem to wrap my head around the query I need.
I need the final hash to be :created_at => :SELL/BUY_ATTRIBUTE
I'm using the groupdate gem to try and get it by minute, but the following doesn't work: Price.group_by_minute(:created_at).pluck(:buy)
The only examples of group_by_X I can find appends it with a .count, never anything else.


text:
Q: Is there a topological interpretation of a module over $\Omega_{PL}(X)$? Associated to a DGCA (differential graded commutative algebra) $A$, we can associate to it the category of modules over $A$. Hence, for a space $X$ we can consider the category of modules over $\Omega_{PL}(X)$, modules over the PL de Rham complex of $X$. The starting point of rational homotopy theory is that $\Omega_{PL}(-)$ is an equivalence upon restricting to simply connected spaces and simply connected DGCA's in a homotopical sense.
I am wondering, perhaps after replacing $\Omega_{PL}(X)$ with a Sullivan model, does this category of modules have a topological interpretation? I am also interested in the d.g. lie algebra analog.

A: TLDR: there is a contravariant adjunction between the derived category of $A_{PL}(BG)$ and the naive category of rational $G$-spectra. In some cases, this is a contravariant equivalence of categories, for example when $G$ is a connected Lie group.

If I am not mistaken, the derived category of $A_{PL}(X)$ is equivalent to the homotopy category of modules over the ring spectrum $\operatorname{Map}(\Sigma^\infty X_+, H\mathbb Q)$. I think this follows from a paper of Richter and Shipley.
We may as well pose the question about modules over the singular cochain complex $C^*(X)$, a.k.a modules over $\operatorname{Map}(\Sigma^\infty X_+, H\mathbb Z)$, or even more generally, about modules over the ring spectrum $D(X)=F(\Sigma^\infty X_+, S)$ (the Spanier-Whitehead dual of $X_+$).
When $X$ is a disjoint union, all these rings or ring spectra split as products. So we may assume that $X$ is connected. In this case there is a Koszul duality between cochains on $X$ and chains on $\Omega X$. Or better still, there is a Koszul duality between the ring spectra $D(X)$ and $\Sigma^\infty \Omega X_+$. This implies that there is a contravariant adjunction between the homotopy categories of modules of these spectra. This adjunction restricts to an equivalence between certain subcategories of these module categories. For example, there is an equivalence between finitely generated free cellular modules over either one of the ring spectra, and the so-called nilpotent modules over the other one.
Without loss of generality we may assume that $X=BG$ where $G$ is a topological groups. Then modules over $\Sigma^\infty \Omega BG_+\simeq \Sigma^\infty G_+$ are the same as spectra with an action of $G$. So there is a contravariant adjunction between the category of modules over $D(BG)$ and the naive category of $G$-spectra. Similarly, there is a Koszul duality between the ring spectra $D_{\mathbb Q}(BG)=\operatorname{Map}(\Sigma^\infty BG_+, H\mathbb Q)$ and $H\mathbb Q \wedge G_+$. If I am not mistaken, the homotopy category of modules over $\Omega_{PL}(X)$ is equivalent to modules over $D_{\mathbb Q}(BG)$. So we obtain a contravariant adjunction between this category and the naive category rational $G$-spectra.
This adjunction is not an equivalence in general, but sometimes it is. For example, I think the paper
"An algebraic model for free rational $G$-spectra for connected compact Lie groups", by Greenlees and Shipley,
tells you that it is an equivalence when $G$ is a connected compact Lie group. They also give an explicit algebraic model for the category of modules in this case.
I have the feeling that when $G$ is connected and $BG$ is finite, the adjunction is also close to being an equivalence in some sense that can be made precise. Maybe the (naive) category of rational $G$-spectra is equivalent in this case to the category of pro-nilpotent modules over $A_{PL}(BG)$, but I am not 100% sure. There is a paper about derived Koszul duality by Blumberg and Mandell that says something about it.
On the other hand, if $G$ is a finite group, then $D_{\mathbb Q}(BG)\simeq H\mathbb Q$, but the category of rational $G$-spectra of course depends on $G$.
(Incidentally the paper
Complexes of injective $kG$-modules by Benson and Krause contains some interesting information about the derived category of $C^*(BG; \mathbb F_p)$ for finite $G$.)


text:
Q: Ruby undefined method for variable I have a bit of code that goes:
def strip_str(str)
  if str.nil?
    return ""
  end
  return I18n.transliterate(UnicodeUtils.downcase(str.force_encoding("utf-8"))).gsub(/\s+/, " ")
end

city_info = []

transactions.each do |trx|
  city = strip_str(trx["city"])
  event_city = strip_str(trx["event_city"])

  cities_dist = Levenshtein.distance city event_city
  cities_normal_dist = Levenshtein.normalized_distance city event_city
  cities_equal = (city == event_city)

  city_info << [cities_dist, cities_normal_dist, cities_equal]
end

This runs normally for a bunch of elements in transactions but eventually at one point where city = 'manaus' and event_city = 'manaus', I get:
NoMethodError: undefined method `city' for main:Object

on the cities_equal = (city == event_city) line. That seems to make no sense to me, as I'm just comparing two strings and none of them is being called as a method. What's wrong with this bit of code?


text:
Q: JSON data not filling up in DataTable I am having a JSON file with the following values and I am trying to fill the DataTable with the values of the JSON file. I have tried using the following AJAX call method with "data" and using the "columns" and using several trials and errors using both the "data" and the "columns" but my DataTable is still empty. Is there a reason what I am doing wrong as I am able to use this in another JSON file with the input shown in the most bottom but that JSON file is in the form of array. Thus, I am unsure what to do to fill up the DataTable with a JSON file that isn't an array.
AJAX Call
$.ajax({
  'url': 'http://localhost:8080/Retail-war/webresources/products/getProduct/' + productId,
  'method': 'GET',
  'contentType': 'application/json; charset=utf-8',
  'headers': {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}).done( function(data) {
  $('#product-inventory-level').DataTable( {
    "data": data,
    "columns": [
      { "data": "productId"},
      { "data": "originalPrice"},
      { "data": "productStatus"}
    ],
  })
  console.log("THIS IS THE DATA")
  console.log(data.productId)
  console.log(data.invSelectionCount)
  console.log(data.productId)
})

JSON File
{
    "productId": 1,
    "originalPrice": 59.9,
    "currentPrice": null,
    "productStatus": "LISTED",
    "discount": null,
    "productVol": null,
    "invSelectionCount": {
        "red=small": 100,
        "red=medium": 200
    },
}

Works For JSON File
[
    {
        "productId": 1,
        "originalPrice": 59.9,
        "currentPrice": 0.0,
        "productStatus": "LISTED",
        "discount": 0.0,
    },
    {
        "productId": 2,
        "originalPrice": 9.99,
        "currentPrice": 0.0,
        "productStatus": "LISTED",
        "discount": 0.0,
    },
    {
        "productId": 3,
        "originalPrice": 69.9,
        "currentPrice": 0.0,
        "productStatus": "LISTED",
        "discount": 0.0,
    },
]

A: I think DataTable should only accept list type data. You can try :
  $('#product-inventory-level').DataTable( {
    "data": [data],
    "columns": [
      { "data": "productId"},
      { "data": "originalPrice"},
      { "data": "productStatus"}
    ],
  })

It will just wrap you object into a list.

A: Try the below Snippet. if you ajax result is coming as the above format, it will work fine

var data=[
    {
        "productId": 1,
        "originalPrice": 59.9,
        "currentPrice": 0.0,
        "productStatus": "LISTED",
        "discount": 0.0,
    },
    {
        "productId": 2,
        "originalPrice": 9.99,
        "currentPrice": 0.0,
        "productStatus": "LISTED",
        "discount": 0.0,
    },
    {
        "productId": 3,
        "originalPrice": 69.9,
        "currentPrice": 0.0,
        "productStatus": "LISTED",
        "discount": 0.0,
    },
];

$('#product-inventory-level').DataTable( {
    "data": data,
    "columns": [
      { "data": "productId"},
      { "data": "originalPrice"},
      { "data": "productStatus"}
    ],
  })

<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>

                productId
                originalPrice
                productStatus


text:
Q: Unable to print spreadsheet by using ExcelLibrary i am using this Create Excel (.XLS and .XLSX) file from C#
What steps will reproduce the problem?
1. Create a spreadsheet using excellibrary
2. Open the spreadsheet in Excel
3. Try to print the spreadsheet
What is the expected output? What do you see instead?
Should print, instead get message 'Excel could not find anything to print'
If you copy the data to a new spreadsheet then it prints fine.
is there any solution?

A: after some searching i have found this link
http://code.google.com/p/excellibrary/issues/detail?id=31&colspec=ID%20Type%20Status%20Priority%20ReportedBy%20Owner%20Summary%20Opened
by this i have solve this

A: Here is the recompiled dll with the print fix.
https://excellibrary.googlecode.com/issues/attachment?aid=310010000&name=ExcelLibrary.dll&token=ABZ6GAfhAt8vF9GuExA0wgjRJnejNwrlVg%3A1412108599039


text:
Q: Using QLocalServer over QtService : how to set security attributes to named pipe created by QLocalServer? I am trying to use QLocalServer in service application on win7.
QLocalServer's windows implementation uses named pipes, and since winVista try to access it from GUI causes error. There was even QT bug about it, but trolls closed it without any fixing.
So my question is:
Is there a way to change security attributes of already created in service named pipe to make it accessible from gui applications?
Or the only way is copypaste QT QLocalServer object and add security attributes to its code which creates pipe?
I grant access to pipes handles with
template <class To, class From> inline To* d_ptr(From* ptr)
{
    return (To*)QObjectPrivate::get(ptr);
}
...
QLocalServerPrivate* p=d_ptr<QLocalServerPrivate>(this);

But what to do with them now?

A: if believe to this pipe security attributes cannot be changed under LocalAdmin user...
so I edited QLocalServer, which i did not wanted to do :(

A: I faced with the same problem few years ago. Maybe it already fixed in latest Qt version. I resolved the problem with next workaround:
bool fixLocalServerPermissions(QLocalServer *server)
{
    QString pipeName = server->fullServerName();

    HANDLE h = CreateNamedPipeA(pipeName.toStdString().c_str(), PIPE_ACCESS_DUPLEX | WRITE_DAC,
            PIPE_TYPE_MESSAGE, PIPE_UNLIMITED_INSTANCES, 1024*16, 1024*16, 0, NULL);

    if (h == INVALID_HANDLE_VALUE)
        return false;

    bool status = SetSecurityInfo(h, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL) == ERROR_SUCCESS;
    CloseHandle(h);

    return status;
}


text:
Q: Graphics processing fast on HDMI, slow on USB + Display port I am running Ubuntu 22.04 on a Dell Optiplex 7050 micro, with a standard Dell monitor and also a HP EliteDisplay S140u portable monitor. My Optiplex has HDMI ports, DisplayPorts and   USB 3.0 ports. Forgive me if this turns out to be a hardware question, and not an Ubuntu one.
The external monitor uses a USB highspeed connection. The other monitor only has VGA and Display Port, no HDMI. The portable uses a DisplayLink driver and the other monitor doesn't use a proprietary driver. The graphics card is just an intel integrated one.
At first, I was using the standard monitor using an HDMI to VGA adapter. I noticed that the external monitor has a hard time rendering complex graphics, like if I'm running a photo editing program, or I'm browsing a site with a lot of HD photos. The scrolling becomes choppy and rendering takes longer. But if I dragged these windows over to the other monitor, they loaded quickly.
Then, I replaced the HDMI/VGA connection with a Display Port connection. The quality of the display is a lot better now, on the standard monitor, but now this monitor also has problems rendering large images, the same as the portable one.
I am running Wayland, but I switched over to Xorg and this didn't fix the problem. I need to be able to run Wayland, anyway, because some Wine programs only display properly on Wayland. Anyway, I'm wondering if there's anything I can do to improve the graphics performance on one (or both) of these monitors.
I assumed this


text:
Q: HTML to PostScript Conversion I'm searching for a free component or library that could convert HTML to PostScript ( .ps file format ). I'm using .Net framework 1.1. Any one have experience with situation like this ?

A: You could use the HTML viewer control and print the html to a PostScript printer that outputs to a file. Not very elegant, but it would work.
I think there are unix tools that does this, so you might find a windows port for one of them and use it via Process.Start.


text:
Q: How to launch my web application on startup? OpenBSD I just migrated a web application from NodeJS to Go, and I am having troubles getting it to run on startup. Previously using my Node app, I would use pm2 to handle starting the app. However I cannot find a good way to do this with Go.
I have looked into making my own service with rc.d but I can't really find anything that helpful. Is there an easy way to do this? I can compile the source code to binary if need be.
At the moment I have it just running in a TTY, but I would really like it to be a daemon.
Edit: Just to clarify, I am using NGiNX to reverse proxy the Go app.

A: If you don't want to use the rc.d infrastructure (you should), you can just add whatever is appropriate to /etc/rc.local BUT remember that everything there is run as root, so you'll probably want to use su to run your application as another user (and while you're at it, check if you want to run it chrooted somewhere).
If you want to go the rc.d way, you might want to start by skimming throug the man pages for rc.d and rc.subr, and the template at /usr/ports/infrastructure/templates/rc.template might also be a big help.  Yet another option is to find an already ported Go web application, install it and see how it is run.  For instance gitea is installed as a compiled binary and then has a very simple /etc/rc.d/gitea script:
#!/bin/ksh
#
# $OpenBSD: gitea.rc,v 1.6 2021/01/17 21:07:41 pvk Exp $

daemon="/usr/local/sbin/gitea"
daemon_user="_gitea"

. /etc/rc.d/rc.subr

rc_bg=YES
rc_reload=NO

rc_cmd $1

A: I'm not really an OpenBSD guy, but don't you just need to make sure that httpd starts at boot?


text:
Q: I'm trying to implement quickselect by partitioning the array, but it constantly produces wrong answers. Where am I committing a mistake? Here's the java code
The select function returns the kth smallest element present in the array.
Even though the code seems alright to me, it does not produce the correct results.
public static Comparable select(Comparable[] a, int k, int lo, int hi) {
        if(hi <= lo) return a[--k];

        int j = partition(a, lo, hi);
        if(j == k-1) return a[j];
        else if(j > k-1) return select(a, k, lo, j-1);
        else if(j < k-1) return select(a, k, j+1, hi);

        return a[--k];
    }

    private static int partition(Comparable[] a, int lo, int hi) {
        int i = lo, j = hi;
        Comparable pivot = a[lo + (hi - lo)/2]; // the pivot element;

        while(i < j) {
            while(less(a[++i], pivot)) if(i == hi) break;
            while(less(pivot, a[--j])) if(j == lo) break;

            exchange(a, i, j); // exchanges elements at indices i and j
        }
        exchange(a, lo, j); // exchanges elements at indices lo and j

        return j;
    }

A: The code is using Hoare partition scheme, which means the pivot and elements equal to the pivot can end up anywhere. This means the kth smallest element won't be known until a base case is reached, and this line should be deleted:
        if(j == k-1) return a[j];


text:
Q: Why do Lambda expressions in Java 8 implement a functional interface, instead of a delegate as in C#? Many developers who work on projects in Java and on other projects in C# are used to the C# delegate syntax.
Also, the C# delegate syntax is much shorter than the Java functional interface syntax:
Example in C#:
public delegate void ProcessBook(Book book);

Same example in Java:
public interface ProcessBook {
    void processBook(Book book);
}

As C# has in the past adopted much of the Java syntax, why did we not adopt this C# delegate syntax in Java 8?

A: probably because of backward compatibility. when you use interface, you can use it with all the existing api (and java's strength is the plenty of libraries). for example you can use lambda in every place instead of Runnable, Comparable etc. But when you create some new concept / new keyword, all existing libraries can't benefit from it - they have to be rewritten to work with this new construct


text:
Q: Fathom. Is it a commonly used verb? I have come across the word FATHOM. Is it a commonly used verb in the AmE? Meaning to think, understand smth. Thank you!

A: According to Merriam Webster, fathom is in the top 30% of popular English words. This probably includes both major meanings of the word:

Definition of fathom
  1 : a unit of length equal to six feet (1.83 meters) used especially for measuring the depth of water —sometimes used in the singular when qualified by a number five fathom deep
  2 : comprehension
  the themes display a newer fathom than the technical modernism of the composer's earlier works —Newsweek
[merriam webster]

Anecdotally, as a non-native speaker I am quite familiar with the word and guess that it is fairly common in its second definition of "comprehension".
Edit: The most common usage, as noted by Henry, is probably as verb form:

2 : to penetrate and come to understand. couldn't fathom the problem

There's also the related adjective fathomable.


text:
Q: Adding data to a socket.io socket object I am trying to add some custom information to my socket object on connect, so that when I disconnect the socket, I can read that custom information.
IE:
// (Client)
socket.on('connect', function(data){
  socket.customInfo = 'customdata';
});

// (server)
socket.on('disconnect', function () {
  console.log(socket.customInfo);
});

A: Since it is JavaScript you can freely add attributes to any object (just as you did). However socket.io does give you a built-in way to do that (so you won't have to worry about naming conflicts):
socket.set('nickname', name, function () {
  socket.emit('ready');
});

socket.get('nickname', function (err, name) {
  console.log('Chat message by ', name);
});

Note that this is only on one side (either client or server). Obviously you can't share data between client and server without communication (that's what your example suggests).
The socket in your browser and the socket in the server won't share the same properties if you set them.
Basically you have set the data only at the client side (which is in your browsers memory NOT on the server).

A: For anyone still looking for an answer, there are a couple of things you can do to share data from the client to the server without actually sending a message.

*

*Add a custom property to the auth property in the client socketIo options. This will be available to the server event handlers in socket.handshake.auth.xxxx.

*Add a custom header to the transportOptions.polling.extraHeaders property in the client socketIo options. This will ONLY be presented when the socket.io client is connected via polling and not when "upgraded" to websockets (as you can't have custom headers then).

*Add a custom query property to the client socketIo options. I don't recommend this since it potentially exposes the data to intermediate proxies.


text:
Q: Things to take into account when making a website? What security considerations should I/do I have to take into account if I decide to make a professional website(HTML,CSS,JavaScript,PHP,etc.). For example, when having a database, one should think about hackers who want to hack the website by SQL-injection. But there are many other examples. What I would like to know is a list of things(security) a webmaster must consider/take into account. Also maybe some things that are recommended, but not a must. A short explanation about each topic is much appreciated, but you don't have to. Thanks in advance.
btw. I'm not sure about the tags. Please add/modify if you know better.

A: The best resource for securing web applications is the OWASP Top 10: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
I suggest you read through each of these top 10 security risks and ensure you understand three things:

*

*What the risk is

*How it is exploited

*How to protect against it in you language of choice


text:
Q: Can I hide a Category (and its subcategories) from the sidebar? I put the widget category on the primary sidebar, from the dashboard. Than, on code, I use :
<?php get_sidebar('left'); ?>

and it create the code for the categories. Now, I'd like to hide the category with tag_ID=6, and all of its subcategories.
How can I do it?
Tried this tutorial, but seems that I don't have the $cat_args = "orderby=name&show_count={$c}&hierarchical={$h}"; line? I'm on last version of WordPress, 3.4.2

A: The tutorial seems outdated, so I wouldn't rely on that. It is not necessary to hack around in the WordPress-source - create a simple Plugin which hooks into the right filters.
In your case those filters are widget_categories_dropdown_args (when you select "Display as dropdown" in the Widget-options) and widget_categories_args (if the Widgets displays the list as normal text with links).
With that knowledge you can now code the actual plugin (I've called it Myplugin, I think you should rename it) - just put that PHP code into the file wp-content/plugins/myplugin.php:
<?php
/**
 * @package Myplugin
 * @version 1.0
 */
/*
Plugin Name: Myplugin
Plugin URI: http://example.com
Description:
Author: You
Version: 1.0
Author URI: http://example.com
*/

// Create a list with the ID's of all children for
// the given category-id
function myplugin_recursive_filter($catid) {
    $result = array($catid);

    $cats = get_categories(array(
        'child_of' => $catid,
    ));

    foreach($cats as $category) {
        $result[] = $category->cat_ID;
    }

    return implode(",", $result);
}

// Actual filter function. Just set the "exclude"
// entry to a comma separated list of category ID's
// to hide.
function myplugin_filter_categories_args($args) {
    // 6 is the "tag_ID"
    $args['exclude'] = myplugin_recursive_filter(6);

    // or hard code the list like that:
    //$args['exclude'] = '6,10,11,12';
    // but you'd have to include the ID's of the
    // children, because "eclude" is not recursive.
    return $args;
}

// Register the filter to the relevant tags
add_filter('widget_categories_dropdown_args',
    'myplugin_filter_categories_args', 10, 1);

add_filter('widget_categories_args',
    'myplugin_filter_categories_args', 10, 1);

The function myplugin_recursive_filter is necessary, because the exclude-entry is not recursive (except if you check "Show hierarchy" in the widget options). If your categories don't change that much you could replace function call with a hard-coded list of ID's (with the children) for better performance.


text:
Q: Specify multiple notes of a table by xtable I want to create a table which may contain multiple notes like :

which I found here.
This works fine in a pure LaTeX context, yet I'm using knitr to convert my Rnw files (under R) to pdf, because there are too many tables to do by hand in LaTeX.
\documentclass[11]{article}
\author{''}
\usepackage{float}
\usepackage{array}
\usepackage{fullpage}
\usepackage{pdflscape}
\usepackage{cite}
\usepackage{booktabs}
\usepackage[top = 0.5in, bottom = 0.5in, left = 0.5in, right = 0.5in]{geometry}
\begin{document}

print(xtable(x, digits = c(0, 0, 0, 3,3, 0, 3,3), # first zero "represents" row numbers which we skip later
                 align = "llcccccc",  # align and put a vertical line (first "l" again represents column of row numbers)
                 caption = strCaption, label = "yearlyprivatization"),
          size = "normalsize", #Change size; useful for bigger tables "normalsize" "footnotesize"
          include.rownames = FALSE, #Don't print rownames
          include.colnames = TRUE, #We create them ourselves
          caption.placement = "top", #"top", NULL
          hline.after=NULL, #We don't need hline; we use booktabs
          floating=TRUE, # whether \begin{Table} should be created (TRUE) or not (FALSE)
          sanitize.text.function = force, # Important to treat content of first column as latex function
          add.to.row = list(pos = list(-1,0,nrow(x)-1,
                                       nrow(x)),
                            command = c(paste("\\hline \n",  # NEW row
                                              "\\multicolumn{1}{c}{} & \\multicolumn{3}{c}{\\textbf{Consecutive Sample}} &
                                              \\multicolumn{3}{c}{\\textbf{Entire Sample}} \\\\\n","\\cmidrule(l){2-4} \\cmidrule(l){5-7}\n"),
                                        paste("\\hline \n"),  # NEW row
                                        paste("\\hline \n"),
                                        paste0("\\hline \n \\multicolumn{",dim(beforeTable)[2],"}{p}",
                                               "",paste("{\\scriptsize{", "1 PS= number of privatized frims/number of SOEs \\newline 1 PS= number of privatized frims/number of SOEs","}}",sep = " "))
                                        # paste0("\\multicolumn{",dim(beforeTable)[2],"}{l}",
                                        #        "",paste("{\\scriptsize{", "2,Total of PS is yearly average;" ,"}}",sep = " "),"\n")
                 # paste is used as it is more flexible regarding adding lines

                                        )
                            )
          )
\end{document}

Above is the code I'm currently using, which works fine when I only need one table note,

but always gets wrong when I want more than one? How can I fix this?


text:
Q: Iterating model to create 3 buffers around three points and find their intersection (trilateration) in ArcMap This past summer I recorded the location of a large number of plants I was working with by calculating the distance from each plant to each of 3 tripods for which I have GPS coordinates. I'm trying to use ArcGIS 10 to reconstruct the location of each of these plants. I don't have the bearing from the focal plant to the reference points, only the distance. So as I understand it, this is a trilateration problem.
I've created the following model:

So I have the three GPS reference points as separate features, and each time I enter the distance from the focal plant to each of these reference points. It creates the three buffers, finds their intersection, and plots a point at the center of the intersection polygon.

Although this works, it is incredibly time consuming (~5 hours to get the first of four populations). I have around 1,300 more samples in three separate populations that I need to map in this way.
I cannot figure out how to make an iterative version of this model, however, in large part due to my inexperience with GIS. I have a hard time searching the help documents because the jargon is unfamiliar to me, so I think I just lack the correct keywords.
I have seen Trilateration using 3 latitude/longitude points, and 3 distances?, but as I searched to see how to convert between UTM and the coordinate system used there, it seemed that would be potentially problematic, and I feel like I'm 95% of the way to the solution with the model I already have.
The most obvious way this should work to me is to have an input feature that contains all of the reference and buffer distance data, and iterating through sets of three, or through a set of files each of which contains three points. However, when I've experimented with entering a table like this:

the intersection tool no longer outputs a single polygon where all three buffers overlap, but instead multiple polygons where there is an overlap between at least 2 of the buffers, like this:

I assume that this is because the three buffers are in a single feature instead of three different features, but why this would create a difference in the behavior of the intersection tool passes my understanding.
Furthermore, I don't seem to understand how to make iterators operate properly. My attempts at using the row or feature iterators always result in only one output representing the last row, even when I use dynamic naming of the output.
Is there some way to create an iterative version of this model, or should I just give up on it and go back to square one?


text:
Q: Data not loaded when API CALL made using fetch() function in REACTJS I have tried to make an apicall with react code and tried to print the response but it shows error
react code

    import React,{Component} from 'react'

    class ApiCall extends Component
    {
        constructor(props)
        {
            super(props);
            this.state=
            {
                items:[],
                isloaded:false,
            }
        }

        componentDidMount()
        {
            fetch('api.openweathermap.org/data/2.5/weather?q=chennai&appid=e407e5e8......')
            .then(res=>res.json())
            console.log(res.json())
            .then(json=>{
                 this.setState({
                     isloaded:true,
                     items: json,
                 })
            });
        }

        render()
        {
            var{isloaded,items}=this.state;

            if(!isloaded)
            {
                return
Loading..
;
            }
            else
            {
            return(

                   Data Loaded

                       {items.map(item=>(

                               Title: {item.title  }
                               Body:{item.body}

                       ))};

            )
            }
        }
    }

    export default ApiCall;

inside app.js

    class App extends Component
    {
      render()
      {
        return(

            <ApiCall/>

        )
      }
    }

**folder structure:
project:
src:
App.js
components:
apicall.js
**
I got an error in the browser saying,
Failed to compile
src\components\apicall.js
Line 20:21:  'res' is not defined  no-undef
Note:The link inside fetch() is taken from openweather website
Can somebody help me with this?

A: the issue is you are using the res outside of the then block to solve it add this to the code
.then((res) => {
    console.log(res.json());
    return res.json();
 })


text:
Q: What's the easiest way to generate a binary number of variable length consisting of all 1's in Java I have a variable called length.
I want to generate a binary number consisting of all 1's which is the length of my variable.
e.g. length = 4
     result = 1111
I've tried arithmetic shifting a 1 in a for loop, but I can't seem to get it to work.
edit: This is not my homework! I'm not even a student!
For those asking for an attempt, this is what I've tried:
        int test = 1;
        for(int i = 0; i<length;i++){
            test >> 1;
        }

A: The simplest way is to shift 1 by n, generating 2^n, then subtract 1 to get 2^n - 1, which is all ones in binary:
int result = (1 << length) - 1;
System.out.println(Integer.toBinaryString(result));

Explanation: Powers of two have a binary representation of one followed by n zeros (10000 for n=4) and can be generated by shifting 1 to the left n times. To get to this number by counting up in binary, the previous number has to be a sequence of ones (e.g. 1111 for n=4). So we just need to compute the corresponding power of two and subtract one to get the desired sequence of ones.

A: Depending if you need a String or an int, how to get it:
public static void main(String[] args) {
        int length = 14;

        //To provide a string
        String res1="";
        for(int i=0;i<length;i++) res1+='1';
        System.out.println(res1);

        //To provide an int
        int res2=0;
        for(int i=0;i<length;i++) res2+=Math.pow(2, i);
        System.out.println(Integer.toBinaryString(res2));
    }


text:
Q: Python pandas dataframes - transforming 2 columns with date ranges - into monthly columns for each month I am new to Python, starting to use Pandas to replace some processes done in MS Excel.
Below is my problem description
Initial dataframe:
Contract Id, Start date, End date

 12378,   '01-01-2018', '15-05-2018'
 45679,   '10-03-2018', '31-07-2018'
 567982,  '01-01-2018', '31-12-2020'

Expected output
Contract Id , Start date, End date, Jan-18,Feb-18,Mar-18,Apr-18,May-18...Dec-18
    12378, '01-01-2018', '15-05-2018', 1, 1, 1, 1, 1, 0, 0, 0, 0, .....,0
    45679, '10-03-2018', '31-07-2018', 0, 0, 1, 1, 1, 1, 1, 0, 0, 0....,0
    567982,'01-01-2018', '31-12-2020', 1, 1, 1, 1.........………..., 1, 1, 1

I would like to create a set of new columns with Month Id as column headers and populate them with a flag (1 or 0) if the contract is active during the specified month.
any help will be highly appreciated. Thank you

A: I also am new to pandas. Maybe there is a better method to do this, but here is what I have:
data['S_month'] = data['S'].apply(lambda x:int(x.split('-')[1]))
data['E_month'] = data['E'].apply(lambda x:int(x.split('-')[1]))
months = []
for s_e in data[['S_month','E_month']].values:
    month = np.zeros(12)
    month[s_e[0]-1:s_e[1]] = 1
    months.append(month)
months = pd.DataFrame(months,dtype=int,columns=np.arange(1,13))
data.join(months)

Or you could just skip the first two lines and do this:
months = []
for s_e in data[['S','E']].values:
    month = np.zeros(12)
    month[int(s_e[0].split('-')[1])-1:int(s_e[1].split('-')[1])] = 1
    months.append(month)
months = pd.DataFrame(months,dtype=int,columns=np.arange(1,13))
data.join(months)

A: This approach uses the very rich date functionality in pandas, specifically the PeriodIndex
import pandas as pd
import numpy as np
from io import StringIO

# Sample data (simplified)
df1 = pd.read_csv(StringIO("""
'Contract Id','Start date','End date'
12378,'01-02-2018','15-03-2018'
45679,'10-03-2018','31-05-2018'
567982,'01-01-2018','30-06-2018'
"""), quotechar="'", dayfirst=True, parse_dates=[1,2])

# Establish the month dates as a pandas PeriodIndex, using month end
dates = pd.period_range(df1['Start date'].min(), df1['End date'].max(), freq="M")

# create new dataframe with date matches with apply
# Match the start dates to the periods using the Period dates comparisons
# AND the result elementwise   using numpy logial _nd
data = df1.apply(lambda r: pd.Series(np.logical_and(r[1] <= dates, r[2] >= dates).astype(int)), axis=1)

# Data frame with named month columns
df2 = pd.DataFrame(data)
df2.columns = dates

# Cooncatenate
result = pd.concat([df1, df2], axis=1)
result

#   Contract Id Start date   End date  2018-01  2018-02  2018-03  2018-04  2018-05  2018-06
#0        12378 2018-02-01 2018-03-15        0        1        1        0        0        0
#1        45679 2018-03-10 2018-05-31        0        0        1        1        1        0
#2       567982 2018-01-01 2018-06-30        1        1        1        1        1        1

A: Pandas comes with a lot of built-in date/time handling methods that can be put to good use here.
# SETUP
# -----
import pandas as pd

# Initialize input dataframe
data = [
    [12378, '01-01-2018', '15-05-2018'],
    [45679, '10-03-2018', '31-07-2018'],
    [567982, '01-01-2018', '31-12-2020'],
]
columns = ['Contract Id', 'Start date', 'End date']
df = pd.DataFrame(data, columns=columns)

# SOLUTION
# --------
# Convert strings to datetime objects
df['Start date'] = pd.to_datetime(df['Start date'], format='%d-%m-%Y')
df['End date'] = pd.to_datetime(df['End date'], format='%d-%m-%Y')

# For each month in year 2018 ...
for x in pd.date_range('2018-01', '2018-12', freq='MS'):
    # Create a column with contract-active flags
    df[x.strftime("%b-%y")] = (df['Start date'].dt.month <= x.month) & (x.month <= df['End date'].dt.month)

    # Optional: convert True/False values to 0/1 values
    df[x.strftime("%b-%y")] = df[x.strftime("%b-%y")].astype(int)

which gives as result:
In [1]: df
Out[1]:
   Contract Id Start date   End date  Jan-18  Feb-18  Mar-18  Apr-18  May-18  Jun-18  Jul-18  Aug-18  Sep-18  Oct-18  Nov-18  Dec-18
0        12378 2018-01-01 2018-05-15       1       1       1       1       1       0       0       0       0       0       0       0
1        45679 2018-03-10 2018-07-31       0       0       1       1       1       1       1       0       0       0       0       0
2       567982 2018-01-01 2020-12-31       1       1       1       1       1       1       1       1       1       1       1       1


text:
Q: Approximating the optimal value of a function involving a Gaussian integral Consider the following function
$$
f(\lambda) = \alpha (1+\lambda^2) + (1-\alpha)2\int_\lambda^\infty (x-\lambda)^2 \phi(x) dx
$$
where $\alpha \in (0,1)$ and $\phi$ is the standard normal probability density function.
Is there a good (closed-form) approximation to the minimum value and/or minimizer of $f$ over $[0,\infty)$?

A: Using Leibniz's rule to differentiate the integral we have
$$\frac {\partial}{\partial \lambda} \int_\lambda^\infty (x-\lambda)^2 \phi(x) dx = -(\lambda-\lambda)^2 \phi(\lambda) + \int_\lambda^\infty \frac {\partial}{\partial \lambda}(x-\lambda)^2 \phi(x) dx$$
$$=-2\int_\lambda^\infty (x-\lambda)\phi(x) dx = -2\int_\lambda^\infty x\phi(x) dx +2\lambda\int_\lambda^\infty \phi(x) dx$$
The integrals can be transformed into truncated standard normals in $[\lambda, \infty]$
$$\frac {\partial}{\partial \lambda} \int_\lambda^\infty (x-\lambda)^2 \phi(x) dx =-2\Phi(-\lambda)\int_\lambda^\infty x\phi(x)\left[\Phi(-\lambda)\right]^{-1} dx +2\lambda\Phi(-\lambda)\int_\lambda^\infty \phi(x)\left[\Phi(-\lambda)\right]^{-1} dx$$
$$\Rightarrow \frac {\partial}{\partial \lambda} \int_\lambda^\infty (x-\lambda)^2 \phi(x)  dx =-2\phi(\lambda) +2\lambda\Phi(-\lambda)\cdot 1$$
Then (simplyfying $2$)
$$\frac {\partial f(\lambda)}{\partial \lambda} = \alpha\lambda - 2(1-\alpha)\left[\phi(\lambda) -\lambda\Phi(-\lambda)\right] = 0$$
$$\alpha\lambda = 2(1-\alpha)\left[\phi(\lambda) -\lambda\Phi(-\lambda)\right] \qquad [1]$$
From $[1]$ it is obvious that $\lambda^* \neq0$. Then
$$\frac {\alpha}{2(1-\alpha)}=\left[\phi(\lambda)\lambda^{-1} -\Phi(-\lambda)\right] =  \phi(\lambda)\left[\lambda^{-1} -m(\lambda)\right]$$
where $m(\lambda)$ is Mills ratio of the standard normal. The traditional approximation to the mills ratio of the standard normal is $m(\lambda) = \lambda^{-1} - \lambda^{-3} +3\lambda^{-5} -...$ (for lots of stuff on Mills ratio and other approximation see here). Use just the first two terms to obtain
$$\frac {\alpha}{2(1-\alpha)}\approx  \lambda^{-3}\phi(\lambda) = \lambda^{-3}\frac{1}{\sqrt{2\pi}}e^{-\frac 12 \lambda^2}$$
$$\Rightarrow \ln\left(\frac {\alpha}{2(1-\alpha)}\right) +\frac 12 \ln {2\pi}\approx -3\ln \lambda -\frac 12 \lambda^2$$
Approximate (at your peril) $\ln \lambda \approx \lambda -1$ to obtain
$$\ln\left(\frac {\alpha}{2(1-\alpha)}\right) +\frac 12 \ln {2\pi}\approx -3(\lambda -1)-\frac 12 \lambda^2$$
$$\Rightarrow \frac 12 \lambda^2 +3\lambda -3+\ln\left(\frac {\alpha}{2(1-\alpha)}\right) +\frac 12 \ln {2\pi} =0$$
which is a quadratic in $\lambda$ and the roots will be a function of $\alpha$.


text:
Q: How I can check if a object array key exists in Array Javascript I have following array
 let newArray = [
    {
      "conterTop": {
        "uncategroized": [item1, item2, item3],
        "categroized": [item4, item5]
      }
    },
    {
      "flooring": {
        "uncategroized": [item1, item2, item3],
        "categroized": [item4, item5]
      }
    }
]

I'm pushing countertop & flooring on runtime. Now I need to check if countertop already exists in newArray, it should not push countertop again. I have tried newArray.includes() but it's not working. Please any suggestion?

A: You can filter the array to look for your matching key and check the length of the filtered array. If the length is greater than 0, it exists. If not, it doesn't.
newArray.filter(x => return typeof(x.countertop) !== "undefined").length > 0

A: Here I just filtered out every value that doesn't have counterTop and check if any value left

let newArray = [{
    "conterTop": {
      "uncategroized": [1, 2, 3],
      "categroized": [4, 5]
    }
  },
  {
    "flooring": {
      "uncategroized": [1, 2, 3],
      "categroized": [4, 5]
    }
  }
];

let isCounterTopExists = newArray.filter(x => x.conterTop).length > 0
console.log(isCounterTopExists);

A: This is what Array.prototype.some is for:

let newArray = [
    {
      "conterTop": {}
    },
    {
      "flooring": {}
    }
];

let testArray = [
  {
    "flooring": {}
  }
];

const testArrayResult = testArray.some(obj => obj.conterTop);
const newArrayResult = newArray.some(obj => obj.conterTop);

console.log("testArray has 'conterTop':", testArrayResult);
console.log("newArray has 'conterTop':", newArrayResult);


text:
Q: No puedo imprimir un dato que pertenece a otra tabla Mi problema surge dentro de un foreach en una vista que incluye una relación entre 2 tablas. La tabla de pedidos y productos. En la tabla de pedidos uno puede ver cuáles productos fueron seleccionados y lo que intento realizar es mostrar los datos (productos) seleccionados a la tabla de "pedidos". No tengo error en insertar, sólo en la parte de mostrar dichos datos, puedo mostrar el id pero no es lo que deseo hacer.
Vista:
    @slot('display')
        @foreach($pedidos as $pedido)

                 {{ $pedido->miembro }}
                 {{ $pedido->grupo->nombre }}
                 {{ $pedido->productos->producto }}
                 {{ $pedido->cantidad }}

                        X

        @endforeach
    @endslot

Miembro = miembro, Grupo = grupo_id, Producto = grupo_id, Cantidad = cantidad. Sólo intento relacionar 2 columnas y es curioso que en el caso de grupo_id no haya tenido problemas.
Migración:
        Schema::create('pedidos', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('producto_id')->unsigned();
            $table->foreign('producto_id')->references('id')->on('productos');
            $table->string('miembro');
            $table->bigInteger('grupo_id')->unsigned();
            $table->foreign('grupo_id')->references('id')->on('grupos');
            $table->integer('cantidad');
            $table->timestamps();
        });

Mensaje de error:
Trying to get property 'producto' of non-object (View: /Users/eduardocoello/Projects/plenitud/resources/views/pedidos.blade.php)
Modelos
Producto:
    public function pedido()
    {
        $this->hasMany(Pedido::class);
    }

Pedido:
    public function producto()
    {
        return $this->hasMany(Producto::class);
    }

Controlador de PedidosController, funciones.
    public function index()
    {
        $pedidos = Pedido::all();
        $grupos = Grupo::all();
        $productos = Producto::all();
        return view('/pedidos', compact('pedidos', 'grupos', 'productos'));
    }

        public function create()
    {
        $grupos = Grupo::all();
        $productos = Producto::all();
        return view('pedidos.crear', compact('grupos', 'productos'));
    }

    public function store(Request $request)
    {
        $pedidos = new Pedido();
        $pedidos->producto_id = request('producto');
        $pedidos->miembro = request('miembro');
        $pedidos->grupo_id = request('grupo');
        $pedidos->cantidad = request('cantidad');

        $pedidos->save();
        return redirect('/pedidos');
    }

A: Relación Muchos a Muchos
Estructura de las tablas
Para definir esta relación, se necesitan tres tablas de base de datos: productos, pedidos y pedido_producto. La tabla pedido_producto se deriva del orden alfabético de los nombres de modelo relacionados y contiene las columnas pedido_id y producto_id:
Migración productos:
Schema::create('productos', function (Blueprint $table) {
    $table->bigIncrements('id');
    // las demás columnas
});

Migración pedidos:
Schema::create('pedidos', function (Blueprint $table) {
    // $table->id(); // esto nunca lo ví y no sé si funcione, supongo que quieres una columna id autoincremental
    $table->bigIncrements('id');
    // esta llave foránea no va aquí, la agregas en la tabla pivot
    // $table->bigInteger('producto_id')->unsigned();
    // $table->foreign('producto_id')->references('id')->on('productos');
    // las demás columnas
});

Migración tabla de relación entre pedidos y productos:
Schema::create('pedido_producto', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('pedido_id')->unsigned();
    $table->foreign('pedido_id')->references('id')->on('pedidos');
    $table->bigInteger('producto_id')->unsigned();
    $table->foreign('producto_id')->references('id')->on('productos');
});

Estructura del Modelo
Las relaciones de muchos a muchos se definen escribiendo un método que devuelve el resultado del método belongToMany. Por ejemplo, definamos el método de productos en nuestro modelo de Pedido:
/**
 * Los productos que pertenecen a un Pedido.
 */
public function productos()
{
    return $this->belongsToMany(Producto::class);
}

Una vez que se define la relación, puedes acceder a los productos del pedido utilizando la propiedad dinámica de productos:
$pedido = Pedido::find(1);

foreach ($pedido->productos as $producto) {
    //
}

O en Blade, si estás iterando sobre una colección de Pedido:
@foreach($pedidos as $pedido)
    @foreach($pedido->productos as $producto)
        {{ $producto->id }}
    @endforeach
@endforeach

Definiendo la inversa de la relación
Para definir la inversa de una relación de muchos a muchos, realiza otra llamada a belongsToMany en tu modelo Producto.
/**
 * los pedidos que pertenecen a un Producto.
 */
public function pedidos()
{
    return $this->belongsToMany(Pedido::class);
}

Y accedes de la siguiente manera:
$producto = Producto::find(1);

foreach ($producto->pedidos as $pedido) {
    //
}


text:
Q: Dual criteria data validation in Excel Unlike the other questions posted with this topic, my criteria are not simple comparators. I want a dropdown list that includes all values in one named table excluding those values that meet another criteria. For instance a table includes employee names in one column and vacation dates in another column. I want the data validation to allow a list of employees who are not on vacation for a variable date drawn from another cell. The general method seems to be to create additional tables where the secondary criteria (in this case date) is the column header populated by items from the first list that satisfy some criteria. It seems impractical to create 365 tables named for each date and populated by rows of employees from the first table that have not requested that date off. Is there another way to accomplish this?
Sample Data:
| Employee| Vacation Dates  |        | work on 1/26/20 |
_____________________________        ___________________
| Bob     | 1/26/20, 1/27/20|        | <allow only     |
| Mike    | 2/20/20, 2/21/20|        | Mike or Cindy>  |
| Cindy   | 2/20/20, 1/28/20|

A: Had to transpose my thinking. Rather than a table for each date, I can have a vacation table for each employee. The validation formula has to be a custom validation rather than a list, so no drop down selection list is available, but it will work. Error message also cannot discriminate which criteria is being violated -- name not on employee list versus name from employee list who is on vacation. Would be great if validation worked like conditional formatting with different rules applied in sequence.
| Employee| Bob   | Mike    | Cindy |        | 1/26/20 |
____________________________________|        ___________
| Bob     |1/26/20| 2/20/20 |2/20/20|        |         |
| Mike    |1/27/20| 2/21/20 |1/28/20|        |         |
| Cindy   |

The validation formula for the "1/26/20" column (F in the scheme above) would be
=AND(COUNTIF($A$2:$A$4,F2)>0,COUNTIF(INDIRECT(ADDRESS(2,MATCH(F2,$B$1:$D$1,0)+1)):INDIRECT(ADDRESS(3,MATCH(G2,$B$1:$D$1,0)+1)),F1)<1)


text:
Q: Web API v2 Filter checking different types for same field I have the code below in an API filter.  The SampleRequester object is just information from a form.  It has a property called captcha.  It works great but i have other forms that will also have a captcha property.  And this will only work for SampleRequester objects.  How could I check any object for a captcha property?
public class ValidateCaptcha : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var cookiePayload = actionContext.Request.GetCookie("MyCaptcha");
        SampleRequester requester = (SampleRequester)actionContext.ActionArguments["requester"];
        if(cookiePayload !== requester.captcha)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
        }

    }

}

A: If you know the possible types in advance, you can use the as operator:
public class ValidateCaptcha : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var cookiePayload = actionContext.Request.GetCookie("MyCaptcha");
        var requester = actionContext.ActionArguments["requester"] as SampleRequester;
        if (requester != null && cookiePayload == requester.captcha)
             return;
        requester = actionContext.ActionArguments["requester"] as AnotherRequester;
        if (requester != null && cookiePayload == requester.captcha)
             return;

        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
    }
}

If you don't, but you expect whatever type to have the property captcha, you can use dynamic:
public class ValidateCaptcha : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var cookiePayload = actionContext.Request.GetCookie("MyCaptcha");
        dynamic requester = actionContext.ActionArguments["requester"];
        if (requester != null && cookiePayload == requester.captcha)
             return;

        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
    }

}

Ideally, the first option, while making sure that all Requesters implement the same interface, so you can use as to the interface type.
I wonder, why you have the Captcha value in the Cookie?

A: My solution was to use inheritance.  I created a base class called Form that has only the captcha property.  Then when in the filter I simply cast the requester object to a Form object.  The full example can be seen below:
public class ValidateCaptcha : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var cookiePayload = actionContext.Request.GetCookie("MyCaptcha");
        Form form = (Form)actionContext.ActionArguments["requester"];
        if(cookiePayload != form.captcha)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
        }

    }

}


text:
Q: What can be expected in terms of latency with tcp/ip over the loopback interface on windows? I am measuring the latency of a TCP/IP connection on windows over the loopback interface and getting about 4ms for the time from a message is sent to a response is received.
For RPC purposes there is a TCF layer on top of TCP/IP.
The messages sent and received contain only a single character as payload in addition to the TCF framing.
The "server" which handles the commands are implemented in C++ using boost asio.
The "client" sending commands is a Python script that uses the Python TCF reference implementation.
I have tried setting the socket options to TCP_NODELAY to disable the Nagle algorithm and experimented with various buffersizes for the socket, but the roundtrip time remains at about 4ms. I was expecting it to be quite a bit lower.
Profiling on the C++ side shows that it spends about 50% of it's execution time waiting for commands, so the next step will be to try and replace the python script with a C++ implementation, but it would be nice to know what one can expect for the roundtrip time on the loopback interface.
This SO, question:
Linux Loopback performance with TCP_NODELAY enabled
is related but did not quite answer my question.

A: You can establish a lower bound on the latency with ping localhost. The number it reports is one packet sent, one received.
If your TCP message is sent on an existing connection, you might get nearly that latency.
If your measured time included the TCP connection setup, you might get 10x that latency.


text:
Q: Android strange behavior on orientation change with Custom View in fragment I have a FragmentActivity which shows a Fragment by defualt. The fragment consists of an EditText, a TextView and a Custom DropDown, made by extending AutoCompleteTextView.
If my custom AutoCompleteTextView is focused or the drop down list is open and I change the orientation of the device. I get following exception:

Failed Looking up window
  java.lang.IllegalArgumentException: Requested window null does not exist

It works if the custom AutoCompleteTextView is not in focused state.
I've tried removing the focus in onSaveInstanceState() by making other layout get focus by requestFocus()
I've searched for this on the internet for more then 2 days, and it seems that no one has faced such issue before regarding Custom Views in context of fragments and orientation change.
Here is my FragmentActivity:
public class Balance_Inquiry extends FragmentActivity implements OnTouchListener, EventCallbackListener, DataCallBack,CustomResultReceiver.Receiver  {

LinearLayout balInquiryLayout;
FragmentTransaction fragmentTransaction;
FragmentManager fm;
Fragment fr;

//SQLiteDatabase sql;
//ConDb db;

public final static int ACTIVITY_ID = 2;
private Bundle orientationData;

protected void onCreate(Bundle savedInstanceState){

    try{
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    int screenWidth = (int) (metrics.widthPixels * 0.90);

    setContentView(R.layout.common_blank_dialog);
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(App.context()));

    getWindow().setLayout(screenWidth, LayoutParams.WRAP_CONTENT);

    balInquiryLayout = (LinearLayout) findViewById(R.id.dialogtoplayout);
    orientationData = savedInstanceState;
    if(savedInstanceState == null){
        fr = new Balance_Main_Fragment();
         fm = getSupportFragmentManager();
         fragmentTransaction = fm.beginTransaction();
         fragmentTransaction.setCustomAnimations(R.anim.zoom_enter, R.anim.zoom_exit);
         fragmentTransaction.add(R.id.dialogtoplayout, fr,"tag1");
         fragmentTransaction.commit();
    }
    else{
         fr = getSupportFragmentManager().findFragmentByTag("tag1");
    }

    balInquiryLayout.setOnTouchListener(this);
    }
    catch(Exception e){
        e.printStackTrace();
    }

}

@Override
public boolean onTouch(View v, MotionEvent event) {

    balInquiryLayout.requestFocus();
    DisableKeyboard.hideKB(v, getApplicationContext());
    return false;
}

private AccountBean ab_;
private ValuesBean resp_;

public void show_result(){
    try{
      fr = new Balance_Result_Fragment();
         fm = getSupportFragmentManager();
         fragmentTransaction = fm.beginTransaction();
         fragmentTransaction.setCustomAnimations(R.anim.zoom_enter, R.anim.zoom_exit);
         fragmentTransaction.add(R.id.dialogtoplayout, fr, "tag2");
         fragmentTransaction.commit();
    }

    catch(Exception e){
        e.printStackTrace();
    }
}

public void hideResult(){

      fr = new Balance_Result_Fragment();
         fm = getSupportFragmentManager();
    fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.setCustomAnimations(R.anim.zoom_exit,R.anim.zoom_enter);
    fragmentTransaction.remove(fr).commit();

    //new Balance_Main_Fragment().clearAll();

}

@Override
public void onButtonClicked(int a) {

    switch(a){

            case 0:
                {

                    hideResult();

                    try{

                          fm = getSupportFragmentManager();
                          Balance_Main_Fragment fre=(Balance_Main_Fragment)getSupportFragmentManager().findFragmentByTag("tag1");
                             fre.clearAll();

                         fre.enableButtons();
                         }
                         catch(Exception e){
                             e.printStackTrace();
                         }

                    break;
                }

            case 1:
            {
                show_result();
                break;
            }

    }

}

@Override
public void passData(String... a) {

}

@Override
public void passData(Object... a) {
    try{
     this.ab_=(AccountBean) a[0];
     this.resp_ = (ValuesBean) a[1];
     }
    catch(ClassCastException e){
        e.printStackTrace();
    }

}

@Override
public Object[] getData() {
    // TODO Auto-generated method stub
    return new Object[]{this.ab_,this.resp_};
}

@Override
public void onBackPressed(){
    if(MainExpandActivity.backApprove== true){
        if(ParserMain.isMyServiceRunning(MessengerService.class, this)){
        NetworkThread.stopServiceNow(Balance_Inquiry.this);
        NetworkThread.unBindServicePlz(Balance_Inquiry.this);
        }
        super.onBackPressed();
    }
    else{
        // do nothing here hehehehe
    }

}

@Override
public void onReceiveResult(int resultCode, final Bundle resultData) {
    Log.e("activity", "activties onRecieveresul is called");
}

public void onDestroy(){
    //NetworkThread.unBindServicePlz(Balance_Inquiry.this);
    super.onDestroy();
    Log.e("onDestory()", "onDestory() is called");
    if(isFinishing()){
        NetworkThread.unBindServicePlz(this.getApplicationContext());
        NetworkThread.stopServiceNow(this.getApplicationContext());
        Log.e("onDestory()", "isFinishing() block");
    }

}

public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);

  if(hasFocus)
     Toast.makeText(Balance_Inquiry.this, "focus gained", Toast.LENGTH_LONG).show();

  else
      Toast.makeText(Balance_Inquiry.this, "focus lost", Toast.LENGTH_LONG).show();
}

public void onPause(){
    Log.e("onPause()", "pause called");
    balInquiryLayout.requestFocus();

    super.onPause();

    }

}

Following is my Fragment class, posting only relevant snippets from it:
InstantAutoComplete accounts;  // custom View
LinearLayout balInq2ndLayout;
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    setRetainInstance(true);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    main_view = inflater.inflate(R.layout.fragment_balance1, container,false);
    sub = (Button) main_view.findViewById(R.id.sub_bal);

    cancel = (Button) main_view.findViewById(R.id.cancel_bal);

    accounts = (InstantAutoComplete) main_view.findViewById(R.id.bal_accounts);

    mHat = new Handler();
    balInq2ndLayout = (LinearLayout) main_view.findViewById(R.id.balInq2ndLayout);
    balInq2ndLayout_2 = (LinearLayout) main_view.findViewById(R.id.balInq2ndLayout_2);

    macBalance = (TextView) main_view.findViewById(R.id.macbal_balinq);

    macBalance.setText(SessionInfo.getBalanceString()+SessionInfo.getMacBalance());
    bal_prog = (TextView) main_view.findViewById(R.id.bal_status);

    pb = (ProgressBar) main_view.findViewById(R.id.progressBarBalance);
    pb.setVisibility(View.GONE);
    balInq2ndLayout.requestFocus();
    balInq2ndLayout.setOnTouchListener(this);
    balInq2ndLayout_2.setOnTouchListener(this);

    pin_no = (EditText) main_view.findViewById(R.id.bal_pin);

    bal_accountLocked = (EditText) main_view.findViewById(R.id.bal_accountlocked);

    bal_accountLocked.setEnabled(false);
    bal_accountLocked.setFocusable(false);
    bal_accountLocked.setVisibility(View.GONE);

    myData = new Bundle();

    if(savedInstanceState==null){

    bal_accountLocked.setVisibility(View.GONE);

    }
    else{

        pin_no.setText(savedInstanceState.getString("pin"));

        if(savedInstanceState.getBoolean("key")){
            bal_accountLocked.setVisibility(View.VISIBLE);
            bal_accountLocked.setText(savedInstanceState.getString("locked"));
        }

        if(accounts.getText().toString().length()!=0){
            ab = savedInstanceState.getParcelable("ab");
        }

        if(savedInstanceState.getBoolean("progress")){

            pb.setVisibility(View.VISIBLE);
            disableButtons();
        }

        accounts.setText(savedInstanceState.getString("account"));

    }

    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(App.context()));

    final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.select_dialog_item, ObjectsHolder.ab);
    accounts.setAdapter(adapter);

    accounts.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){
                if(accounts.getText().length()==0){
                //Toast.makeText(getActivity(), "focus lost", Toast.LENGTH_LONG).show();
                accounts.setText(saved1);
                DisableKeyboard.disableSoftInputFromAppearing(accounts, getActivity());

                    }
                }
            else if(hasFocus){
                DisableKeyboard.disableSoftInputFromAppearing(accounts, getActivity());
            }

        }
    });

    accounts.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            DisableKeyboard.disableSoftInputFromAppearing(accounts, getActivity());
            saved1=DisableKeyboard.showAll(accounts);
            if(accounts.getText().toString().length()==0){
                bal_accountLocked.setText("");
                bal_accountLocked.setVisibility(View.GONE);
            }
            return false;
        }
    });

    accounts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id){
                Log.e("inside setOnItemSelectedListener", "this is called normally");
                //Toast.makeText(arg0.getContext(), "On item click: "+arg0.getItemAtPosition(arg2), 1).show();
                ab= (AccountBean) adapter.getItem(position);

                //ab = (AccountBean) arg0.getItemAtPosition(arg2);
                if(ab==null){
                    Log.e("ab object", "is null :(");
                }
                else{
                    bal_accountLocked.setVisibility(View.VISIBLE);
                    bal_accountLocked.setText(ab.getAccountNumber());
                }
                //saved1 = (String) arg0.getItemAtPosition(arg2);
    }

    });

    return main_view;

}

@Override
public boolean onTouch(View v, MotionEvent event) {
    balInq2ndLayout.requestFocus();
    DisableKeyboard.hideKB(v, getActivity());
    return false;
}

    public void onSaveInstanceState(Bundle state){
      super.onSaveInstanceState(state);
      Log.e("onSaved", "onSaved is  called");
      balInq2ndLayout.requestFocus(); // setting request here to LinearLayout
      if(bal_accountLocked.isShown()){
      state.putString("locked", bal_accountLocked.getText().toString());
      state.putBoolean("key", true);
      }
      if(ab!=null){
        state.putParcelable("ab", ab);
      }
      state.putString("pin", pin_no.getText().toString());

      if(pb.getVisibility() == View.VISIBLE){
        state.putBoolean("progress", true);
        state.putBoolean("back", true);
      }

      if(accounts.getText().toString().length()!=0){
        state.putString("account", accounts.getText().toString());
      }

  }

Finally This is my custom AutoCompleteTextView
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;

public class InstantAutoComplete extends AutoCompleteTextView {
String savedTexti2;

public InstantAutoComplete(Context context) {
    super(context);
}

public InstantAutoComplete(Context arg0, AttributeSet arg1) {
    super(arg0, arg1);
}

public InstantAutoComplete(Context arg0, AttributeSet arg1, int arg2) {
    super(arg0, arg1, arg2);
}

@Override
public boolean enoughToFilter() {
    return true;
}

@Override
protected void onFocusChanged(boolean focused, int direction,
        Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    if (focused) {
        performFiltering(getText(), 0);
        showAll();
    }
    else{
        //Toast.makeText(getContext(), "works", 10).show();
        //restore();
    }

}

public void restore() {
    this.setText(savedTexti2);
}

public void showAll() {
    savedTexti2 = this.getText().toString();
    this.setText("");
    this.showDropDown();
    }

}

Here is the complete StackTrace:

Failed looking up window
  java.lang.IllegalArgumentException: Requested window null does not exist
  at com.android.server.WindowManagerService.windowForClientLocked(WindowManagerService.java:9293)
  at com.android.server.WindowManagerService.addWindow(WindowManagerService.java:1891)
  at com.android.server.WindowManagerService$Session.add(WindowManagerService.java:6771)
  at android.view.IWindowSession$Stub.onTransact(IWindowSession.java:66)
  at com.android.server.WindowManagerService$Session.onTransact(WindowManagerService.java:6743)
  at android.os.Binder.execTransact(Binder.java:288)
  at dalvik.system.NativeStart.run(Native Method)
  Attempted to add window with token that is not a window: null.  Aborting.

I've tried many different things, like removing focus from the AutoCompleteTextView , switching focus.. but nothing seems to work. If anyone can help me I would be grateful as I've visited each and every corner of stackoverflow but no luck. If someone has faced this issue and managed to solve it, please help a brother here.
--EDIT--
This issue was produced in emulator of API 8
Tested it on Emulator of JellyBean API 17 and it works fine. No exception. I wonder if its only related to lower APIs. Have to check them all one by one. sigh


text:
Q: Add/Subtract/etc element by the next element in an array I have an array with [25, -6, 14, 7, 100]. The expected output is
Sum:        = 140
Difference: = -90
Product:    = -147000

Basically, the next element is subtracted/added to the current element when looping. That sum and product is easy as I only need to do
for (int i = 0; i < array.length; i++) {
  System.out.println(" => " + array[I]);
  sum += i;
  product *= i;
}

The problem is that when I do difference -= i, it gives me -108, which is wrong. And when there is only a single element in the array, it gives me the negative form of the element. e.g.
String[] array = [32] // outputs -32

I tried looping through the code like:
for (int i = 0; i < arrayNumbers.length; i++) {
  System.out.println(arrayNumbers[i] - arrayNumbers[i + 1]);
}

and it gives me Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

A: you are basing you calculation on index while you must base it on array[index]
var sum=0;
var difference=0;
var product=1;

for (int i = 0; i < array.length; i++) {
  System.out.println(" => " + i);
  sum += array[i];
  if (i ==0)
    difference+=array[i];
  else
    difference-=array[i];
  product *= array[i];
}

A: FOUND THE ANSWER
int[] array = {25, -6, 14, 7, 100}

int sum = 0;
int product = 1;
int difference = 0;

for (int i = 0; i < array.length; i++) {
  System.out.println(" => " + array[i]);
  sum += i;
  product *= I;
  if (i == 0)
    difference = i;
  else
    difference -= i;
}

A: This Exception
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1"
is due to the reason that whin i=arrayNumbers.length-1,then in the Code:
the arrayNumbers[i + 1] gives an exception as it is accessing the arrayNumbers[arrayNumbers.length];


text:
Q: Is there an R spline that matches the Schoenberg algorithm? Is there a R algorithm that fit smoothing splines while minimizing L,
L = ρ ∑ (i from 0 to n-1) wi(yi-Si(xi))² + (1 - ρ) ∫ (x from 0 to x_(n-1)) (S''(x))² dx
Maybe it's possible with smooth.spline but I didn't succeed to find the good parameters.
(The equation can be seen more clearly here : https://www.iro.umontreal.ca/~simardr/ssj/doc/html/umontreal/iro/lecuyer/functionfit/SmoothingCubicSpline.html)

A: pspline::smooth.Pspline(  x = input_x,
                          y = input_y,
                          norder = 2,
                          method = 1,
                          spar = rho)

will do the job.


text:
Q: how to use gulp to call au build in a typescript aurelia cli project? I built an aspnetcore web project use vs207, and then use aurelia-cli (aspnetcore and typescript) created the front end. it works fine when I run au build in command prompt. but I want to use vs2017 to build it automatically when file is changed.
my gulpfile.js looks like:
var gulp = require('gulp');
var shell = require('gulp-shell');

gulp.task('build', shell.task('au build'));

the Task Runner Explorer can show the task correctly, but when I double click the build task, there are errors:
[12:31:10] Starting 'build'...
[12:31:10] 'build' errored after 14 ms
[12:31:10] Error: spawn au build ENOENT
    at exports._errnoException (util.js:856:11)
    at Process.ChildProcess._handle.onexit
(internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at nextTickCallbackWith2Args (node.js:474:9)
    at process._tickCallback (node.js:388:17)
    at Function.Module.runMain (module.js:431:11)
    at startup (node.js:139:18)
    at node.js:999:3
Process terminated with code 1.

not sure the reason, is there something I miss?

A: You might need to specify which Node version you want VS to use, in VS2017 you can change it in Tools \ Options \ Projects and Solutions \ Web Package Management.
Also you might also want to change the Gulp file so that you can start "au build --watch" instead of "au build". The cli already supports "au run --watch", but not "au build --watch". If you want to build on changes I think using this will be much faster than running a complete "au build"
Check out the comment here for details on how to add "au build --watch" to your gulp file:
https://github.com/aurelia/cli/issues/240#issuecomment-238179488


text:
Q: Urysohn's Lemma, Stone-Weierstrass
Let $X$ be a compact space. Show that the following statements are equivalent:
a) $X$ is homeomorphic to a compact subset of $\mathbb{R}^n$
b) There are functions $f_1,\dotso, f_n\in C(X)=\{f:X\to\mathbb{C}\quad\text{continuous}\}$, such that every linear combination of functions from the form
$x\mapsto f_1(x)^{k_1}\cdot\dotso\cdot f_n(x)^{k_n}$ with $k_1,\dotso, k_n\in\mathbb{N}_0$ are dense in $C(X)$.

Hello,
I want to proof the implication a) "$\Rightarrow$" b).
For this task the hint is given, that we need the theorem of Stone-Weierstrass and Urysohn's Lemma.
To proof the first implication, I need a subalgebra $\mathcal{A}\subseteq C(X)$, which contains every linear combination of functions from the form above:
$x\mapsto f_1(x)^{k_1}\cdot\dotso\cdot f_n(x)^{k_n}$ with $k_1,\dotso, k_n\in\mathbb{N}_0$
How can I note this set $\mathcal{A}$?
$\mathcal{A}:=\{\sum_{i=1}^k f_{i_1}^{k_{i_1}}\cdot\dotso\cdot f_{i_n}^{k_{i_n}}, f_{i_1},\dotso, f_{i_n}\in C(X), k_{i_1},\dotso, k_{i_n}\in\mathbb{N}_0\}$
I am not sure, because the product of these functions can contain any function, and I do not really know, how to note it as a set.
After that I have to prove that $\mathcal{A}$ is a subalgebra and holds the three conditions of Stone-Weierstrass:
1) contains the constant functions
2) self-adjoint
3) seperates points
Thanks in advance for any help.

A: For $a \implies b$, consider a subset $X \subseteq \Bbb R^n$, and the collection of functions
$$
f_1(\mathbf x) = x_1, f_2(\mathbf x) = x_2,\dots, f_n(\mathbf x) = x_{n}
$$
Note that $\mathcal A$ contains the constant function
$$
g(x) = (f_1)^0(f_2)^0 \cdots (f_n)^0
$$
moreover, $\mathcal A$ separates points since for any two elements $\mathbf a = (a_1,\dots,a_n) \in X, \mathbf b = (b_1,\dots, b_n)\in X$, we can take the function
$$
g(\mathbf x) = (x_1-a_1)^2 + (x_2-a_2)^2 + \cdots + (x_n-a_n)^2
$$
which satisfies $g(\mathbf a) = 0$ and $g(\mathbf b) = \|\mathbf a - \mathbf b\|^2 > 0$.
If $X$ is homeomorphic to a subset of $\Bbb R^n$, all of this still works.  In particular, suppose that $h : X \to Y \subset \Bbb R^n$ is a homeomorphism.  Then, for $x \in X$, we can define
$$
\tilde f_i(x) = f_i (h(x))
$$
where $f_i$ are the "projections" as defined above.

For $b \implies a$, I think the idea is to define the map $h:X \to \Bbb R^n$ by
$$
h(x) = (f_1(x),\dots,f_n(x))
$$
and show that this map is a homeomorphism.  However, in the problem as written, the $f_i$ are complex-valued, which means that this isn't even a map into $\Bbb R^n$.


text:
Q: Slack App (bot) send private messages to multiple users i'm trying to create a chess bot to play with other users on the workspace. I can't figure out how to create a private conversation including 2 users (the 2 players) and the bot user. To play in private.
I tried to use the slack api but it does not work.

A: I would recommend using a "multi-person direct message" (MPIM). It allows you to create a new / or join an existing direct message channel with multiple users, e.g. 2 players and your bot user.
A MPIM is different from a private channel as it does not require a dedicated name and you can create multiple in the same workspace as long as it contains a different set of users.
To open a MPIM call the API method conversations.open with your bot user token and provide the user IDs of the two users in the users parameter. You will get a channel ID in return, which you can use later to resume the conversation. Alternatively you can just open it again with the same list of users.


text:
Q: How to make the created JAR file from Maven-WAR plugin into build path I have used Maven -war plugin to create a JAR from another reference WAR .Now this JAR is available in the target folder.
My problem is I have to use the class which is available inside the created JAR in target folder but I am unable to get the class from JAR.
Is it possible to make available the created JAR available in the classpath through POM.
My maven WAR plugin as like below.
<plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.1.1</version>
                    <configuration>
                        <overlays>
                            <overlay />
                            <overlay>
                                <groupId>test.Vehicle</groupId>
                                <artifactId>test-location</artifactId>
                            </overlay>
                        </overlays>
                        <attachClasses>true</attachClasses>
                    </configuration>
                </plugin>


text:
Q: Assignment error cast in C I have the following code:
struct message_t *msg = ( struct message_t* ) malloc ( sizeof( struct message_t ) );
struct server_t *server = ( struct server_t* ) malloc ( sizeof( struct server_t ) );

server = network_connect( argv[ 2 ] );

The function network_connect return a struct server_t. However I contentiously get the error:

warning: assignment makes pointer from integer without a cast [enabled by default].

I don't understand this error... first I didn't allocated memory to my pointer server_t. Well I get the error and try allocate memory and nothing. I review the code network_connect and all is right.

A: My psychic powers tell me that you're missing the function prototype (declaration) for the network_connect function—make sure to include the header file that it's contained in.
In C, the compiler allows implicit declarations: when the compiler sees a new function name it's never seen before (such as network_connect), it assumes that it takes an arbitrary number and types of arguments and that it returns int.  So, due to the implicit function declaration, the compiler thinks you're trying to convert from an int to a struct server_t*, which results in the given warning.
You also have a memory leak in your code—you're allocating memory for the server object with malloc, and then you immediately overwrite that pointer with the value returned by network_connect, so that memory you allocated is gone forever.  There's no need to allocate any memory in this case, since network_connect directly returns its value.
Finally, in C, there's no need to cast the return value of malloc.  malloc returns a void*, and C (but not C++) allows an implicit cast from void* to any other pointer type.  A cast here is just unnecessary extra verbosity, and it can actually hide errors—if you forget to include <stdlib.h>, then any use of malloc will use an implicit declaration (see above) that returns int.  A cast will hide the error (that you forgot to include <stdlib.h>), whereas having no cast will give you a warning.

A: Going by your description of the network_connect declaration, and the error message, I would say that network_connect looks something like
struct server_t network_connec(char *);

The above declaration says that the function returns the structure as is, i.e. it returns a copy. But you declare the variable server to be a pointer, and you can't assign a non-pointer value to a pointer. The solution is to not make the server variable a pointer (because that allocation will introduce a memory leak) and just declare it as a normal non-pointer variable:
struct server_t server;


text:
Q: Possible to consume a WCF service in Silverlight via a channel factory, using a Portable Class Library? The Current Setup: Silverlight client consuming regular WCF services using RIA classes and generated service references.
The Goal: Replace the service references and RIA classes with channel factories and a Portable Class Library (PCL).  (XY goal: get rid of generated code.)
The Approach So Far:
The first part of this -- using channel factories -- is straightforward, and well documented.  Basically, the WCF service remains as-is, with the caveat that the ServiceContract has to be defined on an interface.  Then on the client you create a ChannelFactory<IMyService>, supply the service URL, and the proxy is created like magic (no need for a service reference).
There is a wrinkle with Silverlight, namely that you have to use conditional compilation to define asynchronous operation contracts.  (This will be important in a moment when I try to move the operation contract to the PCL.)  Thus the service contract will look something like this:
[ServiceContract]
public interface IMyService
{
#if SILVERLIGHT
    [OperationContract(AsyncPattern = true)]
    IAsyncResult BeginGetAString(AsyncCallback callback, object state);
    string EndGetAString(IAsyncResult result);
#else
    [OperationContract]
    string GetAString();
#endif
}

Note that it is (apparently) necessary to exclude the synchronous operation from the Silverlight compilation, as above.  Otherwise, the call to ChannelFactory.CreateChannel complains:

The contract 'IMyService' contains synchronous operations, which are not supported in Silverlight. Split the operations into "Begin" and "End" parts and set the AsyncPattern property on the OperationContractAttribute to 'true'. Note that you do not have to make the same change on the server.

So far so good.  The next step is to move code that is shared between client and server, from RIA .shared class files to a PCL.  For the DataContract classes, this works perfectly well -- but trying to move the OperationContract class presents a problem.  The Silverlight ChannelFactory approach requires the conditional compilation of the synchronous method definition, as above, which (as is my understanding) is not possible in a PCL.
The Question:
What is the most straightforward way (if any) to get this to work, short of abandoning the channel factory approach or maintaining an RIA project?  For example, is there any way to tell Silverlight to simply ignore synchronous operations, rather than throwing an error?  Or any way to somehow exclude the synchronous definition for the Silverlight-targeted PCL (eg, a conditional build maybe)?


text:
Q: Zorin OS 6.3 installation hangs on "Preparing to Install" I'm looking for help on installing Zorin OS 6.3 32bit. The program gets stuck on the "preparing to install" phase.

original URL: http://imgur.com/PulGPMD
I've tried loading it in both "Live System", and "Graphics Safe Mode". Both get stuck at the same screen. Alternatively, I've tried the "Load the Installer Directly", right after startup, but I only receive an error. It's being run side by side a no longer working version of Windows 7 x32bit. When I try to boot from my hard drive "Drive Read Error Press Ctrl+alt+delete to re-reload" appears. Not sure if that's relevant, but figured it might be.

A: This issue reported on the ZorinOS website sounds like your issue, titled: Installation Hangs After Boot Menu.
The workaround reported in that post was to do the following:

When you get to the boot menu in the live DVD, press the
  Tab Key and then a command line will appear.

The type the following, and then press Enter.
nomodeset


text:
Q: Cheerio returns empty string while scraping target.com I am trying to scrape a product page of target.com to retrieve the product title, price and image using cheerio. Using the code below I was able to retrieve the title and image, but the price always returns an empty string. I am new to scraping and I have run out of my wits. Any help is appreciated.
Thank you!

const axios = require('axios')
const cheerio = require('cheerio');
const { html } = require('cheerio/lib/api/manipulation');
const express = require('express')
const { get } = require('http')

async function getTargetProductDetails(prodUrl) {
    try {
        const scrapeUrl = prodUrl

        const { data } = await axios({
            method: "GET",
            url: scrapeUrl,
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36",
            },
        })
        const $ = cheerio.load(data)
        const prodTitleElemSelector = '#pageBodyContainer > div:nth-child(2) > div.h-padding-h-default > h1 > span'

        const prodPriceElemSelector = '#pageBodyContainer > div:nth-child(2) > div.styles__StyledRow-sc-1nuqtm0-0.znNOo > div.styles__StyledCol-sc-ct8kx6-0.CBMCR.styles__StyledSecondCol-sc-y0ahq4-2.jftnqo.h-padding-h-default > div > div.h-margin-b-x2 > div:nth-child(1) > span'
        const imgElemSelector = '#pageBodyContainer > div:nth-child(2) > div.styles__StyledRow-sc-1nuqtm0-0.znNOo > div.styles__StyledCol-sc-ct8kx6-0.cQDVpz.styles__StyledFirstCol-sc-2vujr8-3.hHPFGX.h-padding-h-default > div:nth-child(1) > section > div.styles__CarouselProductFilmstripWrapper-sc-cwwbs3-2.fMvUGZ > div.styles__NicolletFilmstripDiv-sc-1ldzhqm-0.ctFgTt.BaseCarousel-sc-pnaqvl-0.loHErH > div > button:nth-child(1) > div > div > div > div'

        console.log($(prodTitleElemSelector).text().trim())
        console.log($(imgElemSelector).find('img').attr('src'))
        console.log($(prodPriceElemSelector).text())

    } catch (err) {
        console.error(err)
    }

}

getTargetProductDetails('https://www.target.com/p/nintendo-switch-lite/-/A-83031385?preselect=77419248#lnk=sametab')

A: The data was actually being fetched via few APIs. Inspecting the page source revealed the json objects. Extracting the json data was all I had to do to get what I wanted.
Here is the exact solution !


text:
Q: Timed sound effect happening twice via Handler My activity plays a specific sound effect once every second.
The following code works, however there is a bug: occasionally the sound is played TWICE every second. This only happens every once in a while (once every 10-20 attempts). When it happens, the double sound occurs for the entire run of the activity, start to finish. So, if I see the activity started without the bug, it stays that way for the entire run of the activity.
Here's the relevant code - what's the problem with it? Thank you!
    private Handler mHandler = new Handler();

    @Override
protected void onResume() {
    super.onResume();
    mHandler.removeCallbacks(mUpdateTimeTask);
    mHandler.post(mUpdateTimeTask);
}

@Override
protected void onPause() {
    // Another activity is taking focus (this activity is about to be "paused").
    mHandler.removeCallbacks(mUpdateTimeTask);
    super.onPause();
}

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        PlayTick();
        mHandler.removeCallbacks(this);
        mHandler.postDelayed(this, 1000);
    }
};

    public void PlayTick() {
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
soundPool.play(soundID, volume, volume, 1, 0, 1f);
    }

A: Found a solution - seems it's a known SoundPool bug, it sometimes plays the effect twice. I used a .wav file; converting the file to .ogg seems to resolve the issue.