text:
Q: Elasticsearch more like this returns too many documents I have documents like this:
{
title:'...',
body: '...'
}

I want to get documents which are more than 90% similar to the with a specific document. I have used this query:
query = {
    "query": {
        "more_like_this" : {
            "fields" : ["title", "body"],
            "like" : "body of another document",
            "min_term_freq" : 1,
            "max_query_terms" : 12
        }
    }
}

How to change this query to check for 90% similarity with specified doc?

A: Take a look at the Query Formation Parameter minimum_should_match

A: You should specify minimun_should_match
minimum_should_match

After the disjunctive query has been formed, this parameter controls
  the number of terms that must match. The syntax is the same as the
  minimum should match. (Defaults to "30%").

It form query using this

The MLT query simply extracts the text from the input document,
  analyzes it, usually using the same analyzer at the field, then
  selects the top K terms with the highest tf-idf to form a disjunctive
  query of these terms

So if you would like to boost you title field you should boost your title field because if the title contains most of the terms present in the term frequency/ Inverse document frequency. the result should be boosted because it has more relevance. You can boost your title field by 1.5.
Refer this document for referenceren on the more_like_this query


text:
Q: Can't get boostrap 3 navbar to show active colour correctly I have implemented a bootstrap3 navbar to a site I'm creating for an assessment task at uni. I used a website to generate a semi-fancy navbar that features colors on mouse-over etc.
I'm trying to set up a script to highlight the active page (on the navbar), but I've  had no luck.
I have tried multiple attempts to setup a script but even using other questions for reference I can't get any to work.
Here is my navbar code (template from the navbar generator):

            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
            Toggle navigation

            </button>
            FACEBOOK LITE

                      Login

                      Register

                      Home

                      My Account

  Account Preferences

  Log Out

Here is my custom css for the navbar (created by the navbar generator)
.navbar-default { background-color: #1658BA}
.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>li>a:hover, .navbar-default .navbar-nav>li>a:focus { background-color: #3D7EFF}
.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a, .navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a, .navbar-default .navbar-nav>.open>a:hover, .navbar-default .navbar-nav>.open>a:focus { background-color: #3D7EFF}
.dropdown-menu { background-color: #D1E0FF}
.dropdown-menu>li>a:hover, .dropdown-menu>li>a:focus { background-color: #3D7EFF}
.navbar-default { background-image: none; }
.dropdown-menu>li>a:hover, .dropdown-menu>li>a:focus { background-image: none; }
.navbar-default { border-color: #080808}
.navbar-default .navbar-brand { color: #FFFFFF}
.navbar-default .navbar-brand:hover { color: #FFFFFF}
.navbar-default .navbar-nav>li>a { color: #FFFFFF}
.navbar-default .navbar-nav>li>a:hover, .navbar-default .navbar-nav>li>a:focus { color: #FFFFFF}
.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.open>a, .navbar-default .navbar-nav>.open>a:hover, .navbar-default .navbar-nav>.open>a:focus { color: #FFFFFF}
.navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus { color: #FFFFFF}
.dropdown-menu>li>a { color: #333333}
.dropdown-menu>li>a:hover, .dropdown-menu>li>a:focus { color: #FFFFFF}
.navbar-default .navbar-nav>.dropdown>a .caret { border-top-color: #999999}
.navbar-default .navbar-nav>.dropdown>a:hover .caret { border-top-color: #FFFFFF}
.navbar-default .navbar-nav>.dropdown>a .caret { border-bottom-color: #999999}
.navbar-default .navbar-nav>.dropdown>a:hover .caret { border-bottom-color: #FFFFFF}

And finally this is my head (bootstrap and jquery files as well as script that looked like it should be working):

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

        <link type="text/css" rel="stylesheet" href="default.css">

As mentioned before I have tried a few different scripts and none seem to work.
All I would like is for the navbar to highlight the current .li (set the class="active") according to the current page I am on.
You can view the website here: http://titan.csit.rmit.edu.au/~s3605062
So you can see how the blue highlight works on mouseover, but it doesnt stay highlighted for the active page which is what I would like.
Any  help is much appreciated,
Thank you!
Ricky

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django form - DELETE and PUT http method I would like to use a middleware or something like that in a Django form in order to have the support of the PUT and the DELETE HTTP method.
My first question is :
What's the best and easy way to do that ?
Google suggests me to use something like that : https://gist.github.com/1161423
Is it really the best way ? Nothing else ?
My second question is : Is it safe ? (csrf for example)


text:
Q: Google Drive SDK, can it do this? StackOverFlowers:
I not if this is possible, so I wanted to ask quickly.
Can I:

*

*Create a Document and Share it with other Google Users (using the Google API's)

*Update that document when needed.. mostly add content to a spreadsheet.

3.. if 1&2 are possible, what libraries do I use for this.. I'm looking at the
Javascript APIs now, and I have used the PHP libraries in the past.
Any guidance is helpful..

A: Yes, both are possible using the Drive SDK. Updating the the file might be tricky, because you have to download it, update it locally then re-upload it, but that is not hard when using something like CSV.
For Javascript, please check out the Google Drive SDK Javascript Quickstart.


text:
Q: My obb file is getting removed from device automatically (android expansion files) I am trying to test my expansion file for my application. I manually place my main.version.pkg.obb file in Android/obb/pkg/ folder in my Galaxy S3 phone. But the device is automatically removing my file everytime. Can someone tell me why is this happening.
I am just copying the file using usb and the moment I remove usb and connect again, the file is getting removed (which shows scanner is removing my obb file).
Thanks for any help

A: Are you using Kit Kat 4.4.2.
If that's the case,then this is due to a bug in kitkat that many people are facing.Google has kept this bug in mind and is working on it.It will be solved with the next kit kat update.


text:
Q: Mouse Events in Flash I have just started an online class on Flash and ActionScript 3.0 and I have been having troubles with mouse events, especially with the CLICK class.
So I'm trying to create a basic division calculator, but I can't seem to understand my error with the button. So this is the code that is not working :
public function U1A4_DivEtMod() {
    btnSoumettre.addEventListener(MouseEvent.CLICK, divise);
}

private function divise(event:MouseEvent):void {
    monFormat.font = "Arial";
    monFormat.size = 20;
    monFormat.bold = true;
    monFormat.color = 0xFFFFFF;

    monMessage.x = 50;
    monMessage.y = 300;

    monMessage.autoSize = TextFieldAutoSize.LEFT;
    monMessage.border = true;
    monMessage.defaultTextFormat = monFormat;

    var nmb1:int;
    var nmb2:int;
    var repDiv1:int;
    var repDiv2:int;
    var repMod1:int;
    var repMod2:int;
    var nouvMessage:String;

    nmb1=int(entier1.text);
    nmb2=int(entier2.text);
    repDiv1 = nmb1 / nmb2;
    repDiv2 = nmb2 / nmb1;
    repMod1 = nmb1 % nmb2;
    repMod2 = nmb2 % nmb1;

    nouvMessage = (
        nmb1 + " / " + nmb2 + " = " + repDiv1 + "\n" +
        nmb2 + " / " + nmb1 + " = " + repDiv2 + "\n" +
        nmb1 + " % " + nmb2 + " = " + repMod1 + "\n" +
        nmb2 + " % " + nmb1 + " = " + repMod2 );

    monMessage.text = nouvMessage;
    addChild(monMessage);
}

I noticed that my code works when I replace btnSoumettre by this but I can click wherever I want on the application. I'm trying to make the method only work when the user clicks the button itself.
This is the error Flash is giving me:

1061: Appel à la méthode addEventListener peut-être non définie, via la référence de type static Class.

So my version is in French so you guys might not understand but it basically says that the method addEventListener is not defined with a static class reference.
Thanks a lot for your help!


text:
Q: How to calculate kriging weights? In Esri's documentation on how to make a prediction in Kriging, I couldn't figure out the linkage between the semivariograms and the prediction process from reading the description therein:

After you have uncovered the dependence or autocorrelation in your
  data (see Variography section above) ... you can make a prediction
  using the fitted model. Thereafter, the empirical semivariogram is set
  aside.
You can now use the data to make predictions. Like IDW interpolation,
  kriging forms weights from surrounding measured values to predict
  unmeasured locations...

Still, that doesn't say much about how kriging forms weights.
Is it true that we're just using a different set of weight values than the 1/distance in IDW?
If Kriging really just uses a different weight values than IDW, how can it solve the well-know summit problem for IDW? (whereby IDW cannot predict a higher value outside the range of the control points. e.g. One cannot correctly predict the elevation of a peak in a terrain based on lower elevation values of nearby data points.)
I understand the semivariogram measures average dissimilarity for a given separation distance, and the values are all non-negative.
Can someone explain how the combination/weighting method (e.g. with linear regression or any other variant) on a computed semivariogram works to solve the "summit" problem?

A:
Is it true that we're just using a different set of weight values than the 1/distance in IDW?

Yes, both IDW interpolation and Ordinary Kriging (OK) will calculate weights based on distance, but with different criteria. In both methods, weights do not depend on sample values. The answer from Dahn Jahn in Ordinary kriging example step by step? is very clarifying about this.
The main difference is that in Ordinary Kriging distances are used to measure the correlation structure among sample points (i.e. how similar they are based on lags of distances) and this correlation structure is captured in the form of the variogram model. The variogram model is used to calculate covariances (or semi variances): i) among sample points and; ii) between sample points and prediction points. These covariances are then, used to calculate weights (see how below).

How does Ordinary Kriging form weights?

The main processing steps in Ordinary Kriging are:

*

*Calculate experimental variogram.

*Fit theoretical variogram model.

*Calculate weights (using the Lagrange multiplier method).

*Predict (and estimate kriging variance).

Background:
For a detailed mathematical explanation and theoretical insights about Ordinary Kriging refer to materials linked in 'References'.
Assume from bullet number 2 our variogram model is of type exponential:
C(h) = a + (σ² - a), if |h| = 0
C(h) = (σ² - a)exp(-3|h|/r), if |h| > 0

where: C(h) = covariance; a = nugget effect; σ² = sill (σ² - a = partial sill); r = range.

We want to predict a value so that Ŷ0 = wiyi where Ŷ0 is the predicted value at location 0, wi is the weight from sample i and yi is the observed value from sample i.
The idea of kriging is that its estimator Ŷ0 is unbiased (i) and the estimation variance is minimized (ii):

*

*i) E(Ŷ0) = E(Y0). For this to happen, ∑wi = 1 and the mean is stationary (i.e. E(Yi) = u, given any i).

*ii) σ²_ε = E[Y0 - Ŷ0]² = Var(Y0 - Ŷ0) is minimized.

In order to minimize σ²_ε, the Lagrange multiplier method is used:
L = Var(Y0 - Ŷ0) + 2λ(∑wi - 1)
  = σ² + ∑∑wiwjCij - 2∑wiCi0 + 2λ(∑wi - 1)

where L is the Lagrange function, λ is the Lagrange multiplier and 2λ(∑wi - 1) is the part that guarantees ∑wi = 1. Cij is the covariance among sample points i and j and Ci0 is the covariance between sample point i and prediction point.
Now, taking partial derivatives from L with respect to wi and λ, setting the equations to zero, and solving them, will result in (skipped all calculations through the last step):
[w1]    [C11 ... C1n 1]-1  [C10]
|. |    |.       .   .|    |.  |
|. | =  |.       .   .|    |.  |
|. |    |.       .   .|    |.  |
|wn|    |Cn1 ... Cnn 1|    |Cn0|
[λ ]    [1   ... 1   0]    [1  ]

Example:
Assume the following sample points (1, 2 and 3) and the prediction point (0), their respective values and distances:
point | x_coordinate y_coordinate | value | dist_to_1 dist_to_2 dist_to_3 dist_to_0
1     | 0            0            | 10    | 0         2         3.16      1.41
2     | 0            2            | 7     | 2         0         3.16      1.41
3     | 3            1            | 3     | 3.16      3.16      0         2
0     | 1            1            | ???   | 1.41      1.41      2         0

Assume the covariance function with nugget a = 1, sill σ² = 4 and range r = 6:
C(h) = σ² = 4, if |h| = 0
C(h) = (σ² - a)exp(-3|h|/r) = (4 - 1)exp(-3|h|/6), if |h| > 0

Calculate covariances among sample points:
[C11 C12 C13]   [4    1.1  0.62]
|C21 C22 C23| = |1.1  4    0.62|
[C31 C32 C33]   [0.62 0.62 4   ]

Calculate covariances between sample points and prediction point:
[C10]   [1.48]
|C20| = |1.48|
[C30]   [1.1 ]

Calculate weights:
[w1]    [4    1.1  0.62 1]-1  [1.48]   [ 0.353]
|w2| =  |1.1  4    0.62 1|    |1.48| = | 0.353|
|w3|    |0.62 0.62 4    1|    |1.1 |   | 0.293|
[λ ]    [1    1    1    0]    [1   ]   [-0.505]

So, w1 = 0.353, w2 = 0.353, w3 = 0.293 and the Lagrange multiplier = -0.505. See that ∑wi = 0.353 + 0.353 + 0.293 = 1.
Predict value in point 0 (Ŷ0):
Ŷ0 = 0.353*10 + 0.353*7 + 0.293*3 = 6.88

Calculate kriging variance (aka minimized estimation variance):
σ²_ε = sill - [w1 w2 w3 λ] [C10]
                           |C20|
                           |C30|
                           [1  ]

σ²_ε = 3.14

Same example, in R:
library(gstat)
library(sp)

p = SpatialPoints(cbind(c(0,0,3),c(0,2,1)))
p$z = c(10,7,3)
krige(z~1, p, SpatialPoints(cbind(1,1)), vgm(psill=3, nugget=1, range=2, "Exp"))
# psill = partial sill.
# the vgm function takes the 'range' argument equal to
#C(h) = (σ² - a)*exp(-|h|/r) (or S(h) = a + (σ² - a)*(1-exp(-[h]/r)
#that is why range = 2 (and not equal 6 as in the previous example)
# which means approximate 1/3 of the distance where the curve flattens.

[using ordinary kriging]
  coordinates  var1.pred  var1.var
1      (1, 1)  6.887426   3.136307

How can Ordinary Kriging solve the well-know summit problem for IDW? (whereby IDW cannot predict a higher value outside the range of the control points).

Besides Kazuhito's answer, this is also addressed in Edzer Pebesma's answer to Kriging values greater than the most extreme value of the input layer?.

References:

*

*Bailey and Gatrell. Ordinary Kriging, Ch. 5.5. Michigan State University. pdf.

*Rossiter, D.G. Introduction to Spatial Statistics, ITC. Ordinary Kriging explained. xls.

A: Maybe I should begin by stating that "the summit issue is reflecting how IDW models the surface, rather than weighting". IDW sees the predicted surface as an averaging model, while Spline tries to minimize abrupt change to make 'smooth rubber sheet' and Kriging tries to minimize errors. (I hope this makes my point clear).
Let me focus on the difference between surfaces predicted by IDW and Kriging, especially how they are related to measured data.

Above (my poor drawing) is trying to picture that:

*

*IDW (blue line) estimates the values as averages of measured samples, and its surface will not pass through sample points. Its smoothness is controlled by power value, but even bumpy - high power settings cannot make it above the maximum or below the minimum (so, yes, summit problem). Because power is merely working as relative influence of each sample point.

*Kriging, like Spline, can account general trends and estimate beyond range of sample data. On the above example, though not obvious, measured height has a mild increase toward left-hand side... where Kriging (red line) surface goes higher than the sample points. The surface pass through sampling points if the variance (or s.d.) is zero, but not necessary.

I did not answer the weighting aspect of the question, the subject we cannot go without mathematics... and I am really bad at it.


text:
Q: Yii clickable td I currently have a table with data retrieve from DB, and I wish the td are clickable to redirect to another page. So far I found a example bellow:
<td onClick="document.location.href='http://www.yoursite.com';"> some text here </td>

I still not sure this work or not, because im using Yii Chtml::tag to create table.
So my question is where to put the onClick function into Yii td ?
echo CHtml::tag('td', array('class'=>"td"),"-");

Or any other suggestion so I can click on the td to another page? Thanks

A: how about trying this if your td has a class "td"
$('td.td').click(function(){
     //your redirect here
});


text:
Q: Qt display double number without exponential format Let's say that I have a double number: 1679616. When I try to set text to label, the number is shown as 1.67962e+06. Is there a way so that the number can be shown as it is without exponential format?
If I use: QString::number(result, 'f', 2) to cast the number to string, everything is OK, but what if the number has more than two digits after that point? I know that I can set it to be 10 for example, but you know that this is not the right thing that I want to do. I want if the number is 82348.12323 to be shown as it is. If it is 234.2, I want just one number after the point.

A: The following examples work pretty well for me:
double a1 = 82348.12323;
double a2 = 234.2;

QString s1 = QString::number(a1, 'g', 10);
QString s2 = QString::number(a2, 'g', 10);

qDebug() << "s1:" << s1;
qDebug() << "s2:" << s2;

Output:
s1: "82348.12323"
s2: "234.2"

More information on the format argument can be found here.

A: I had a similar problem using int64. I solved it by using a conversion to std::string thusly:
std::string tsSS2 = std::to_string(tStamp);

which converted an int64 (tStamp) to a std::string and then when I issued:
qDebug << tsSS2;

It printed the number without scientific notation (SN). Curiously it printed it with a decimal point and trailing zeros. Still, no SN.
Sean


text:
Q: Questions regarding bound variables $$x\in(\cap F)\cap(\cap G)=[\forall A\in F(x\in A)]\land[\forall A\in G(x\in A)]$$
Since the variable $A$ is bounded by universal quantifier, it is regarded as bounded variable, according to the rules, the variable is free to change to other letters while the meaning statement remains unchanged. But,the above statements mention two different families of sets, $F$ and $G$, why is it correct to state the sets of $F$ and $G$ by using the same letter $A$, for the first $A$ in the first part of the conjunction stands for sets in $F$ while the latter stands for sets in $G$? Isn't different letters should be used to refer those sets($A$ for $F$ while $B$ for $G$)? I am extremely confused with the usage of bound variables. Please explain, thanks!

A: The reason for this is that when you take the conjunction of two statements, its truth depends on the truth of each of the two components, and you don't look any further than that.
For example, the statements
$$\forall x \geq 5 \quad 2x \geq 10$$
and
$$\forall x \leq - 3 \quad x^2 \geq 9$$
are both true, taken separately. Therefore the conjunction
$$(\forall x \geq 5 \quad 2x \geq 10) \wedge (\forall x \leq - 3 \quad x^2 \geq 9)$$
must be true, regardless of the fact that $x$ represents different possible numbers in each of the two statements.
Edit: Nonetheless, it is true that $x$ is taken as belonging to some overarching "universe" of all objects. In my example, this is the set of all real numbers, and in your example, $A$ belongs to the universe of all sets, regardless of whether they belong to $F$ or $G$ or not. A statement such as
$$ \forall A \in F \quad x \in A$$
really means
$$\forall A \quad A \in F \Longrightarrow x \in A,$$
where the part "$\forall A$" means "for all sets $A$." Analyzed this way, you see that really $A$ represents the same type of object, namely a set.

A: In a quantified expression like $\forall x A(x)$ the occurrences of the variable $x$ into the formuala $A(x)$ are bounded by the quantifier (i.e. $\forall x$) becuase they occur into the scope of the quantifier.
So, in the example :

$\forall x (A(x) \land B(x))$

both the occurence of $x$ in $A$ and the occurrence of $x$ in $B$ are bound.
In the expression :

$\forall x A(x) \land B(x)$

I have renoved the parentheses, so "restricting" the scope of the quantifier: now the $x$ in $A(x)$ is bound, but the $x$ in $B(x)$ is free.
When you consder the formula :

$\forall x A(x) \land \forall x B(x)$

two different quantifiers act one on $A(x)$ and one on $B(x)$; so, both occurences of $x$ are bound, but the fact that the two quantifiers use both $x$ is immaterial. The "effect" of the quantifier "vanish" outside its scope.
The last formula is equivalent to :

$\forall x A(x) \land \forall y B(y)$

because the variable in the quantifier preceding $A(x)$ is not "linked" to the variable in the quantifier preceding $B(x)$.

A: The answer to your specific question is that $A$ occurs as a bound variable in two different expressions.  When a variable is bound, it has no meaning outside the expression it is in, so you can use it again as a variable in another expression, and that is what is done here. (But if I were writing a book or paper about logic aimed at beginners, I would use a different letter for the two bound variable anyway.)


text:
Q: Option value auto run javascript on page load So when I load the page, Week 1 is automatically the chosen option which is good, but the javascript doesn't run until I manually select an option. I would like the javascript to automatically load on week 1 but I'm not sure how to do it.

            <form name = "form_schedule" action = "">
                <select id = "s1" name = "s1" onchange = "schedule('this.form')">
                    <option value = "Week 1" selected> Week 1 </option>
                    <option value = "Week 2"> Week 2 </option>
                    <option value = "Week 3"> Week 3 </option>
                    <option value = "Week 4"> Week 4 </option>
                    <option value = "All Weeks"> All Weeks </option>
                </select>
            </form>

 Schedule

                             Home
                             Result
                             Away

A: You could add a onload function:

Just put it before the closing body tag.


text:
Q: React native: Failed to call into JavaScript module method AppRegistry.runApplication() Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
        A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

I tried the same code in other react-native project but the value is same.

A: there might be a problem in the code like invalid fetching (In my case, wrong use of firebase query to get data). There might be wrong fetching of packages etc ( as mentioned in the official react-native git issues ). Try to check there


text:
Q: Prevent duplicate record insertion on page refresh I search A lot.. but failed to implement.
here is my code, how i prevent duplicate insertion on page refresh,, (how i use viewstate, or any other method.... resposnse.redirect is not a solution in this scenario).
protected void btn_save_click(object sender, EventArgs e)
    {
            System.Data.DataTable dt_plotid = new System.Data.DataTable();
            dt_plotid = FghBAL.Admitting.GetMax_ByPlotID(txt_plot.Text);
            string plotid = dt_plotid.Rows[0]["ID"].ToString();
            if (FghBAL.Alotee.InserAllotee(txt_alotee_name.Text.ToUpper(), ddl_alotee_sw.SelectedValue.ToUpper(), txt_alotee_fname.Text.ToUpper(), alotee_cnic, txt_alotee_phone.Text, txt_alotee_cellno.Text, txt_alotee_address.Text, txt_alotee_email.Text, plotid))
            {
                lbl_error_3.Visible = true;
                lbl_error_3.Text = "Add Successfully";
                txt_alotee_name.Enabled = false;
                ddl_alotee_sw.Enabled = false;
                txt_alotee_fname.Enabled = false;
                txt_alotee_cnic_1.Enabled = false;
                txt_alotee_cnic_2.Enabled = false;
                txt_alotee_cnic_3.Enabled = false;
                txt_alotee_phone.Enabled = false;
                txt_alotee_cellno.Enabled = false;
                txt_alotee_address.Enabled = false;
                txt_alotee_email.Enabled = false;
                System.Data.DataTable dt_alotee_data = new System.Data.DataTable();
                dt_alotee_data = FghBAL.Alotee.GetDatabyPlot_Id(plotid);
                grid_alotee.DataSource = dt_alotee_data;
                grid_alotee.DataBind();
                grid_alotee.Visible = true;
                btn_save_alotee.Visible = true;

                btn_link_another_alotee.Visible = true;
                lbl_grd_alotee.Visible = true;
                tabcontent3.Style.Add("height", "80%");
                //ViewState["dt_alotee_view"] = dt_alotee_data;
                btn_save_alotee.Enabled = false;
               // Response.Redirect(Request.Url.AbsoluteUri);
            }
            else
            {
                lbl_error_3.Text = "Unable to add Allottee Information";
            }
        }

A: Your question seems to indicate that a button event handler is triggered on a page refresh - which is odd. A page refresh results in a GET action. Changes to server side data should only be done in POST requests though. And button event handlers should only be called when a button is clicked. I can't tell from this code in what way your architecture is violating these stipulations.

A: You can use view state or session to store the flag when the page first loads and then change the flag value to true when you have inserted in the database get the full code from here :
http://dotnetready4u.blogspot.com/2015/01/avoid-repaeted-insertion-on-page-refresh.html


text:
Q: Missing return type in uml class I have to write the java code corresponding the following class diagram:

what about missing informations about visibility and return type of methods? Is the visibility understood as 'package'? Is the return type understood as 'void'?

A: On p. 53 of UML 2.5 (section 7.8.12 PackageableElement):

A PackageableElement must have a visibility specified if it is owned by a Namespace. The default visibility is public.

On p. 116 of UML 2.5 (section 9.6 Operations):

<return-type> is the type of the return result Parameter if the Operation has one defined.

So in Cxx-terms that would be void.


text:
Q: Spring Hibernate SessionUtils connection.close Question regarding following code
SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection()

Does connection checked out from above line of code required to be closed upon method finished work?

A: The real answer depends on how you're using it. The intent is that this can be called multiple times within a transaction, and if you're using it this way then you definitely would not want to close it.


text:
Q: Magento 2: setup upgrade error "We can't find the role for the user you wanted" I got strange error while running command "php bin/magento setup:upgrade".
Error:
We can't find the role for the user you wanted...
Unable to complete my all command process.
Please help.

A: Solution:
Please go to file:
vendor/magento/module-authorization/Model/Acl/AclRetriever.php at line# 85 and edit below code into edit one:
Original Code:
        if (!$role) {
            throw new AuthorizationException(
                __('We can\'t find the role for the user you wanted.')
            );
        }
        $allowedResources = $this->getAllowedResourcesByRole($role->getId());

Edit Code:
        if (!$role) {
            $allowedResources = array();
        }

Now, please run setup:upgrade and rest commands.
Important:
Once success, please revert back the file.
Thanks,

A: in my case it was caused by Shopial_Facebook (which I do not need). I ran
php bin/magento module:disable Shopial_Facebook

cleared cache and the error was gone. I hope it helps.


text:
Q: Jooq Postgres JSON query What support is there for querying into postgres json objects with JOOQ?
For example,
SELECT id, data->'author'->>'first_name' as author_first_name FROM books;

A: Many standard SQL/JSON operators like JSON_ARRAY(), JSON_OBJECT(), JSON_ARRAYAGG() and a few more are supported starting from jOOQ 3.14.
Currently (as of jOOQ 3.15), support for these vendor specific JSON operators is still not implemented: https://github.com/jOOQ/jOOQ/issues/10018
However, you can always resort to using plain SQL. Your query can be expressed as such with jOOQ:
DSL.using(configuration)
   .select(BOOKS.ID, field("{0}->'author'->>'first_name'",
                       String.class, BOOKS.DATA
                     ).as("author_first_name"))
   .from(BOOKS)
   .fetch();

For details, see the DSL.field() methods javadocs.
Or, write your own mini API
If you're using a lot of these JSON path notations, you might be able to factor out a mini API as such:
public static Field<Object> jsonObject(Field<?> field, String name) {
    return DSL.field("{0}->{1}", Object.class, field, DSL.inline(name));
}

public static Field<String> jsonText(Field<?> field, String name) {
    return DSL.field("{0}->>{1}", String.class, field, DSL.inline(name));
}

The above could then be used as such:
DSL.using(configuration)
   .select(BOOKS.ID, jsonText(jsonObject(BOOKS.DATA, "author"), "first_name")
                     .as("author_first_name"))
   .from(BOOKS)
   .fetch();


text:
Q: runtimeException in ringdroid on android - how to catch exception Ringdroid is a 3rd party app im using to edit music. My question isn't really about ringdroid.  Ringdroid is crashing on some android devices and i've provided the stack trace below. My question is how can i catch an exception from this third party app when im using startActivity(...) to launch it in android ?
java.lang.RuntimeException: Unable to resume activity {org.jefferyemanuel.waitingtones/com.ringdroid.RingdroidSelectActivity}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2742)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:561)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:64)
at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:133)
at android.database.CursorWrapper.requery(CursorWrapper.java:186)
at android.app.Activity.performRestart(Activity.java:5157)
at android.app.Activity.performResume(Activity.java:5183)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
... 10 more


text:
Q: multiple where clauses I have the following table:
 ID    Key   Value
 1     From  x
 1     To    Y
 1     CC    a
 2     From  Z
 2     To    X
 2     CC    b
 3     From  X
 3     To    Y
 3     CC    c
 4     From  X
 4     To    Z
 4     CC    d

I want Id 1 and 3 as result such that where key =" From " and value = "x " and  where key =" To " and value = "Y " (From->To should be x->y)
It should be something like this
SELECT Id
FROM table_name
WHERE REGEXP_LIKE(KEY, '(^|\s)from(\s|$)', 'i')
    AND REGEXP_LIKE(value, '(^|\s)x(\s|$)', 'i')
    AND
WHERE
WHERE REGEXP_LIKE(KEY, '(^|\s)to(\s|$)', 'i')
    AND REGEXP_LIKE(value, '(^|\s)y(\s|$)', 'i')

Is it possible to  solve this problem?

A: Using conditional SUM
SqlFiddleDemo
SELECT ID
FROM Table1
GROUP BY ID
HAVING
      SUM(CASE WHEN "Key" = 'From' and LOWER("Value") = 'x' THEN 1 ELSE 0 END) = 1
 AND  SUM(CASE WHEN "Key" = 'To' and LOWER("Value") = 'y' THEN 1 ELSE 0 END) = 1

OUTPUT
| ID |
|----|
|  1 |
|  3 |

A: Join the table to itself and filter accordingly.
    SELECT ID
    FROM
            Table t1
            INNER JOIN Table t2
            ON t1.ID = t2.ID
    WHERE
            t1.Key = 'From' AND
            t1.Value = 'x' AND
            t2.Key = 'To' AND
            t2.Value = 'y'


text:
Q: How to validate dynamic fields (field created on the fly) I'm using FormValidation plugin and I have this code:
data.entities.forEach(function (value, index, array) {
    html += '
';
    html += '<input type="checkbox" name="norm[]" id="' + value.id + '" value="' + value.id + '">	';
    html += '' + value.code + '	';
    html += '' + value.name + '	';
    html += '' + value.ct + '	';
    html += '
';
});

$("#resultadoNormaBody").html(html);

As you can see the input type="checkbox" elements are created on the fly, I need to perform a validation on this new fields, how? I'm thinking to use this piece of code as start point but don't know if it will works since fields are dynamically created.
$('#normasForm').formValidation({
    framework: 'bootstrap',
    err: {
        container: 'tooltip'
    },
    row: {
        selector: 'td'
    },
    icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        'norm[]': {
            validators: {
                notEmpty: {
                    message: 'Please choose one at least'
                }
            }
        }
    }
});

Any advice?
Executing test based on answer
After read the docs for Adding dynamic field I comes with a second doubt. This is the original code:
$('#btnBuscarNorma').on('click', function (e) {
    e.preventDefault();

    $.post(Routing.generate('filterNorm'), $('#normSearch').serialize(), 'json').done(function (data, textStatus, jqXHR) {

        if (data.entities.length > 0) {
            var html = '';
            data.entities.forEach(function (value, index, array) {
                html += '
';
                html += '<input type="checkbox" name="norm[]" id="' + value.id + '" value="' + value.id + '">	';
                html += '' + value.code + '	';
                html += '' + value.name + '	';
                html += '' + value.ct + '	';
                html += '
';
            });

            $("#resultadoNormaBody").html(html);
        }
    });
});

All right? Since adding dynamic fields include this piece of code,
.on('click', '.removeButton', function() {
    var $row    = $(this).parents('.form-group'),
        $option = $row.find('[name="option[]"]');

    // Remove element containing the option
    $row.remove();

    // Remove field
    $('#surveyForm').formValidation('removeField', $option);
})

Should I get ride of my code and put it inside the .on() on the validator itself? I'm a bit confused and don't know what to do. This is what I mean in a few words:
.on('click', '#btnBuscarNorma', function() {
    $.post(Routing.generate('filterNorm'), $('#normSearch').serialize(), 'json').done(function (data, textStatus, jqXHR) {

        if (data.entities.length > 0) {
            var html = '';
            data.entities.forEach(function (value, index, array) {
                html += '
';
                html += '<input type="checkbox" name="norm[]" id="' + value.id + '" value="' + value.id + '">	';
                html += '' + value.code + '	';
                html += '' + value.name + '	';
                html += '' + value.ct + '	';
                html += '
';
            });

            $("#resultadoNormaBody").html(html);
        }
    });
})

Of course I need to add the field dynamic to the validator but it will be right on this way?

A: You can use AddField method like this:
$('#formID').formValidation('addField', $element);

$element means your new element for validation, in this case your <input>.
Check this doc: http://formvalidation.io/examples/adding-dynamic-field/
Update#1
The key to solve your problem is to get the object collection which you just dynamic added.
So:
.on('click', '#btnBuscarNorma', function() {
    $.post(Routing.generate('filterNorm'), $('#normSearch').serialize(), 'json').done(function (data, textStatus, jqXHR) {

        if (data.entities.length > 0) {
            var html = '';
            data.entities.forEach(function (value, index, array) {
                html += '
';
                html += '<input type="checkbox" name="norm[]" id="' + value.id + '" value="' + value.id + '">	';
                html += '' + value.code + '	';
                html += '' + value.name + '	';
                html += '' + value.ct + '	';
                html += '
';
            });

            $("#resultadoNormaBody").html(html);

            //get objects
            var inputs =  $("#resultadoNormaBody").find("input[name='norm[]']");
            //assume your form id is surverForm
            $('#surveyForm').formValidation('addField', inputs);
        }
    });
})

The jquery selector input means the <input> element, and [attr='val'] means the element which has attr attribute with value of val.
Here's a sample:http://jsfiddle.net/994hL0q7/


text:
Q: UIButton is taking 3 taps before working? Swift I have a button as seen in the image and when the user presses it first it should change the image and the user is now following this profile. However when the user presses the button first it does nothing and on the second tap it works. How can I make this work on the first tap?
Edit cleaned up code This code takes two taps for the button to work. With a double tap it follows or unfollows the user and updates the image. But like i said it takes two taps.
 @IBAction func favButton(sender: UIButton) {

    buttonPressed = !buttonPressed

            if buttonPressed == true {

                let followedObjectId = userToShowDetail?["name"] as? String

                if isFollowing[followedObjectId!] == true {

                }

            } else  {

                let followedObjectId = userToShowDetail?["name"] as? String

                if isFollowing[followedObjectId!] == false {

                    isFollowing[followedObjectId!] = true
                    sender.setImage(UIImage(named: "fave_on@2x.png"), forState: UIControlState.Normal)

                    print("follow")

                    let following = PFObject(className: "Followers")
                    following["following"] = userToShowDetail?["name"] as? String
                    following["follower"] = PFUser.currentUser()?.objectId
                    favLabel.text = "Favourite Jammer"

                    following.saveInBackground()

                } else {

                    if buttonPressed != true {

                        isFollowing[followedObjectId!] = false
                        print("notFollow")
                        sender.setImage(UIImage(named: "fave_off@2x.png"), forState: UIControlState.Normal)
                        favLabel.text = "Add to favourites?"

                    }

                }
            }

This code fixed it visually, but it no longer works behind the scenes. The button changes image and prints follow and unfollow to the logs but it doesn't unfollow a user and also adds the followed user to my data twice.
        buttonPressed = !buttonPressed

    if buttonPressed == true {

        let followedObjectId = userToShowDetail?["name"] as? String

        isFollowing[followedObjectId!] = true

        sender.setImage(UIImage(named: "fave_on@2x.png"), forState: UIControlState.Normal)
        print("follow")

        let following = PFObject(className: "Followers")
        following["following"] = userToShowDetail?["name"] as? String
        following["follower"] = PFUser.currentUser()?.objectId
        favLabel.text = "Favourite Jammer"

        following.saveInBackground()

    } else {

        if buttonPressed != true {
            let followedObjectId = userToShowDetail?["name"] as? String

            isFollowing[followedObjectId!] = false
            print("notFollow")
            sender.setImage(UIImage(named: "fave_off@2x.png"), forState: UIControlState.Normal)
            favLabel.text = "Add to favourites?"

        } // !=true
    } // else

} // uibutton

A: The code is a very messy and I wouldn't recommend going about it like this... Too many queries are happening and too much in general is going on in that button...
However, any query (data the you want to access and modify in your app) should be in the viewDidLoad (or a similar method) so that the values are there before the button is pressed. These values should be stored in arrays. And when the button is pressed, you will already have access to the values and it'll be easier to modify them in the future and in different methods.
This needs to be shortened.
But, assuming you still want to do it this way the button logic needs to be broken down into functions.
Create a function out of that query and then reference it in the button. Too many things are happening + you're calling the button in the wrong place.
This is a very rough example:
Your button should look something like this:
  @IBAction func favButton(sender: UIButton) {

    buttonPressed = !buttonPressed

    if buttonPressed == true {

        let followedObjectId = userToShowDetail?["name"] as? String

        if isFollowing[followedObjectId!] == true {

            //something needs to happen here?

        }

        updateImage()

    } else  {

      followersUpdate()

    }

   }

      //Your functions below the button:

 func followersUpdate() {

    let followedObjectId = userToShowDetail?["name"] as? String

    if isFollowing[followedObjectId!] == false {

    isFollowing[followedObjectId!] = true
    sender.setImage(UIImage(named: "fave_on@2x.png"), forState: UIControlState.Normal)

    print("follow")

    let following = PFObject(className: "Followers")
    following["following"] = userToShowDetail?["name"] as? String
    following["follower"] = PFUser.currentUser()?.objectId
    favLabel.text = "Favourite Jammer"

    following.saveInBackground()

    } else {

    }

}

func updateImage() {
        if buttonPressed != true {

            isFollowing[followedObjectId!] = false
            print("notFollow")
            sender.setImage(UIImage(named: "fave_off@2x.png"), forState: UIControlState.Normal)
            favLabel.text = "Add to favourites?"

            let query = PFQuery(className: "Followers")

            query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
            query.whereKey("following", equalTo: (userToShowDetail?["name"] as? String)!)

            query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

                if let objects = objects {

                    for object in objects {

                        object.deleteInBackground()

                    }
                }

            })

        }

    }

    //Your viewDidLoad() initial query to parse:

 override func viewDidLoad() {
    super.viewDidLoad()

    let query = PFUser.query()

    query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

        if let users = objects {

            for object in users {

                if let user = object as? PFUser {

                    if user.objectId! != PFUser.currentUser()?.objectId {

                        self.usernames.append(user.username!)
                        self.userids.append(user.objectId!)

                        let query = PFQuery(className: "Followers")

                        query.whereKey("follower", equalTo: (PFUser.currentUser()!.objectId)!)
                        query.whereKey("following", equalTo: user.objectId!)

                        query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

                            if let objects = objects {

                                if objects.count > 0 {

                                    self.isFollowing[user.objectId!] = true

                                } else {

                                    self.isFollowing[user.objectId!] = false

                                }
                            }

                            if self.isFollowing.count == self.usernames.count {

                            }
                        })
                    }
                }

            }
        }
    })
}

As I mentioned, this is a rough example to give you an idea of what you should be doing (even though I think the queries and server sending back and forth is 1) superfluous, 2) not needed and 3) will make your app slower.)
If you break it down like this and have less going on in your button, the image should update. You're going to have to play around with this and revise the code/make it much shorter.
Let me know if you have more questions I'll be happy to help.


text:
Q: "I saw Sue in town yesterday, but she didn't see me." Why is there no article before "town"? From a Raymond Murphy book on English grammar, I saw the following sentence:

I saw Sue in town yesterday, but she didn't see me.

Why is there no article before "town"?
Is the following incorrect? Why?

I saw Sue in a/the town yesterday.

A: In town here uses a special sense of town, which refers to whatever is understood to be the local region. Saying someone is in town is akin to saying they are in the neighborhood or in the area; as the LDOCE has it:

where you live [uncountable]: the town or city where you live:

Cam left town about an hour ago, so he should be out at the farm by now.
     I'll be out of town for about a week.
     Guess who's in town? Jodie's sister!
     Do you know of a good place to eat? I'm from out of town (=from a different town).
    We're moving to another part of town.

*

*To say Cam left town means he departed from the local area, or from wherever area he had been before. To say Cam left his town means he departed from (perhaps abandoned) his hometown. To say Cam left the town means he departed from some particular settlement which is known.

*If you live in town, it means you live in the local urbanized area, as opposed to living in the suburbs or in the country for the outlying areas.

*You can be out of the town but not out of town— that is, you can be physically outside the boundary line of a jurisdiction that is called a town, but you have not left the larger area.

There are other locations— mostly institutions— where dropping the determiner changes the meaning, like being in hospital or out of school; writing from prison or at sea; or going to church or to court.
See for example Which nouns should include an article after "go to [noun]" in AmE and BE? and Is there a reason the British omit the article when they "go to hospital"?.

A: For urban (and quasi-urban) dwellers "in town" means in their residential environs.  Depending on the context, it might mean in the business district.  This is opposed to "out of town," which means traveling away from home.


text:
Q: C# opening a Form out of a TrayIcon i just used this snippet for creating a tray application with two buttons (settings and exit):
using System;
using System.Windows.Forms;
using System.Drawing;
using WindowsFormsApplication1;

//*****************************************************************************
abstract class NotIco
{
private static NotifyIcon notico;

//==========================================================================
public static void Main(string[] astrArg)
{
    ContextMenu cm;
    MenuItem miCurr;

    cm = new ContextMenu();

    miCurr = new MenuItem();
    miCurr.Index = 0;
    miCurr.Text = "&Settings";
    miCurr.Click += new System.EventHandler(SettingsClick);
    cm.MenuItems.Add(miCurr);

    miCurr = new MenuItem();
    miCurr.Index = 1;
    miCurr.Text = "Beenden";
    miCurr.Click += new System.EventHandler(ExitClick);
    cm.MenuItems.Add(miCurr);

    notico = new NotifyIcon();
    notico.Icon = new Icon("tanss.ico");
    notico.Text = "TANSS Busylight Connector";
    notico.Visible = true;
    notico.ContextMenu = cm;
    notico.DoubleClick += new EventHandler(NotifyIconDoubleClick);

    Application.Run();

}

//==========================================================================
protected static void ExitClick(Object sender, EventArgs e)
{
    notico.Dispose();
    Application.Exit();
}

//==========================================================================
protected static void SettingsClick(Object sender, EventArgs e)
{

    /// <summary>
    /// Der Haupteinstiegspunkt für die Anwendung.
    /// </summary>

    // This should open the "Settings"-Popup, containing 3 textboxes and a button to      save them to xml.

}

//==========================================================================
protected static void NotifyIconDoubleClick(Object sender, EventArgs e)
{
    // ...
}

}

Now i want to open a new Form as a Popup containing 3 textboxes to write some values in and a button to save them.
In the background, a never ending loop is requesting a url and parsing a value out of a json.
could you help me opening the new form (its not made yet, i just need it to open first :/)
and where do i embedd my background loop-code?
thanks so much!

A: It is as simple as
MyForm form1 = new MyForm();
form1.Show();

You have to create a new form object and show it on screen.
and, if you want to, you can set all others properties
form1.Location = new Point(20, 20);
form1.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
form1.MaximizeBox = true;
form1.ControlBox = true;
......

I think is better (easier actually) to create the form from the designer and avoid the creation of every textbox and everything from code.


text:
Q: Outer loop only runs once :( My code is of course below. I'm just trying to see if my nesting is working, so I'm printing a string so that each character should correspond to an iteration of the loop at that level. So '1' outside of the loop, '2' is the first loop, '3' is the inner loop.
var testing = function(){
    string = '1';
    for(var count = 0; count < 10; count++){
        string += '2';
        for(var count = 0; count < 10; count++){
            string += '3'
        };
        string += '2'
    }
    string += '1'
    return string;
}

document.write(testing())

the page reads: 12333333333321
but I want it to have '2{...}2' 10 times instead of just the once. The outer loop is only running once.

A: In Javascript, the scope of a variable declared with var is the current execution context (in your case the function) and if you redeclare a variable it doesn't lose it's value.
Add this together and your inner loop and outer loop are both using the same count variable.
Solution: rename one of them.


text:
Q: JavaScript execution exceeded timeout
*

*I am not doing a large chunk of computation in JS.

*Everything works fine on iPad iOS 5 in Safari until I added this code:
var watchID = navigator.geolocation.watchPosition(updatePos,locationError,{maximumAge: 10000, frequency: 60000, enableHighAccuracy: true, timeout: 1000});

function updatePos(position) {
    if (position.coords.accuracy < accuracyThreshold) {
        $.post(websiteRoot + '/ReportDeviceLocation?rand=' + (Math.random() * Math.random()) + '&longitude=' + position.coords.longitude + '&latitude=' +position.coords.latitude);

    } else {
        console.debug("Location data is not accurate enough. Location not updated.");
    }
}

*Then the web page worked for about 4 minutes and I get this error:
JavaScript execution exceeded timeout.

*Then no JavaScript would load. None of the debug messages I inserted into my.js file would print. Only the above error.

*The error persists even after I left the page that generated this error, and opened other web pages under the same domain.

*I used try and catch, I used setTimeout function, but neither gave me the source of the error nor solved the problem.
I don't know what the problem is. It has been burning me for the entire day and will be burning me for the weekend.

A: Surprisingly, when I used geolocation.getCurrentPosition, the error message stopped showing up.
To replace watchPosition with getCurrentPosition, I use the function setInterval:
        function getLocation() {
            navigator.geolocation.getCurrentPosition(updatePos, locationError, { enableHighAccuracy: true, timeout: 10000 });
        }

        var intervalID = window.setInterval(getLocation, 10000);

This has worked out better than watchPosition because watchPosition sometimes does not follow rules(update location 8 times in 3 minutes despite the frequency is set to 10 minutes).
If the timeout still occurs, one would need to call clearInterval:
var geolocationID;
(function getLocation() {
     var count = 0;
     geolocationID = window.setInterval(
       function () {
            count++;
            if (count > 3) {  //when count reaches a number, reset interval
                window.clearInterval(geolocationID);
                getLocation();
            } else {
                navigator.geolocation.getCurrentPosition(updatePos, locationError, { enableHighAccuracy: true, timeout: 10000 });
            }
        },
        600000); //end setInterval;
})();

A: Just as an addendum:
This problem exists on the iPhones as well (not surprisingly) and is still not fixed. Even worse, if you exit (not kill) the browser, you get a battery drainer, within 12hrs the phone is dead. Unfortunately I need to rely on the watch since getCurrentPosition is by far not as accurate.
Once the bug sets in (after ~4min, as reported), an execution timeout error is reported exactly every second and the JS engine is dead. The problem is that it is NOT an execution timeout. That is the bug, even site reloads do not change it, stop/start of the watch does not help either. Only killing the browser (double-tap on the button, long tap on icon, then -) does the trick.
It seems that we are doomed until apple releases a fix...
Update: after more experimenting with this it seems the problem are XHR requests, maybe jquery specific, it seems there is some limit on those requests or no proper cleanup. The timeout error would pop up on any other site as well as soon as the first XHR is triggered. Before all JS runs fine.

A: I struggled with the same problem and found a quite elegant solution.
The timeout errors occurred when I started my 'follow location mode' with navigator.geolocation.watchPosition and reloaded the page without stopping it. So I could fix this problem just by clearing the watcher when the user leaves the page.
$(window).unload(function(){
  window.navigator.geolocation.clearWatch(myWatchHandler);
});

Hope this helps!

A: I am using watchPosition to post back my long, lat and most important speed. I got the same problem like users in this thread: Safari/Chrome on iOS killed the GPS feed (it wasn't the interval that stopped, I tested). Only by killing the browser (as in double click home button) I could make it work again for a couple of seconds. I tried everything, like clearing the interval but it didn't work. Then, later, I went outside and it kept on working! Went back inside and the GPS signal was gone. Since apps like RunKeeper kept on working inside I assumed that it would work inside as well, but that turned out to be wrong. If anybody has any questions, please feel free to ask.

A: Maybe it's the Safari issue that blocks all getCurrentPosition while running watchPosition in another Tab or Website.

A: I had a similar problem, and I also use html5 geolocation.
I have already implemented the suggested setInterval() solution. The same issue to still occurred, although taking a much longer time.
I did some experimentation by putting the following snippet in my code, just to 'pause' the code execution:
ms = 30000;
ms += new Date().getTime();
while (new Date() < ms){
}

The above snippet reliably generates a javascript execution timeout. I surreptitiously discovered that the next snippet will generate a timeout as well. But it seems that the browser is able to recover from the timeout. Don't ask me why. It just works. I hope that those affected can verify my findings.
ms = 30000;
ms += new Date().getTime();
while (new Date() < ms){
    if (new Date() %100 == 0){
        console.log('in while');
    }
}

So, the solution seems to be, trivial it may seem, that console.logs should be added to portions of the code which is called most often. I hope that this can be helpful (though I think it seems ridiculous too but it works for me)


text:
Q: Hide frame instead of close when user click on close button of the window I have an application which shows a window. Instead of closing window when user presses on "Close" button I want just to hide this window, how can I do this?
Here is my code (it does not work, the app is closed on click):
  object UxMonitor {

  def main(args: Array[String]) {
    val frame = new MainScreen()
    frame.peer.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE)
    initTrayIcon(frame.peer)
  }

....
class MainScreen extends MainFrame {
      private val HEADERS = Array[Object]("Security", "Last Price", "Amount", "Cost")
      private val quotes = new Quotes()
      private val tableModel = new DefaultTableModel()

      title = "UX Monitor"

      tableModel.setColumnIdentifiers(HEADERS)

      private val table = new Table {
        model = tableModel
      }

      contents = new ScrollPane {
        contents = table
      }

      quotes.setListener(onQuotesUpdated)
      quotes.startUpdating

      peer.addWindowListener(new WindowAdapter{
        def windowClosing(e : WindowEvent){
            self.setVisible(false)
        }
      })

      pack

A: Simplest method is:
final JFrame frame=...;

....

frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

Alternatively you can achieve the same result with adding a WindowAdapter overriding windowClosed(...) and in there calling setVisible(false) on JFrame) like so:
...

 frame.addWindowListener(new WindowAdapter() {
    @Override
  public void windowClosing(WindowEvent evt) {
    frame.setVisible(false);
  }
});


text:
Q: Call Java From Javascript (Birt) I want to call Java object from within javascript in my rptdesign file (which is under a report project), after i put the jar of my class in /Web-Inf/lib directory and the .class in Web-Inf/classes i tried something like this in the open event of the data set:
gsh = new Packages.de.vogella.birt.stocks.daomock.StockDaoMock();

stock = gsh.getStockValues();

de.vogella.birt.stocks.daomock is the name of a package located in a Java Project (ClassPackage) under /src
StockDaoMock is the name of the class.
getStockValues() is the method.
But I get this error:
cannot evaluate the script. data set script method fetch returned null.expected a boolean value.

What is wrong?

I tried to replace all the code in the fetch method by
     "system.out.println("essai");
     return true;"
and still have this error
     "Data Set script method "Fetch" returned null; expected a Boolean value."

A: Enable logging to see the stack trace. See the wiki.
Make sure the exception is logged (the example just logs the message) :-)
"Quick and Dirty Logging" might also help.
You might also have a classloader issue. See this blog post for classloader options and how to debug bundle discovery by OSGi when using BIRT.
[EDIT] The error message means that you forgot return true; or return false; at the end of the fetch method.

A: The java runs on the server, and javascripts runs in the browser, so it is obvious you can't call Java from javascript directly.
There is a library called DWR (Direct Web Remoting). It can expose Java method to Javascript methods. When you call the Javascript it makes a AJAX request, then DWRServlet handles it, executes your desired Java method, and returns the method result to the browser.


text:
Q: What should the Scrum Master do when the Product Owner tries to add more items to the Sprint? Sprint planning has completed, sprint goals set, all is well. 2 days in the PO asks the lead developer if they could add a new item into the sprint, "it's an easy fix" "another team wants this".
What should the developer and the Scrum Master do? What is the conversation?

A: The Scrum Master may have a conversation with the Product Owner to understand the workflow on how an item comes into a Sprint backlog. If the Product Owner understands the workflow eg: Create item, Item satisfies "Definition of Ready" (User story template, estimate...), Item lands in Backlog, Item may be pulled in Sprint Backlog if there is free capacity and it does not affect any Sprint Goal.

A: The Scrum Master can plan ahead for this in multiple ways:

*

*Plan less story points to the sprints in case this happens again, leaving room to add some extra ad-hocs tickets when they come

*Take out a ticket from the current sprint with the same amount of story points that the ticket the PO is trying to add

*Help the POs reflect and ask them: "what happen if we don't do this ad-hoc right now?" "Adding this ticket to the on going sprint will aid or delay the progress towards the sprint goal?"

*Alternatively, manage expectations by creating a list together with the lead dev and the PO with a set of rules about when it is ok to add a ticket to an on going sprint, so everybody is on the same page

A: Scrum has always accounted for this situation from the very beginning.  The simple answer is that the Sprint Backlog is "locked down" at the start of the Sprint and cannot be changed.  This, "Oh, it's just a quick fix." situation was exactly described by Ken in the original book as a prime source of distractions that get in the way of the Team from succeeding.
There's only one recourse, which is a "premature termination of the Sprint".  The Sprint ends immediately, nothing is delivered and a new Sprint is started with a new Sprint Backlog and a new end date.
It sounds harsh, but the truth is that the organization won't respect the Team's time unless you say "No" in these situations.
Another aspect to this is that someone early on, I cannot remember who, said the Sprint length should be set to the length of time that the organization go without changing its mind.  So if this is a real problem, then shorten up the Sprints.
Back at the beginning, most teams used 4 week Sprints, and this is now seen as way too long.  If you can swing it, a 1 week Sprint can be way better.  In the example given in the question, 2 days into the Sprint is 3 days away from the end of a 1 week Sprint, and waiting for the next Sprint for the "quick win" is probably going to be fine.
The answer to most Scrum problems is often to make your stuff smaller.

A: What should the SM do?  Well... nothing.
If the SM has coached the team properly, and they understand that they have committed to the Sprint Goal and understand it cannot be endangered, then you can just assume that the person being asked to do the work feels confident that the extra task and the Sprint Goal can be met.
If the extra task is competed and the Sprint Goal is failed, then that's a learning exercise for the Retro - Does everyone in the team understand that the Sprint Goal is a commitment and that it shouldn't be endangered?  You could also cover techniques for helping the team handle such situations.
There's nothing wrong with the team doing extra tasks - as long as the Sprint Goal is met. This covers the self-management part of Scrum. The team decide for themselves if they are capable enough to do both activities in the Sprint timebox, and if not, they need to be coached to push back.


text:
Q: Fast way to recolour an indexed image based on another array I have a an indexed image bins consisting of multiple regions. 0 is background and other positive value is a region.
I want to fill in values for each region based on another array, e.g.:
bins = # image of shape (height, width), type int
ids = np.array([1, 5, ... ]) # region ids
values = np.array([0.1, ...]) # Values for each region, same shape as ids
img = np.empty(bins.shape, 'float32')
img[:] = np.nan
for i, val in zip(ids, values):
    img[bins == i + 1] = val

but this loop is super slow in python. Is there a way to write it in a nice numpy way?
Thanks in advance!

A: Here's an approach -
out = np.take(values, np.searchsorted(ids, bins-1))
out.ravel()[~np.in1d(bins,ids+1)] = np.nan

Please note that this assumes ids to be sorted. If that's not the case, we need to use the optional argument sorter with np.searchsorted.

Here's another one with a very similar idea, but as a minor tweak using initialization and limiting the use of np.searchsorted only on the  valid elements -
out = np.full(bins.shape, np.nan)
mask = np.in1d(bins,ids+1)
out.ravel()[mask] = np.take(values, np.searchsorted(ids+1, bins.ravel()[mask]))


text:
Q: HTML 5 Progress element freezes on activity I want to display an indefinite progress bar while my JavaScript application performs some initialization, e.g. downloading a JSON object using the fetch api. Unfortunately, any activity freezes the progress bar on Firefox 52 64 Bit on Gnome 3.16.4, which may cause my users to reload as they assume the application crashed.
As an MWE I use many console.log calls to emulate the initialization, which also results in a blocked progress bar:

<html>
<head><meta charset="utf-8"></head>
<body style="width:99%;height:1000px;">
<progress style="width:99%;position:absolute;top:50%;height:20px;"></progress>

<script>
for(i=0;i<100000;i++) {console.log("nop");}
</script>

</body>
</html>

How can I achieve an unfrozen progress bar during activity?

A: please try this way:

  function print(){
    return new Promise((resolve,reject)=>{
      console.log('nop');
      resolve(true);
    });
  }

  async function go(){
    for(i=0;i<100000;i++) {
      await print();
    }
  }

  go();
<progress style="width:100%;height:20px;"></progress>


text:
Q: Stripe SCA one-time payments Rails I'm integrating Stripe SCA with payment intents into my rails 5.2.3 (ruby 2.5.1) app.  I successfully had one-time payments working properly, however after I integrated subscriptions (successfully working), the one-time payments are receiving an incomplete status on Stripe "The customer has not entered their payment method".  Looking at the JSON I can see my payment intent with ID successfully being created, however my charges, data is showing up as null.  I can't figure out why the data is not being passed to stripe.  Here are the corresponding files:
purchases.show.html.erb

Purchasing <%= @recipe.title %> for <%= number_to_currency(@recipe.price) %>

    <%= form_with url: recipe_purchase_path(@recipe.id), local: true, id: "payment-form", data: { payment_intent_id: @payment_intent.client_secret } do |form| %>

                Credit or debit card

            Name on Card
            <%= form.text_field :name_on_card, placeholder: "Full name", class: "form-control" %>

            <%= form.hidden_field :payment_intent_id, value: @payment_intent.id %>
            <button class="btn btn-outline-primary buy-recipe">Submit Payment</button>

    <% end %>

purchases_controller.rb
class PurchasesController < ApplicationController
    before_action :authenticate_user!
    before_action :set_recipe, only:[:show, :create]

    def receipt
        @purchase = Purchase.find_by_uuid(params[:id])
        @recipe = Recipe.find(@purchase.recipe_id)
    end

    def show
        @payment_intent = Stripe::PaymentIntent.create(
                amount: @recipe.price_in_cents,
                currency: 'usd',
                payment_method_types: params['card'],
                metadata: {integration_check: 'accept_a_payment'},
            )
    end

    def create
        @payment_intent = Stripe::PaymentIntent.retrieve(params[:payment_intent_id])
        if @payment_intent.status == "succeeded"
            charge = @payment_intent.charges.data.first
            card = charge.payment_method_details.card

            purchase = Purchase.create(
                    customer_id: charge.id,
                    user_id: current_user.id,
                    recipe_id: @recipe.id,
                    uuid:   SecureRandom.uuid,
                    amount: @recipe.price
                )
            current_user.favorites << @recipe
            redirect_to recipe_path(@recipe.slug), notice: "#{@recipe.title} has been added to your Cookbook, thanks for purchasing!"
        else
            flash[:alert] = "Your order was unsuccessful.  Please try again."
            redirect_to recipe_purchase_path(@recipe.id)
        end
    end

    private

    def set_recipe
        @recipe = Recipe.find(params[:recipe_id])
    end

end

purchases.index.js

document.addEventListener("turbolinks:load", () => {
    const form = document.querySelector("#payment-form")
        if (form == null) { return }

    const public_key = document.querySelector("meta[name='stripe-key']").getAttribute("content")
    const stripe = Stripe(public_key)

    const elements = stripe.elements()
    const card = elements.create('card')
    card.mount('#card-element')

    card.addEventListener("change", (event) => {
        var displayError = document.getElementById('card-errors')
        if (event.error) {
            displayError.textContent = event.error.message
        } else {
            displayError.textContent = ''
        }
    })

    form.addEventListener("submit", (event) => {
    event.preventDefault()

    let data = {
      payment_method: {
        card: card,
        billing_details: {
          name: form.querySelector("#name_on_card").value
        }
      }
    }

    stripe.confirmCardPayment(form.dataset.paymentIntentId, data).then((result) => {
      if (result.error) {
        var errorElement = document.getElementById('card-errors')
        errorElement.textContent = result.error.message
      } else {
        //
        //
        form.submit()
      }
    })
  })
})

and a screenshot of JSON

here is my subscriptions.js file
document.addEventListener("turbolinks:load", () => {
    let cardElement = document.querySelector("#card-element")

    if (cardElement !== null) { setupStripe() }
})

function setupStripe() {
    const stripe_key = document.querySelector("meta[name='stripe-key']").getAttribute("content")
    const stripe = Stripe(stripe_key)

    const elements = stripe.elements()
    const card = elements.create('card')
    card.mount('#card-element')

    var displayError = document.getElementById('card-errors')

    card.addEventListener('change', (event) => {
        if (event.error) {
            displayError.textContent = event.error.message
        } else {
            displayError.textContent = ''
        }
    })

    const form = document.querySelector("#payment-form")
    let paymentIntentId = form.dataset.paymentIntent
    let setupIntentId = form.dataset.setupIntent

    if (paymentIntentId) {
        if (form.dataset.status == "requires_action") {
            stripe.confirmCardPayment(paymentIntentId, { setup_future_usage: 'off_session' }).then((result) => {
                if (result.error) {
                    displayError.textContent = result.error.message
                    form.querySelector("#card-details").classList.remove("d-none")
                } else {
                    form.submit()
                }
            })
        }
    }

    form.addEventListener('submit', (event) => {
        event.preventDefault()

        let name = form.querySelector("#name_on_card").value
        let data = {
            payment_method_data: {
                card: card,
                billing_details: {
                    name: name,
                }
            }
        }
        // Complete a payment intent
        if (paymentIntentId) {
            stripe.confirmCardPayment(paymentIntentId, {
                payment_method: data.payment_method_data,
                setup_future_usage: 'off_session',
                save_payment_method: true,
            }).then((result) => {
                if (result.error) {
                    displayError.textContent = result.error.message
                    form.querySelector("#card-details").classList.remove("d-none")
                } else {
                    form.submit()
                }
            })

            // Updating a card or subscribing with a trial (using a SetupIntent)
    } else if (setupIntentId) {
      stripe.confirmCardSetup(setupIntentId, {
        payment_method: data.payment_method_data
      }).then((result) => {
        if (result.error) {
          displayError.textContent = result.error.message
        } else {
          addHiddenField(form, "payment_method_id", result.setupIntent.payment_method)
          form.submit()
        }
      })

        } else {
        //subscribing w no trial
            data.payment_method_data.type = 'card'
            stripe.createPaymentMethod(data.payment_method_data).then((result) => {
                if (result.error) {
                    displayError.textContent = result.error.message
                } else {
                    addHiddenField(form, "payment_method_id", result.paymentMethod.id)
                    form.submit()
                }
            })
        }
    })
}

function addHiddenField(form, name, value) {
    let input = document.createElement("input")
    input.setAttribute("type", "hidden")
    input.setAttribute("name", name)
    input.setAttribute("value", value)
    form.appendChild(input)
}

A: So special thanks to Chris Oliver on this...but what needed to be done was on the show.html.erb I had to change the payment_intent_id to :payment_intent in the form data.
<%= form_with url: recipe_purchase_path(@recipe.id), local: true, id: "payment-form", data: { payment_intent: @payment_intent.client_secret } do |form| %>

then in my show action in purchases_controller.rb I needed to add customer
def show
    @payment_intent = Stripe::PaymentIntent.create(
            amount: @recipe.price_in_cents,
            currency: 'usd',
            payment_method_types: ['card'],
            customer: current_user.stripe_id || current_user.stripe_customer.id
            )
end

Then I completely removed my purchases.js since the one-time payments are being handled in the subscription.js


text:
Q: Volume of a cone r = 5 height 10 So I have acone with radius 5 and height 10. I am trying to find it's volume.
I set up similar trinagles to find a function for the radius so I can get a "slice " and then compute the integral from 0 to 10
$$(10-y)/10 = r/5$$
$$r = \frac{10-y}{2}$$
$$V = \int_0^{10} \pi * r^2$$
$$\pi \int_0^{10}  *(\frac{10-y}{2})^2$$
$$(\frac{10-y}{2})^2 = y^2/4 -5y + 25$$
$$\pi \int_0^{10}  y^2/4 -5y + 25$$
This is wrong, I have odne it many times, why?

A: Your calculation, as far as you took it, is right, you want
$$\pi\int_0^{10}\left(\frac{y^2}{4}-5y+25\right)\,dy.$$
For the integration, an antiderivative is $\frac{y^3}{12}-\frac{5y^2}{2}+25y$.
When you "plug in," the last two terms cancel, and you get $\frac{1000}{12}$. Multiply by $\pi$, simplify, and you get $\frac{250\pi}{3}$.
The work is a little simpler if you put the cone point down, with the apex   at the origin.
Then your similar triangle method gives that the radius of cross-section at height $y$ is $\frac{y}{2}$. Thus our volume is
$$\int_0^{12}\pi\frac{y^2}{4}\,dy.$$
We get $\frac{1000\pi}{12}$, or equivalently $\frac{250\pi}{3}$.

A: The formula for the volume of a cone of radius $r$ and height $h$ is:
$$V=\frac{1}{3}\pi r^2h$$
Plugging in the values of $r$ and $h$ given in the problem gives a volume of $\frac{250\pi}{3}$.  If you evaluate the integral you wrote, you will get the same number.  Your answer is fine.


text:
Q: Why define vector decomposition in terms of an inner product? I can already find the components of any vector in a vector space with respect to some basis by finding the coefficients in front of each basis vector. However I've seen some people define the components of a vector in terms of the inner product of the basis vectors and the vector you're trying to decompose.
These two approaches are equal, so why would you use the inner product approach if the basis coefficient approach requires less assumptions? (It isn't dependent on the presence of an inner product).

A: Because the vector may not be written out explicitly in a component-wise format.
Or, it might be the case that we'd like to project our vector $\vec{v}=a\hat{x}+ b\hat{y}$ into a different (e.g. rotated or skewed coordinate system). In this case, we must write out the new basis vectors in terms of the old, and take the inner product. We do not have the luxury of reading off the components in all cases.


text:
Q: Split list in to sublist in C# I like to split the list in to multiple list, list contains GUID's. For an example, if main list contains 130 GUID's, I have kept threshold as 50, so it should return, 3 list, 1st and 2nd list should contain 50 list each and third list will have 30 GUID's.
How can we do it? Please help me out!!

A: You can use this code. here I'm using string for demo, you can use your guid.
var list = new List<string> { "a", "b", "c", "d", "e" };
var threashold = 2;
var total = list.Count();

var taken = 0;
var sublists = new List<List<string>>(); //your final result
while (taken < total)
{
    var sublst = list.Skip(taken)
        .Take(taken + threashold > total ? total - taken : threashold)
        .ToList();
    taken += threashold;
    sublists.Add(sublst);
}

A: You can use following LINQ query:
 // your sample list
 List<Guid> guids = Enumerable.Range(0, 130).Select(i => Guid.NewGuid()).ToList();

 List<List<Guid>> splitted = guids
    .Select((guid, index) => new { guid, index })
    .GroupBy(x => x.index / 50)
    .Select(g => g.Select(x => x.guid).ToList())
    .ToList();

The essential method is Enumerable.GroupBy which groups them by index / 50. because integer division truncates the fractional part you get groups of 50.

A: You can use MoreLinq written by Jon Skeet:
google code (available on nuget)
The method you are looking for is Batch:
using MoreLinq
...
IEnumerable<IEnumerable<Guid>> result = enumerableGuids.Batch(50);


text:
Q: Figure into a subplot matplotlib I'm currently working with a package that calculates SSA (singular spectrum analysis) in python and it has some functions that give a fig as an output. It would be useful for me to put some figures inside a figure I'm creating as a subplot.
Is there anyway to do that?

A: Since it's really hard to copy content from one figure to another and it is in general not recommended, I would suggest you write your own version of the plotting function of the mcssa package.
So instead of
m = MCSSA(...)
m.run_mcssa(...)
m.plot()

you can copy the following function to plot the result to an axes you specify
def ssaplot(mc_ssa, freq_rank=True, ax=None):
    ax = ax or plt.gca()
    ax.set_yscale('log')
    ax.set_ylabel('Variance')
    ax.set_title('M: {}; cov: {}'.format(mc_ssa.M, mc_ssa.algo))

    if not freq_rank:
        x = [i for i in range(mc_ssa.M)]
        y = mc_ssa.values

        ax.set_xlabel('Eigenvalue Rank')
        ax.plot(y, marker='s', linewidth=0, color='r')

    else:
        x = mc_ssa.freqs[mc_ssa.freq_rank]
        y = mc_ssa.values[mc_ssa.freq_rank]

        ax.set_xlabel('Frequency (Cycle/t. unit)')
        ax.plot(x, y, marker='s', linewidth=0, color='r')

    if mc_ssa.ismc:
        errors = np.array(mc_ssa.stats.iloc[3:5, :])
        mean_suro = np.array(mc_ssa.stats.iloc[0, :])
        ax.errorbar(x, y=mean_suro, yerr=errors, fmt=None,
                     ecolor='k', elinewidth=.5, capsize=2.5)
        ax.set_title('M: {}; g: {}; a: {}; Ns: {}'.format(mc_ssa.M,
                                                       mc_ssa.ar.gamma,
                                                       mc_ssa.ar.alpha,
                                                       mc_ssa.n_suro))

use it like
import numpy as np
import matplotlib.pyplot as plt
from mcssa import MCSSA   # probably(?)

m1 = MCSSA(...)
m1.run_mcssa(...)
m2 = MCSSA(...)
m2.run_mcssa(...)

fig, (ax1, ax2) = plt.subplots(2)
ssaplot(m1, ax=ax1)
ssaplot(m2, ax=ax2)
plt.show()

A: I think you can store the figure output in a variable and keep adding additional plots like you usually do using matplotlib. Here is a post of something similar to what you are asking.


text:
Q: Navwalker won't accept css classes defined in menu So I'm using the Bulma Framework w/ a Bulma Navwalker - The problem that I'm having is that it won't accept my custom css classes defined inside my WordPress menus.
So I have a is-mega class define inside one of my parent menu items, and it's not showing up under "navbar-item has-dropdown is-hoverable".

Does anyone see that I might be missing?
Here is the Navwalker:
<?php
/**
 * Bulma-Navwalker
 *
 * @package Bulma-Navwalker
 */

/**
 * Class Name: Navwalker
 * Plugin Name: Bulma Navwalker
 * Plugin URI:  https://github.com/Poruno/Bulma-Navwalker
 * Description: An extended Wordpress Navwalker object that displays Bulma framework's Navbar https://bulma.io/ in Wordpress.
 * Author: Carlo Operio - https://www.linkedin.com/in/carlooperio/, Bulma-Framework
 * Author URI: https://github.com/wp-bootstrap
 * License: GPL-3.0+
 * License URI: https://github.com/Poruno/Bulma-Navwalker/blob/master/LICENSE
 */

class Navwalker extends Walker_Nav_Menu {

    public function start_lvl( &$output, $depth = 0, $args = array() ) {

        $output .= "
";
    }

    public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

        $liClasses = 'navbar-item ';

        $hasChildren = $args->walker->has_children;
        $liClasses .= $hasChildren? " has-dropdown is-hoverable": "";

        if($hasChildren){
            $output .= "
";
            $output .= "\nurl."'>".$item->title."";
        }
        else {
            $output .= "url."'>".$item->title;
        }

        // Adds has_children class to the item so end_el can determine if the current element has children
        if ( $hasChildren ) {
            $item->classes[] = 'has_children';
        }
    }

    public function end_el(&$output, $item, $depth = 0, $args = array(), $id = 0 ){

        if(in_array("has_children", $item->classes)) {

            $output .= "
";
        }
        $output .= "";
    }

    public function end_lvl (&$output, $depth = 0, $args = array()) {

        $output .= "
";
    }
}
?>

A: You can achieve this by adjusting your walker slightly.  Bulmapress removes the standard classes from the walker so it can use its own.  By adding this, it will allow you to add your custom classes from the Appearance->Menu.
<?php

public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

        // Add your custom item classes here

        $custom_classes_from_menu = implode(' ', $item->classes); // turn the WP classes object array to string values

        $liClasses = 'navbar-item ' . $custom_classes_from_menu; // add the values to your classes list

        $hasChildren = $args->walker->has_children;
        $liClasses .= $hasChildren? " has-dropdown is-hoverable": "";

        if($hasChildren){
            $output .= "
";
            $output .= "\nurl."'>".$item->title."";
        }
        else {
            $output .= "url."'>".$item->title;
        }

        // Adds has_children class to the item so end_el can determine if the current element has children
        if ( $hasChildren ) {
            $item->classes[] = 'has_children';
        }
    }


text:
Q: Aligning HTML headings with image using CSS I'm new to CSS, and I'm experiencing a lot of difficulty with aligning things.
At the moment, I have
 and
 text and an image. I'd like the
 text to reside right beneath the
 text, and I'd like this
-
 block to be positioned in the top-left corner of the screen. I'd like the image to be inline with the text, but centered in the middle of the screen. This is what I have so far:
.header img {
    width: 525px;
    height: 188px;
    text-align: center;
    position: relative:
}

.header h1{
    position: absolute;
    left: 15px;
    top: 35px;
    font-family: 'Tehuti';
    font-size: 3em;
    margin: .2em .5em;
    color: rgba(0,0,0, 0.3);

}
.header h2{
    font-family: 'Tehuti';
    font-size: 3em;
    margin: .2em .5em;
    color: rgba(0,0,0, 0.3);
    background-color: rgba(37, 39, 37, 0.07);
    float: left;
}

I can't for the life of me get this to work. Any help would be greatly appreciated.

A: Since you are using an absolute positioned layout your could absolute position your  to the center of the screen with these styles:
.header img {
    position: absolute;
    left:50%;
    transform:translateX(-50%);
}

See this fiddle for a demo (fullscreen)

A: 1: text-align aligned the content inside the element so setting text-align: center to .header img will no center align the img.
2: the h1 and h2 has by default display: block so that is why it place one bellow the other, set display: inline-block or inline to placed next to each other.
Now you can float: left h1 and h2 set text-align: center to div .header but you will note that the img will not centered in the middle of the screen
So do this

h1, h2{
    display: inline-block;
    font-family: 'Tehuti';
    font-size: 1em;
    margin: .2em .5em;

    color: rgba(0,0,0, 0.3);
}

.header h2{
    background-color: rgba(37, 39, 37, 0.07);
}

.header{
    text-align: center;
}

.header img {
    width: 100px;
    height: 100px;
}

.h-content{
    position: absolute; /*If you want it to be always on the top-left of the screen, even when scrolls set fixed*/
    left: 15px;
    top: 35px;
}

I'm a h1

I'm a h2

I hope this help you


text:
Q: Flutter How to give a Container border bottom only In Flutter how to set a border for the bottom only,
As shown in the picture below, I have a Container with Text, showing a red color border from the bottom, Kindly guide how to set a border from the bottom only.

A: Use Border with the bottom argument.
Container(
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(width: 1.5, color: Colors.grey[300]),
            ),
          ),
          child: ListTile(
            title: Text(title),
            subtitle: Text(score + dateFormatted),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
                 children: [
                    Text(amount),
                    Checkbox(
                       value: false,
                       activeColor: Colors.green,
                       onChanged: (bool newValue) {}),
                    ],
                   ),
           ),
);

A: better to use ListView.separator constructor
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(debugShowCheckedModeBanner: false, home: Home()));

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Scaffold(body: Demo());
}

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: 42,
      separatorBuilder: (_, __) => Container(height: 1.5, color: Colors.grey[300]),
      itemBuilder: (context, index) {
        return ListTile(
          title: Text('item $index'),
        );
      },
    );
  }
}


text:
Q: add extra row of total salaries salary table:
EmpCode BASIC   HRA  CONV
--------------------------
   1    10000   500  300
   2    10000   500  300

Desired output:
   SalaryCode   SalaryDetails
    EmpCode           1
    BASIC           10000
    HRA               500
    CONV              300
   Total            10800

    EmpCode           2
    BASIC           10000
    HRA               500
    CONV              300
   Total            10800
 Grand Total        21600

"i like to show grand total after empcode '2'
 total"
i wrote the code for the total as
select SalaryCode, SalaryDetails
  from
  (select ecode,BASIC,HRA,CONV,(BASIC+HRA+CONV)SUB_Total from empstb) a
  unpivot(SalaryDetails for SalaryCode in (ecode,BASIC,HRA,CONV,SUB_Total)) upvt
but i don't know how to add grand total to it

A: You can use a combination of unpivot and GROUPING SETS. Not sure what you are using your final output for though
DECLARE @Salary TABLE
(
    EmpCode INT NOT NULL,
    BasicSalary INT NOT NULL,
    HRA INT NOT NULL,
    Conv INT NOT NULL
)

INSERT INTO @Salary (EmpCode,BasicSalary,HRA,Conv)
VALUES (1,10000,500,300),(2,10000,500,300);

SELECT  CASE
        WHEN GROUPING(CA1.ColName) = 1 AND GROUPING(S.EmpCode) = 1 THEN 'GrandTotal'
        WHEN GROUPING(CA1.ColName) = 1 THEN 'Total'
        ELSE CA1.ColName
    END AS SalaryCode,
    SUM(CA1.ColVal) -   CASE --Adjust the sum to exclude the EmpCode values
                            WHEN GROUPING(CA1.ColName) = 1 AND GROUPING(S.EmpCode) = 1 THEN SUM(S.EmpCode) / 4
                            WHEN GROUPING(CA1.ColName) = 1 THEN S.EmpCode
                            ELSE 0
                        END AS SalaryDetails
FROM    @Salary AS S
CROSS
APPLY   (VALUES (CAST('BasicSalary' AS VARCHAR(50)),BasicSalary,2),('HRA',HRA,3),('Conv',Conv,4),('EmpCode',EmpCode,1)) AS CA1(ColName,ColVal,RowPos)
GROUP   BY GROUPING SETS((),(EmpCode),(EmpCode,ColName,CA1.RowPos))
ORDER   BY ISNULL(S.EmpCode,MAX(S.EmpCode) OVER ()+1), ISNULL(CA1.RowPos,MAX(CA1.RowPos) OVER()+1) ASC;

Edit
Output has been tweaked as per OP. Do feel this level of presentation doesn't belong here, but this should be as required. As the EmpCode is included in the list some adjustments have to be made to ensure it isn't included in the totals. Also a position value has been added to output in the correct order


text:
Q: TypeError without a clue student_scores = input('Input a list of student scores: ')
for n in range(0, len(student_scores)):
    student_scores[n] = int(student_scores[n])
print(student_scores)

highest = 0
for scores in student_scores:
    if highest < scores:
        highest = scores
print(f'The highest score is {highest}')

I'm learning the basic of Python and input the code accurately that the tutorial video says, but only mine gets TypeError: 'str' object does not support item assignment on the line 3.
I checked it several times, but still have no clue why.

A: The input() function will invariably return a string. What you want to do is have the user input several numbers (presumably separated by a space) and get a list of integer values from that. You can do that as follows (with some explanations on my part):
student_scores_string = input('Input a list of student scores: ')

(That line will just get a string inputted by the user.)
student_scores = student_scores_string.split()

(That line will give you a list, with each item in the list being one of the values inputted by the user, with a space as a separator.)
student_scores = [int(x) for x in student_scores]

(That line will loop over the elements in the student_scores list, turn each of them into an inetger - remember, so far we have strings! - and put that into the list.)
Then you can continue with your code.

A: Assume that the input is in the form '25 30 23' - i.e., a string with integer tokens and whitespace delimiters
scores = input('Input a list of student scores: ')
print('The highest score is', max(map(int, scores.split())))

Output:
The highest score is 30

A: You need to split the input as list, cause student_scores is a string and does not support item assignment (immutable). Assuming the input separated by space:
student_scores = input('Input a list of student scores: ').split()
for n in range(0, len(student_scores)):
    student_scores[n] = int(student_scores[n])
print(student_scores)

highest = 0
for scores in student_scores:
    if highest < scores:
        highest = scores
print(f'The highest score is {highest}')

To get the highest value, you can use highest = max(student_scores):
print(student_scores := [int(n) for n in input('Input a list of student scores: ').split()])
highest = max(student_scores)
print(f'The highest score is {highest}')

Or:
highest = max([int(n) for n in input('Input a list of student scores: ').split()])
print(f'The highest score is {highest}')


text:
Q: Wordpress wp enqueue style I am writing my first wordpress plugin, and I am stuck. Badly.
I want to include a css file in the admin part of the plugin. But I can`t for some reason. The code I tried (and many variation of it):
// Register style sheet.
add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );

/**
 * Register style sheet.
 */
function register_plugin_styles() {
    wp_register_style( 'statistika', plugins_url( '/statistika/css/style.css' ) );
    wp_enqueue_style( 'statistika' );
}

The paths are good I am sure of it, when I write the URL manually in the browser the style open like any other. The thing I am suspecting the error is the files I am including in the plugin php file. I only included wp-load.php in the beginning. Is that enough for the function wp_register_style to work? If it`s not that then what is the problem? Please help.
EDIT:
New problem, how to include jquery and javascript files inside the admin side of wordpress. I tried this:
wp_enqueue_script('jquery', plugins_url('/js/jquery.js', __file__));
wp_enqueue_script('jquery', plugins_url('/js/functions.js', __file__));

I added this to the existing function in the answer.
EDIT 2:
Got it, I forgot that wordpress does not like $ as a jquery object.

A: you have to change wp_enqueue_scripts by  admin_enqueue_scripts

add_action( 'admin_enqueue_scripts', 'safely_add_stylesheet_to_admin' );

/**
 * Add stylesheet to the page
 */
function safely_add_stylesheet_to_admin() {
    wp_enqueue_style( 'prefix-style', plugins_url('style_admin.css', __FILE__) );

this tutorial will help you how to add Stylesheets To WordPress Correctly
I wish my answer be helpful for you.

A: Very simple. Just give path of your CSS file.
function add_wplink_with_parse_stylesheet()
{
    wp_enqueue_style( 'prefix-style', plugins_url( 'CSS File Path here', ____FILE____) );
}

add_action('admin_enqueue_scripts', 'add_wplink_with_parse_stylesheet');

A: Most of the times scripts/styles enqueued are only relevant for specific pages.
To minimize redundant file server calls it is best to perform this action only on desired pages:
// Hook enqueue style sheet.
add_action( 'wp_enqueue_scripts', 'register_my_plugin_styles' );

//Register & Enqueue style sheet
function register_my_plugin_styles() {
    if ( is_page( 'specific-page-name' ) ) {
        wp_register_style( 'my_plugins_style', plugins_url( '/my_plugins_name/css/example.css' ) );
        wp_enqueue_style( 'my_plugins_style' );
    }
}

This would work the same for scripts.
If you want a style/script loaded only on the homepage (front-page), you can use  is_home() instead of is_page().


text:
Q: Dot and Cross product of matrices I have the following matrix multiplication
$$ \left(\begin{matrix} -3&2 \\ 5&-3  \\ \end{matrix}\right)^{-1} \cdot\left(\begin{matrix} 1&4&0 \\ 1 & 1&-2  \\ \end{matrix}\right)\cdot\left[\left(\begin{matrix} 1 \\ 4\\3 \end{matrix}\right)\wedge\left(\begin{matrix} 5 \\ 2\\-1 \end{matrix}\right)\right]$$
For the inverse I get:
$$\left(\begin{matrix} 3 & 5 \\ 2 & 3 \end{matrix}\right)$$
And the cross product leaves me with:
$$\left(\begin{matrix} -10 \\ 16\\-18 \end{matrix}\right)$$
Now it should look like the following:
$$\left(\begin{matrix} 3 & 5 \\ 2 & 3 \end{matrix}\right)\cdot
\left(\begin{matrix} 1&4&0 \\ 1 & 1&-2 \end{matrix}\right)\cdot
\left(\begin{matrix} -10 \\16 \\-18 \end{matrix}\right)$$
This is my current thinking but I have to be making an error since I'm getting the wrong answer.
Hopefuly showing step-by-step helps identifying my error.
Thank you in advance!