PyQt5 QSlider two positions

Question: I want the user to select two frequencies: one low frequency and one high frequency.
Can I make this with one QSlider?
I found this page: https://doc.qt.io/qt-5/qtwidgets-widgets-sliders-example.html but it hasn't something that can I use for this goal.
Answer: file range_slider.py
<code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os
from PyQt5 import QtCore, QtGui, QtWidgets

# Originated from
# https://firstname.lastname@example.com/msg22889.html
# Modification refered from
# https://gist.github.com/Riateche/27e36977f7d5ea72cf4f

class RangeSlider(QtWidgets.QSlider):
    sliderMoved = QtCore.pyqtSignal(int, int)

    """ A slider for ranges.

        This class provides a dual-slider for ranges, where there is a defined
        maximum and minimum, as is a normal slider, but instead of having a
        single slider value, there are 2 slider values.

        This class emits the same signals as the QSlider base class, with the
        exception of valueChanged
    """
    def __init__(self, *args):
        super(RangeSlider, self).__init__(*args)

        self._low = self.minimum()
        self._high = self.maximum()

        self.pressed_control = QtWidgets.QStyle.SC_None
        self.tick_interval = 0
        self.tick_position = QtWidgets.QSlider.NoTicks
        self.hover_control = QtWidgets.QStyle.SC_None
        self.click_offset = 0

        # 0 for the low, 1 for the high, -1 for both
        self.active_slider = 0

    def low(self):
        return self._low

    def setLow(self, low:int):
        self._low = low
        self.update()

    def high(self):
        return self._high

    def setHigh(self, high):
        self._high = high
        self.update()

    def paintEvent(self, event):
        # based on http://qt.gitorious.org/qt/qt/blobs/master/src/gui/widgets/qslider.cpp

        painter = QtGui.QPainter(self)
        style = QtWidgets.QApplication.style()

        # draw groove
        opt = QtWidgets.QStyleOptionSlider()
        self.initStyleOption(opt)
        opt.siderValue = 0
        opt.sliderPosition = 0
        opt.subControls = QtWidgets.QStyle.SC_SliderGroove
        if self.tickPosition() != self.NoTicks:
            opt.subControls |= QtWidgets.QStyle.SC_SliderTickmarks
        style.drawComplexControl(QtWidgets.QStyle.CC_Slider, opt, painter, self)
        groove = style.subControlRect(QtWidgets.QStyle.CC_Slider, opt, QtWidgets.QStyle.SC_SliderGroove, self)

        # drawSpan
        #opt = QtWidgets.QStyleOptionSlider()
        self.initStyleOption(opt)
        opt.subControls = QtWidgets.QStyle.SC_SliderGroove
        #if self.tickPosition() != self.NoTicks:
        #    opt.subControls |= QtWidgets.QStyle.SC_SliderTickmarks
        opt.siderValue = 0
        #print(self._low)
        opt.sliderPosition = self._low
        low_rect = style.subControlRect(QtWidgets.QStyle.CC_Slider, opt, QtWidgets.QStyle.SC_SliderHandle, self)
        opt.sliderPosition = self._high
        high_rect = style.subControlRect(QtWidgets.QStyle.CC_Slider, opt, QtWidgets.QStyle.SC_SliderHandle, self)

        #print(low_rect, high_rect)
        low_pos = self.__pick(low_rect.center())
        high_pos = self.__pick(high_rect.center())

        min_pos = min(low_pos, high_pos)
        max_pos = max(low_pos, high_pos)

        c = QtCore.QRect(low_rect.center(), high_rect.center()).center()
        #print(min_pos, max_pos, c)
        if opt.orientation == QtCore.Qt.Horizontal:
            span_rect = QtCore.QRect(QtCore.QPoint(min_pos, c.y()-2), QtCore.QPoint(max_pos, c.y()+1))
        else:
            span_rect = QtCore.QRect(QtCore.QPoint(c.x()-2, min_pos), QtCore.QPoint(c.x()+1, max_pos))

        #self.initStyleOption(opt)
        #print(groove.x(), groove.y(), groove.width(), groove.height())
        if opt.orientation == QtCore.Qt.Horizontal: groove.adjust(0, 0, -1, 0)
        else: groove.adjust(0, 0, 0, -1)

        if True: #self.isEnabled():
            highlight = self.palette().color(QtGui.QPalette.Highlight)
            painter.setBrush(QtGui.QBrush(highlight))
            painter.setPen(QtGui.QPen(highlight, 0))
            #painter.setPen(QtGui.QPen(self.palette().color(QtGui.QPalette.Dark), 0))
            '''
            if opt.orientation == QtCore.Qt.Horizontal:
                self.setupPainter(painter, opt.orientation, groove.center().x(), groove.top(), groove.center().x(), groove.bottom())
            else:
                self.setupPainter(painter, opt.orientation, groove.left(), groove.center().y(), groove.right(), groove.center().y())
            '''
            #spanRect =
            painter.drawRect(span_rect.intersected(groove))
            #painter.drawRect(groove)

        for i, value in enumerate([self._low, self._high]):
            opt = QtWidgets.QStyleOptionSlider()
            self.initStyleOption(opt)

            # Only draw the groove for the first slider so it doesn't get drawn
            # on top of the existing ones every time
            if i == 0:
                opt.subControls = QtWidgets.QStyle.SC_SliderHandle# | QtWidgets.QStyle.SC_SliderGroove
            else:
                opt.subControls = QtWidgets.QStyle.SC_SliderHandle

            if self.tickPosition() != self.NoTicks:
                opt.subControls |= QtWidgets.QStyle.SC_SliderTickmarks

            if self.pressed_control:
                opt.activeSubControls = self.pressed_control
            else:
                opt.activeSubControls = self.hover_control

            opt.sliderPosition = value
            opt.sliderValue = value
            style.drawComplexControl(QtWidgets.QStyle.CC_Slider, opt, painter, self)

    def mousePressEvent(self, event):
        event.accept()

        style = QtWidgets.QApplication.style()
        button = event.button()

        # In a normal slider control, when the user clicks on a point in the
        # slider's total range, but not on the slider part of the control the
        # control would jump the slider value to where the user clicked.
        # For this control, clicks which are not direct hits will slide both
        # slider parts

        if button:
            opt = QtWidgets.QStyleOptionSlider()
            self.initStyleOption(opt)

            self.active_slider = -1

            for i, value in enumerate([self._low, self._high]):
                opt.sliderPosition = value
                hit = style.hitTestComplexControl(style.CC_Slider, opt, event.pos(), self)
                if hit == style.SC_SliderHandle:
                    self.active_slider = i
                    self.pressed_control = hit

                    self.triggerAction(self.SliderMove)
                    self.setRepeatAction(self.SliderNoAction)
                    self.setSliderDown(True)
                    break

            if self.active_slider < 0:
                self.pressed_control = QtWidgets.QStyle.SC_SliderHandle
                self.click_offset = self.__pixelPosToRangeValue(self.__pick(event.pos()))
                self.triggerAction(self.SliderMove)
                self.setRepeatAction(self.SliderNoAction)
        else:
            event.ignore()

    def mouseMoveEvent(self, event):
        if self.pressed_control != QtWidgets.QStyle.SC_SliderHandle:
            event.ignore()
            return

        event.accept()
        new_pos = self.__pixelPosToRangeValue(self.__pick(event.pos()))
        opt = QtWidgets.QStyleOptionSlider()
        self.initStyleOption(opt)

        if self.active_slider < 0:
            offset = new_pos - self.click_offset
            self._high += offset
            self._low += offset
            if self._low < self.minimum():
                diff = self.minimum() - self._low
                self._low += diff
                self._high += diff
            if self._high > self.maximum():
                diff = self.maximum() - self._high
                self._low += diff
                self._high += diff
        elif self.active_slider == 0:
            if new_pos >= self._high:
                new_pos = self._high - 1
            self._low = new_pos
        else:
            if new_pos <= self._low:
                new_pos = self._low + 1
            self._high = new_pos

        self.click_offset = new_pos

        self.update()

        #self.emit(QtCore.SIGNAL('sliderMoved(int)'), new_pos)
        self.sliderMoved.emit(self._low, self._high)

    def __pick(self, pt):
        if self.orientation() == QtCore.Qt.Horizontal:
            return pt.x()
        else:
            return pt.y()

    def __pixelPosToRangeValue(self, pos):
        opt = QtWidgets.QStyleOptionSlider()
        self.initStyleOption(opt)
        style = QtWidgets.QApplication.style()

        gr = style.subControlRect(style.CC_Slider, opt, style.SC_SliderGroove, self)
        sr = style.subControlRect(style.CC_Slider, opt, style.SC_SliderHandle, self)

        if self.orientation() == QtCore.Qt.Horizontal:
            slider_length = sr.width()
            slider_min = gr.x()
            slider_max = gr.right() - slider_length + 1
        else:
            slider_length = sr.height()
            slider_min = gr.y()
            slider_max = gr.bottom() - slider_length + 1

        return style.sliderValueFromPosition(self.minimum(), self.maximum(),
                                             pos-slider_min, slider_max-slider_min,
                                             opt.upsideDown)
</code>
Usage:
<code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os
from PyQt5 import QtCore, QtGui, QtWidgets
import range_slider

def echo(low_value, high_value):
    print(low_value, high_value)

def main(argv):
    app = QtWidgets.QApplication(sys.argv)
    slider = range_slider.RangeSlider(QtCore.Qt.Horizontal)
    slider.setMinimumHeight(30)
    slider.setMinimum(0)
    slider.setMaximum(255)
    slider.setLow(15)
    slider.setHigh(35)
    slider.setTickPosition(QtWidgets.QSlider.TicksBelow)
    slider.sliderMoved.connect(echo)
    #QtCore.QObject.connect(slider, QtCore.SIGNAL('sliderMoved(int)'), echo)
    slider.show()
    slider.raise_()
    app.exec_()

if __name__ == "__main__":
    main(sys.argv)
</code>
link: https://github.com/Qt-Widgets/range_slider_for_Qt5_and_PyQt5/blob/master/pyqt5_ranger_slider/main.py

PyQt5 QSlider two positions


I have categorical feature and i don't want to use one hot encoder as it will increase number of dimension in my datasets what option do i have now?

Question: My model is based on Decision-Tree algorithm hence I want to avoid One hot encoder as it will increase training time. I know a technique where i know instead of taking one hot encoding, I can go with an option of probability of category with respect to my classified output.But i don't know how to apply that probability part.?
Answer: Decision Trees can handle both numerical and categorical variables, therefore there is no need to encode your categorical variables.
Comment: Suppose you have a feature name zipcode/pincode as we know zipcode isn't number it an area pincode which is unique.
Comment: you said decision tree  can handle both numerical and categorical feature but i was getting an error . I was forced to use label encoder
Comment: hey i am newbie so if i am wrong then please correct me
Comment: This is an implementation-specific problem. What class of which package are you using for the DT model?
Comment: Suppose you have a feature name zipcode/pincode as we know zipcode isn't a number it an area pincode which is unique areawise. So in that scenario instead of considering one hot encoding, i want to take "probability" of that particular "zipcode" w.r.t to my class


moisture problems in a 104 sq ft bathroom with 110 cfm fan

Question: I have a primary bathroom which was just remodeled. Our GC put in a 110 CFM fan tied to a 4" duct. The exhaust should be taken to an external vent.
https://www.lowes.com/pd/Aero-Pure-Low-Profile-110-CFM-0-9-Sones-Quiet-Bathroom-Ventilation-Fan-Ceiling-Mount-White-ENERGY-STAR/1002393698
Theoretically, the fan is the appropriate size for our bathroom but we have such a problem with humidity and condensation even after leaving the fan on and opening the bathroom door and window. Nothing seems to work.
Could there be problems with the fan? With the duct work? The fan turns on and seems to be moving air (at least according to the piece of tissue I held to the vent to test). What can I look into to identify the problem and possible solution?
ETA: I live in Upstate NY. It's relatively warm and humid right now, but not bad and this was a problem before the warm and humid summer.
Comment: "The exhaust should be taken to an external vent."  You need to verify this.
Comment: @JACK that's true, but even if the OP's fan vents to the attic when it shouldn't, it should still be removing the moisture from the bathroom.
Comment: @AMC, this isn't a solution for you, but if you need something to ameliorate your situation while you solve the real problem with the vent fan, get yourself a portable dehumidifier and run it with a timer, e.g. start it when you turn the shower on and set it to run for some period of time after you stop the water.
Answer: It is very possible that the termination of the duct work out a wall or on the roof is clogged or blocked.
If you can reach it safely, check that any screen is open and free from lint, debris or possibly even nests from bugs or other animals.


How do I perform a high speed car jack?

Question: There is a control called "Active Hijack" which I have got bound to Q. This button makes me open my car door while I'm driving and as I pass cars an arrow highlights indicating I can jump onto that car, presumably to hijack it.

However, when I press the jump key, I faceplant into the back of the car and lose a lot of health.
How do I perform a high speed car jack?
Answer: The 'Action Hijack' key (Default Q) is the correct key, but there's a trick to it. Hit and hold Q to pull up the interface where Wei is hanging out of the car and the white arrow appears, then hit Q again when the arrow turns green. I hope this helps clarify the confusion for anyone in the future.
Answer: It sounds like you're hitting the jump button instead of the "Action Hijack" one to perform that final jump.
From the official manual or steam manual:

While driving and approaching another car, you can use left SHIFT to
  leap between the moving vehicles and perform an ACTION HIJACK. When
  the white arrow pointing towards the target vehicle turns green, tap
  the left SHIFT button to leap and take control of the other car.

Both manuals state that left SHIFT is the "Action Hijack" button but the in game default seems to be Q so just replace left SHIFT in the above with Q or, if manually remapped, whatever you have it mapped to.
Comment: Just so you know, the keys are completely incorrect. Left Shift is aiming, Q is action hijack.
Comment: @kotekzot Don't know if this has changed since release but I've just re-downloaded and it's Q now. Both manuals (official and Steam version) still state Left Shift though so I'm not going to misquote them. Merry Christmas!
Comment: You don't need to quote the manual, particularly when it's incorrect. Happy Christmas!
Comment: If the manual is wrong it's worth letting people know, especially if it relates specifically to something they're having trouble with.
Comment: As a side note at the end of an answer, sure, but not as the most prominent part of an answer that is then corrected at the bottom.

How do I perform a high speed car jack?


tangent line of a parametric curve in the form y = mx + c

Question: so for x(t) = 5cos(2t), y(t) = t^(7/2), and t = pi/4
i need to find the tangent line at point t=pi/4 in the form y=mx+c
it is my understanding that
dy/dx = (dy/dt)/(dx/dt)
and m = dy/dx
however when i evaluate dy/dx, and find y = (Pi/4)^(7/2), my answer appears to not be correct, i double checked on this calculator (which i know is likely to be unreliable) and my logic was the same, here is the link.
i only include it so you can see the working out as i dont know how to format well on this site yet and dont want to create an eyesore. I however came to the same answer, the same derivatives, and the same value for y when t = pi/4, and i have no idea what i am doing wrong.
Comment: i'd like to stress i did the working out myself first, not just took the answer from the calculator, the fact that mine is the same as the calculator makes me more worried about my logic then secure.
Comment: MathJax tutorial [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for future reference.
Comment: @JohnLou thank you, i intend to get familar with that soon.
Comment: Why do you think your answer is wrong?
Comment: I've graphed the function and the derivative [here](http://imgur.com/a/gQ20p). This looks like what you got, so I'm not sure where you made a mistake.
Comment: @JohnLou, because it is an online submission for the answer, and putting in my answer both in the approximate decimal form, or the formula form spits out wrong.
Comment: [Here's](https://www.desmos.com/calculator/mj5zoda6mo) a live link. You are right, so maybe you're missing the negative sign?
Comment: @JohnLou you are right i missed the minus sign! i would give u the answer but unfortunately u answered through comment form so i cant :(
Answer: $$x=5 \cos (2 t)\implies \frac{dx}{dt}=\color{red}{-}10 \sin (2 t)$$
$$y=t^{7/2}\implies \frac{dy}{dt}=\frac{7 }{2}t^{5/2}$$
$$\frac{dy}{dx}=\frac{\frac{dy}{dt} }{\frac{dx}{dt} }=-\frac{7}{20} t^{5/2} \csc (2 t)$$ So,  $$t=\frac \pi 4\implies\frac{dy}{dx}=-\frac{7 \pi ^{5/2}}{640}$$ Now, write the equation of the tangent as $$y-y_0=y'\,(x-x_0)$$ Using $x_0=0$ and $y_0=\frac{\pi ^{7/2}}{128}$ makes $$y=-\frac{7 \pi ^{5/2}}{640}\,x+\frac{\pi ^{7/2}}{128}$$ which, in decimal form, would write $$y=0.429353 -0.191334\, x$$
Comment: yeah, thats what i originally got, but i missed the minus sign which ended up in me questioning my logic, careless mistakes causing frustration!
Comment: @Darko. If every single time I missed a sign, I was given a dime, I should be a millionaire ! Cheers.


how to change transport config when create a email template in Laravel 7?

Question: sometimes, we use our custom platform to send emails, and we need to change some config after create an email template.
here is some code to create email template.
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class ResetPassword extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $token;
    public $url;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($token)
    {
        $this->token = $token;
        $this->url = $token;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $subject = sprintf("[%s] %s", setting('app_name'), __('Password Reset Request'));

        return $this->subject($subject)->markdown('mail.reset-password');
    }
}

// test to send an email
Mail::to( User::find(1) )->send( new UserRegistered( User::find(1)  ) );

when we use 3rd platform like Mailgun,
how should we access the transport method, like setKey,
https://github.com/laravel/framework/blob/7.x/src/Illuminate/Mail/Transport/MailgunTransport.php#L169
Thank you.
Comment: You should not be able to access the transport directly, instead of invoking set methods directly it's configured through configuration files like .env. Key on your example is not part of an email template, but rather part of connection settings for Mailgun, therefore there is no need to change it during dispatching of emails through email provider. You can set Key via example provided in [Laravel documentation](https://laravel.com/docs/master/mail#driver-prerequisites)
Comment: Thank you, Daniel, for Changing key just an example to show what I want to do,

In fact, I extend mail mange lib for using another platform, and there is a param called template-id, I need to change it every time when I create an email template.
Answer: Assuming you have setup Mailgun on their website. Now you need to follow the below steps to send mail using Mailgun
Step1:  Change mail driver in your .env file will look like this:
Change
MAIL_DRIVER=smtp

to
MAIL_DRIVER=mailgun

Step2: Add Mailgun credentials to your app services config file i.e config/services.php.
<?php

return [

    'mailgun' => [
        'domain' => 'your_domain_name',
        'secret' => 'your_mailgun_secret',
    ],

    ];

Comment: yes , thank you for your response,

how should I change other params after I creating an email template, here is some code like

```
'mailgun' => [
        'domain' => 'your_domain_name',
        'secret' => 'your_mailgun_secret',
        'template' => tmp_id',
    ],
```

how should we change the template variable?

there is a method in mailgun transport lib exactly called ** setKey **, but I have no idea when and how to access this method.
Comment: any improvement?


Why JSON parse return undefined?

Question: This is the string goes in:
"{"eventId":"program-1","eventTimesSelected":{"243759548768171":"2021-11-30T23:00:00Z"}}"

And it fails basically, why?
const startPaymentIn2 = localStorage.getItem("startPaymentIn");
let startPaymentIn3 = JSON.parse(startPaymentIn2);

Maybe only debugger plan fun with me?
Comment: just asking out of curiosity, why doesn't the string have escaped `"` in them? could this be the reason?
Comment: Does the in-string contain the outer quotation marks? If so this could be why.
Comment: Data comes from localStorage and was used `JSON.stringify` at export
Comment: It works fine, if your original string is in single quotes: https://jsfiddle.net/9xu46fm8/
Comment: Even when using the original object, _stringify-ing_ it, and parsing it, it seams to be working fine : https://jsfiddle.net/9xu46fm8/1/. Maybe your error is not in the string itself. Could you post a larger portion of the relevent code, so we can check if anything is altering the string ?
Comment: You are right @Nicolas, I stepped forward debugger, and debugger treated the output as it is not undefined, though you can see in screen shot `undefined` is written.
Answer: It's the quotations, try this instead
Javascript gets confused the three first characters, "{" is a solitary string.
You can read more about strings here.

let JSONString = `{"eventId":"program-1","eventTimesSelected":{"243759548768171":"2021-11-30T23:00:00Z"}}`

let jsonObject = JSON.parse(JSONString)

console.log(jsonObject)

Why JSON parse return undefined?


Computing: $\lim\limits_{n\to\infty}\left(\prod\limits_{k=1}^{n} \binom{n}{k}\right)^\frac{1}{n}$

Question: I try to compute the following limit:
$$\lim_{n\to\infty}\left(\prod_{k=1}^{n} \binom{n}{k}\right)^\frac{1}{n}$$
I'm interested in finding some reasonable ways of solving the limit. I don't find any easy approach. Any hint/suggestion is very welcome.
Comment: I think [this discussion](http://math.stackexchange.com/questions/125890/the-nth-root-of-the-geometric-mean-of-binomial-coefficients/125927#125927) will also interest you...
Answer: All the binomial coefficients except the last one are at least $n$, so the $n$th root is at least $n^{\frac{n-1}{n}}$, so the limit is infinity.
Comment: @QiaochuYuan Oops, thanks.
Answer: Start with the identity $$\prod_{j=1}^n {n\choose j} =\prod_{k=1}^n {k^k\over k!}.$$
Since $k^k/k!\to \infty$, the same is true of its geometric mean:
$$\left(\prod_{k=1}^n {k^k\over k!}\right)^{1/n}\to\infty.$$
Comment: an interesting and nice approach. Thanks!
Answer: As noted by Phira and Byron Schmuland, the product diverges.
I find an asymptotic expression for the product for large $n$, Eqn. (3) below.
I have found some inspiration for this solution in @sos440's answer here.
With a little work, one can show that
$$\begin{equation*}
\log \left(\prod_{k=1}^n{n\choose k}\right)^{1/n}
= -\frac{n+1}{n}\log n!
+ (n+1)\log n
+ 2 \sum_{j=1}^n \frac{j}{n}\log\frac{j}{n}. \tag{1}
\end{equation*}$$
For a derivation of (1), see below.
Using Stirling's approximation, and the fact that
$\sum_{j=1}^n \frac{j}{n}\log\frac{j}{n} \approx n\int_0^1 x \log x = -n/4$
(the error here is $O(\log(n)/n)$),
we get
$$\begin{equation*}
\log \left(\prod_{k=1}^n{n\choose k}\right)^{1/n}
\sim \frac{n}{2}+1 - \frac{1}{2} \log 2\pi n.\tag{2}
\end{equation*}$$
Therefore,
$$\begin{equation*}
\left(\prod_{k=1}^n{n\choose k}\right)^{1/n} \sim \frac{e^{n/2+1}}{\sqrt{2\pi n}}. \tag{3}
\end{equation*}$$
Clearly the product diverges.
For $n=10$, $100$, and $1000$ the left and right side of (3) agree to $12\%$, $2.0\%$, and $0.28\%$, respectively.
From (3) we get the result
$\lim_{n\to\infty} \left(\prod_{k=1}^n{n\choose k}\right)^{1/n^2} = \sqrt{e}$
for free.
(Use $\lim_{n\to\infty} x^{1/n} = 1$ for $0<x<1$.)
Derivation of Eqn. (1)
Note that
$$\begin{eqnarray*}
\log \left(\prod_{k=1}^n{n\choose k}\right)^{1/n}
&=& \log \left(\prod_{k=0}^n{n\choose k}\right)^{1/n} \\
&=& \frac{1}{n} \sum_{k=0}^n \log {n\choose k} \\
&=& \frac{1}{n} \sum_{k=0}^n \left(\log n! - \log k! - \log (n-k)! \right)\\
&=& \frac{1}{n} \left((n+1)\log n!  - 2 \sum_{k=0}^n\log k!  \right).
\end{eqnarray*}$$
But
$$\begin{eqnarray*}
\sum_{k=0}^n\log k! &=& \sum_{k=1}^n\log k! \\
&=& \sum_{k=1}^n \sum_{j=1}^k \log j \\
&=& \sum_{j=1}^n \sum_{k=j}^n \log j \\
&=& \sum_{j=1}^n (n+1-j) \log j \\
&=& (n+1)\sum_{j=1}^n \log j - \sum_{j=1}^n j (\log j -\log n + \log n) \\
&=& (n+1)\log n! - \frac{n(n+1)}{2} \log n - \sum_{j=1}^n j\log\frac{j}{n}.
\end{eqnarray*}$$
Eqn. (1) follows immediately.
Some key identities:
$$\begin{eqnarray*}
\log n! &=& \sum_{k=1}^n \log k \\
\sum_{k=j}^n 1 &=& n+1-j \\
\sum_{k=1}^n k &=& \frac{n(n+1)}{2} \\
\sum_{k=1}^n \sum_{j=1}^k a_{j k} &=& \sum_{j=1}^n \sum_{k=j}^n a_{j k}
\end{eqnarray*}$$
Comment: Great answer. I was going to suggest maybe accelerating the $1/n$ would make it converge: interesting result!
Comment: @PeterTamaroff: Thanks, Peter. As you probably know, if we hit the product with another power of $1/n$ we get [this problem](http://math.stackexchange.com/questions/125890/the-nth-root-of-the-geometric-mean-of-binomial-coefficients/). Cheers!
Comment: @oenamen: excellent work! Thanks!
Comment: @Chris: Thank you for the interesting question!
Comment: @oenamen: your answer was far more interesting than my question, a real lesson to study! Thanks!


How do I change a machine name in DNS

Question: I'm trying to change my computer's name in DNS so that others on the same subnet can refer to it by its new name -
however, whatever changes I make in /etc/hosts and by using 'hostname' to use the new_host_name and shutting-down and starting, DNS still gives me the old host name.

I'm running Ubuntu 11.10 On...c
All my colleagues/partners are on the same 172.xx.30.xxx subnet

Q1. How do I make the change permanent in DNS?
Q2. Will this ensure that other computers can see my computer with the new *new_host_name*?
Thanks in advance for any guidance and answers,
Best,
Shailen
Comment: Where is the name being resolved?  If it is being resolved by the upstream nameserver, you'll have to have it changed there.
Comment: 0. I have a nameserver defined in /etc/resolv.conf: would it have to be changed there?
1. What exactly does 'having it changed there' entail? (I don't know enough to be able to tell my Windows IT guy, :-(, :-))
Comment: If you want other hosts on the network to automatically see your computer with the new host name (without modifying anything on their system), you will have to talk to your IT guy.  It is possibly the DNS server in /etc/resolv.conf that needs to be updated, but it could also be the DHCP server as well.  Windows can use NetBIOS names to resolve local machines, so that is another fish muddying the waters.  (bottom line, talk to your IT guy)
Comment: Thanks!
I talked to him,but he's soo 'booked up with other stuff' slow,    :-(, will just have to wait, and get the rest of the team to use IP's for now, I suppose.
Answer: You should edit /etc/hosts and /etc/hostname to make it persistent between boots.
Comment: Thanks for the tip, didn't fly, though, because there're MAC address foul ups across the DNS and DHCP servers ...

How do I change a machine name in DNS


How to not highlight values in comments in Emacs?

Question: I want to highlight true and false values in some configuration files.  I've
done it this way:
(defun my/highlight-in-properties-files ()
  "Highlight regexps in PROPERTIES files."
  (when (string-match-p ".properties" (file-name-nondirectory buffer-file-name))
    (highlight-regexp "true" 'hi-green)
    (highlight-regexp "false" 'hi-pink)))

But it also highlight those values in comments:

Is there a way to exclude those highlightings?
UPDATE -- highlight-regexp is an alias for 'hi-lock-face-buffer' in 'hi-lock.el'.  And string-match-p is a compiled Lisp function in 'subr.el'.
Comment: Could you please add the value of `highlight-regexp` to the question?
Comment: And also, add `string-match-p`
Answer: You can just add the regexps via font-lock-add-keywords, which will already account for the comment syntax in the buffer, eg.
(defun my-font-lock-additions ()
  (require 'hi-lock)                    ; fonts
  (font-lock-add-keywords
   nil
   '(("\\btrue\\b"  . 'hi-green)
     ("\\bfalse\\b" . 'hi-pink)))
  (font-lock-flush))

And call (font-lock-refresh-defaults) to revert back to OG settings.
Sticking to a purely regexp solution with highlight-regexp will undoubtebly produce some mistakes in odd cases, but, I think just customizing your regex to check for a comment prefix would probably work well enough as well,
(defun my/highlight-in-properties-files ()
  "Highlight regexps in PROPERTIES files."
  (when (string-match-p ".properties" (file-name-nondirectory buffer-file-name))
    (comment-normalize-vars)            ; ensure comment variables are setup
    (let ((cmt-re (format "^[^%s]*" (regexp-quote (string-trim comment-start)))))
      (highlight-regexp (format "%s\\(\\_<true\\_>\\)" cmt-re) 'hi-green 1)
      (highlight-regexp (format "%s\\(\\_<false\\_>\\)" cmt-re) 'hi-pink 1))))

Answer: A way would be to simply add a $ at the end of your regex to not match the comments, as the true/false are always at the end, while those in comments are always situated in the middle of a sentence
(defun my/highlight-in-properties-files ()
  "Highlight regexps in PROPERTIES files."
  (when (string-match-p ".properties" (file-name-nondirectory buffer-file-name))
    (highlight-regexp "true$" 'hi-green)
    (highlight-regexp "false$" 'hi-pink)))


Select filter doesn't work with cellTemplate, angular ui-grid

Question: I'm working with angular ui-grid library and faced with the problem. I cannot understand how to apply filter for cell with multiple values.
Columns category has an inner array, which I display thru cellTemplate like this
cellTemplate: "
{{item.name}}
"

also in category column I have select filter with dynamic array, which I'm getting thru services
 filter: {
                type: uiGridConstants.filter.SELECT,
                selectOptions: $scope.categories
            },

where $scope.categories comes from
 lovServices.categories().then(function (result) {
                angular.forEach(result, function (value) {
                    $scope.categories.push({
                        value: value.id,
                        label: value.name
                    });
                });
            });

But when I'm selecting any category filter it shows me an empty grid, I understand that grid filter cannot find any value, but the reason of it I cannot understand.
Could anybody help me to find my mistake? I appreciate any help.
Code:
    app.controller('MainCtrl', function ($scope, $http, uiGridConstants, lovServices) {

        $scope.categories = [];

        // Get Grid Data
        var getData = function () {
            lovServices.eventTypes()
                .then(function (response) {
                    //Initial Data
                    $scope.gridOptions.data = response;
                });
        };
        var getOptions = function () {
            lovServices.categories().then(function (result) {
                angular.forEach(result, function (value) {
                    $scope.categories.push({
                        value: value.id,
                        label: value.name
                    });
                });
            });
        };

        // Ui-Grid Options
        $scope.gridOptions = {
            enableFiltering: true,
            rowHeight: 60
        };

        // Ui-Grid Columns
        $scope.gridOptions.columnDefs = [
            {
                displayName: 'Name',
                field: 'name',
                sort: {
                    direction: uiGridConstants.ASC
                }
            },
            {
                field: 'description',
            },
            {
                field: 'category',
                enableSorting: false,
                filter: {
                    type: uiGridConstants.filter.SELECT,
                    selectOptions: $scope.categories
                },
                cellTemplate: "
{{item.name}}
"
            }
        ];

        $scope.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;

        };

        //Get data
        getData();
        getOptions();

    });

This is a plunker with my problem
Answer: Because the data you are filtering against is an array, and not a flat value, it must be compared through iteration.
That is to say, a anonymous function must be supplied as the condition key to the filter object, in order to iterate through the column values and figure out which one matches the search term.
Documentation
Example:
filter: {
    condition: function(searchTerm, cellValue, row, column) {
        var filtered = false;
        for (var i = 0; i < cellValue.length; i++) {
            filtered = cellValue[i].id === searchTerm;
            if (filtered) {
                break;
            }
        }
        return filtered;
    },
    type: uiGridConstants.filter.SELECT,
    selectOptions: $scope.categories
},

Updated plunkr
Comment: The condition, that's it I couldn't understand how to apply, I have tried to impact on it thru for loop in filterChanged at the grid core but did't get any success. Thank you a lot for a help! I have to read docs more careful.


I'm getting a "test interstitial" message, and the music is gone — How do I fix this?

Question: After the last update to TDS, my music is gone. Also, I'm getting a "test interstitial" message when powering on the game. How do I fix these issues?
Comment: Can you post a screenshot of this?  I know TDS now has ads when you launch the game that are directly related to TDS gameplay.
Answer: I got the same once. I believe it was a placeholder for an ad. It appeared the same as the pop-up ads I've seen when starting up the game.


Why has my wood panelling in my shed expanded and popped out? How can I fix it?

Question: Last summer we bought a shed and panelled inside with tongue and groove panelling. We put up damp proof and insulation first and then the panels on top. We used panel pins on every third board.
Over the winter it seems the wood has expanded causing it to push out in places. How can we fix this and can we prevent it happening again?
Comment: That's very odd. Wood usually _contracts_ in winter. Is "winter" where you are actually warm, but humid?
Comment: Any pics to show the extent?
Comment: Is the space temperature controlled?
Comment: Sounds  like moisture trapped in the insulation.
Comment: To add pics, click the [edit] link, then simply drag & drop the pics into your post. The site will upload & host them for you. If you can't do that, post them to imgur.com or similar and paste the links in the comments, someone will embed them for you.
Answer: Your shed may have shifted. I have a larger shed that had this wood veneer nailed to the walls, and it's shifted somewhat, which warps the paneling.
I would make sure your footings and walls are still level. If they aren't, you can use a car jack (use a car stand for a safety backstop) to raise the shed and add supports to raise it back to level.
Comment: Thank you for your replies! I'm in Northern Ireland, so our winters are wet and around -3C to 12C. Could have made it damp inside shed. We stapled black damp proof to the shed walls and then packed the space with insulation that came in a thick roll before panelling. Is that the correct order? I can't seem to add a photo. It is worse around the door and window. We haven't got any hearing in the shed. If we can fix it we will air it out more often and use a space heater occasionally on it throughout winter. Would this help? Do you think the wood will shrink again as the weather warms?


Is it possible to completely disable Grub timeout?

Question: I am setting up a dual boot install for my wife's computer. I would like to disable the timeout for selecting OS that defaults to Ubuntu so the computer wont boot without making a selection. (IE. GRUB_TIMEOUT=INFINITE) Is it just a simple case of leaving it blank or #out the line in /etc/default/grub ? I want it so my wife can choose OS easily on her newly Dual booting PC.
I would also like to know if updating Burg after this would keep the change - as the big graphics of the OS's are a little more noob friendly.
Answer: Edit /etc/default/grub (with root privileges), change GRUB_TIMEOUT value from 10 to -1, save the file and then run sudo update-grub. Reboot and now you have infinite time to choose the OS.
While this works in GRUB, it doesn't work with BURG, and you'll have to change GRUB_TIMEOUT value to some large number like 120 seconds to wait before booting into any OS and run sudo update-burg to reflect the changes. Also note that this change must be made to file /etc/default/burg as BURG doesn't consider options set in /etc/default/grub
Comment: Excellent answer. Thank you very much. I set it to 600 seconds with Burg and it's awesome.
Comment: Which versions of Ubuntu does this apply to?
Answer: Setting timeout to -1 will make GRUB wait infinitely.
By that I mean that you will be required to manually select an entry and hit Enter before launching any OS.
Answer: When running update-grub a warning says that setting grubtimeout to a non zero number is no longer supported. No matter what I changed the grub timeout value to timeout stayed at 10. If you are having this problem the workaround is editing the grub.cfg file located in /boot/grub. Near the end the script says IF TIMEOUT = 0 then timeout= 10. Change 10 to -1. No more countdown.

gksu gedit /boot/grub/grub.cfg
Find the part of the script around the end that says IF TIMEOUT = 0 then timeout= 10. Change 10 to -1.

This is a workaround it will be reverted if update-grub is ever run. Not permanent unless update-grub is not manually run.
(Works on 14.04.)
Answer:
Edit /etc/grub.d/30_os-prober file:

sudo gedit /etc/grub.d/30_os-prober

Find

if [ "\${timeout}" = 0 ]; then
  set timeout=10
fi

and replace set timeout=10 with set timeout=0
Save and update grub config:

sudo update-grub

It worked for me, on Ubuntu 19.10
Comment: @BalázsBörcsök, files stored in the `/etc/grub.d/` directory are not generated files. On the contrary, these are source scripts used to generate `/boor/grub/grub.cfg`. You can read the contents of `/etc/grub.d/README`. The problem there is that script called `30_os-prober` is written in such a way that it effectively forces GRUB timeout of 10 seconds if another OS is found. See the second code excerpt from Maxim Mazurok - the `timeout` variable is set in global scope of the grub.cfg script AFTER setting the timeout variable globally to value defined with `GRUB_TIMEOUT` in `/etc/default/grub`.
Comment: It is not recommended to edit the generated script. Use the `grub-mkconfig -o /boot/grub/grub.cfg` or the `update-grub` script after editing the `/etc/default/grub` configuration file. Just add `GRUB_TIMEOUT=-1` to it.


Does every LCS has a convex balanced local base?

Question: Does every LCS--locally convex (topological vector) space has a convex balanced local base?
Then it implies every LCS is topologized with a countable number of separating seminorms. So  there seems to exist a counterexample.
Answer: This is true. See corollary of theorem 1.14 in W. Rudin Functional analysis.
This property doesn't imply LCS have a countable separating family of seminorms.
Answer: Yes, any locally convex space has a neighborhood basis around zero consisting of balanced convex sets (Wikipedia seems to take this as the definition but as far as I know including ``balanced" in the definition is non-standard, and in any case can be derived from the more general definition requiring the existence of a neighborhood basis around zero consisting of convex sets).
But this says nothing about first-countability. I'm not sure how you're drawing this conclusion. Not all locally convex spaces are metrizable (a first-countable, Hausdorff locally convex space is necessarily metrizable, and this is equivalent to its topology being defined by a countable set of seminorms whose common kernel is zero).


Understanding unit vector arguement for proving gradient is direction steepest ascent

Question: Why is gradient the direction of steepest ascent?
In this question and it's many answer, people argue gradient is direction of steepest ascent by defining a random unit vector and then saying that dot product of this with gradient is maximum when both of them are in the same direction. But how does this prove that gradient is direction of steepest ascent
And, it's not just me, the comments also involve asking the person who answered how the heck his arguement proves it. So, why is it so?
Further in the book, Electricity and magnetism by purcell, in page 64 end to page 65 start, he talks of gradient of a function dependent only distance from origin i.e a radial function f(r) and argues the shortest step which we can make to change f(r) to f(r+dr) is move in the radial direction. Ok, this some what makes sense to me but how do I extend this intuition for regular derivatives and further use this to understand the answer I showed before?
Answer: We can first ask what is meant by the direction of "steepest ascent" for a function $f(\vec{x})$ around $\vec{x}_0$? What we usually mean by this is the direction given by a vector $\vec{\delta}$ so that a minute (infinitesimal step) in that direction gives the greatest increase of the function while keeping the length of the minute step fixed. You can think of the following process as one that converges to finding the direction of steepest ascent:

First start with all unit vectors $\vec{\delta}$, and ask: of all the possible $\vec{\delta}$, which one maximizes $f(\vec{x}_0 + \vec{\delta})$? Let the answer be $\vec{\delta}_1$.

Then reduce the length of $\vec{\delta}$ to say, $0.1$ and ask the same question: of all such possible $\vec{\delta}$, which one maximizes $f(\vec{x}_0 + \vec{\delta})$? Let the answer be $\vec{\delta}_1$.

Continue to reduce the length of $\vec{\delta}$ to be fixed at some number arbitrarily close (but not equal) to zero, and ask the same question, thereby constructing an infinite sequence $$\vec{\delta}_1, \vec{\delta}_2, \vec{\delta}_3, \cdots$$ For differentiable functions, the direction each $\vec{\delta}_i$ as $i \to \infty$ points in will approach a well-defined limit!

The limit of this infinite process can then be thought of the direction of steepest ascent. It maximizes the increase of the function per unit distance traveled around the point $\vec{x}_0$, in the limit where the distance traveled from $\vec{x}_0$ is very small.
To find exactly what direction $\vec{\delta}$ approaches, we can use the idea behind defining the derivative, which is to provide a linear approximation of a function around a point. The idea is that for a multivariate function $f(\vec{x})$ that has a gradient $\nabla f$, moving an infinitesimal amount $\vec{\delta}$ from $\vec{x}_0$ to $\vec{x}_0 + \vec{\delta}$ changes the value of the function from $f(\vec{x}_0)$ to $f(\vec{x}_0) + \nabla f(\vec{x}_0) \cdot \vec{\delta}$. Even though there will always be corrections on the order of $\vec{\delta}^2$ and beyond, they are negligible in the limit as $\delta \to \vec{0}$. That's because every differentiable function can be approximated as linear in the neighborhood of any arbitrary point in its domain.
The problem then becomes to find $\vec{\delta}$ such that $\nabla f(\vec{x}_0) \cdot \vec{\delta}$ is maximized (since this is the increase $f(\vec{x}_0 + \vec{\delta}) - f(\vec{x}_0)$ that is recorded. But remember there's a caveat: the length of all $\vec{\delta}$ must be held fixed. Because of this, finding the vector $\vec{\delta}$ that maximizes $\nabla f(\vec{x}_0) \cdot \vec{\delta}$ is equivalent to finding the unit vector $\hat{\delta}$ that maximizes $\nabla f(\vec{x}_0) \cdot \hat{\delta}$. From there you can check that choosing $\hat{\delta}$ to be the unit vector in the direction of $\nabla f (\vec{x}_0)$ maximizes this quantity.
Comment: Really nice answer using an iterative limit. +1 from me
Comment: this answer changes everything
Comment: I wish there was a continuation to the last part: "choosing $\hat{\delta}$ to be the unit vector in the direction of $\nabla f (\vec{x}_0)$ maximizes this quantity" - why?
Answer: Given a differentiable function $f$ of several variables and a point $P,$ recall that the directional derivative of $f$ at the point $P$ in the direction of a unit vector $\mathbf u$ is defined to be $D_\mathbf u f(P) = \nabla f_P \cdot \mathbf u,$ where $\cdot$ is the usual dot product and $\nabla f_P$ is the gradient of $f$ evaluated at the point $P.$ By the geometric interpretation of the dot product, we have that $D_\mathbf u f(P) = ||\nabla f_P|| \cos \theta,$ where $\theta$ is the angle between $\nabla f_P$ and $\mathbf u.$
Consequently, the directional derivative $D_\mathbf u f(P)$ is maximized whenever $\cos \theta = 1.$ But this says that the angle between $\nabla f_P$ and $\mathbf u$ is $\theta = 0,$ i.e., $\nabla f_P$ and $\mathbf u$ point in the same direction.
Crucially, given a surface $z = f(x, y),$ the directional derivative of $f$ at the point $P$ in the direction of a unit vector $\mathbf u$ can also be written as $D_\mathbf u f(P) = \tan \psi,$ where $\psi$ is the angle of inclination from the point $P$ on the surface $z = f(x, y).$ Under this interpretation, maximizing $D_\mathbf u f(P)$ also maximizes the angle of inclination from the point $P$ on the surface: as $\mathbf u = \frac{\nabla f_P}{||\nabla f_P||}$ maximizes $D_\mathbf u f(P),$ it maximizes the steepness of ascent.
Comment: The directional derivative relies on $\nabla$ in the definition though... This argument seems rather circular.
Comment: Yes, the directional derivative is defined in terms of the gradient. What is the problem?


Is it always possible to always choose coordinates so that the curvature is locally zero?

Question: I would have thought that this was completely possible as manifolds are so "soft" and the only problems would have been global ones (like Gauss Bonnett etc). But I've never seen the phrase "of course it is always possible to find coordinites in an some open neighbourhood around a point so that the curvature is zero". Also people seem to be very excited about normal coordinites as they have vanishing curvature at a single point, so now I am starting to suspect perhaps it is NOT true. But maybe it is and it's just not very useful so nobody cares. Thoughts?
Edit: I initially thought that vanishing christoffel symbols implied vanishing curvature but this is not true at all. As pointed out in comments it is the christoffel symbols that vanish NOT the curvature.
Comment: It's the Christoffel symbols that vanish at the center of a normal coordinate system, *not* the curvature!
Comment: Curvature requires one more derivative. :)
Comment: Thanks Ted, to be honest I thought the vanishing of the christoffel symbols implied vanishing curvature but I can see now that this was a terrible thing to think. I will edit
Answer: No, this is not possible. The curvature (tensor and it's derived quantities) are either intrinsic geometric quantities, i.e. they are preserved by coordinate changes, or extrinsic ones (depend on an embedding into an ambient manifold), but here the same statement holds.
Comment: Wow, this is literally amazing to me!! I mean, now that you say it of course it's a tensor and so the answer is obvious but I still find it totally unintuitive for some reason. Thank you!!
Answer: The "softness" of the manifolds guarantees that given a smooth manifold $M$ and a point $p \in M$, you can always choose a Riemannian metric $g$ such that $p$ has a flat open neighborhood (and in particular, with respect to any choice of coordinates around $p$, the curvature tensor will be zero). This can't always be done globally just like you said because of topological restrictions.
However, like Thomas wrote, if you start with a Riemannian manifold $(M,g)$ and hold the metric fixed, you can't generally choose local coordinate systems with respect to which the curvature tensor is zero.
Comment: To emphasize the main point of this answer in the intuitive terminology of the question: A Riemannian metric makes a manifold considerably less "soft" than it would be without the metric.


how to manage CPU resources

Question: In a producing and consuming application, let's say producting takes one cpu cycle and consuming takes 3 avarage cpu cycles. Then how do we manage to keep equal number of productions and consumptions boundry. this is a problem I imaginge while I was studying threads.
If you have any idea to implement this with Java please share your knoweledge.
Comment: Concurrency is a complicated subject, it's not just a matter of CPU cycles, take a look at this thread http://stackoverflow.com/questions/13581575/system-not-scaling-to-support-concurrent-users/13583213#13583213 and I'd suggest reading the book I recommend there.
Comment: Have you looked at BlockingQueue? http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html
Answer: You have to design your system so that you consumers can keep up with your producer in the long run.  Most producers are bursty and if you use a queue it doesn't matter that for very short periods they are producing faster than your can consume.  If this is not the case you can

have multiple consumers.
drop or combine produced messages to reduce the load on the consumer.
push back on the producer to slow down.

how to manage CPU resources


What are the six basic primitives in Turing Complete

Question: I am listening the edX lesson, and the professor stresses that every machine able to perform those six basic primitives can be called Turing Complete. But what are the six basic primitives?
Answer: The six basic operations/primitives that gives a language Turing completeness are:

Right: Move the Machine's head to the right of the current square
Left: Move the Machine's head to the left of the current square
Print: Print a symbol on the current square
Scan: Identify any symbols on the current square
Erase: Erase any symbols presented on the current square
Nothing/halt: Do nothing

You can learn more at Alan Turing reference web site
and/or watch a small video about it.
Comment: for those that want to try writing something using the above primitives this esoteric language has been created: https://en.wikipedia.org/wiki/Brainfuck
Comment: Is this about programming languages, or Turing Machines? They're not the same thing.
Comment: But, these are not programming language operations. These are turing machine operations.
Comment: @Marcin This is about Turing O-Machines that are implemented as programming languages.
Comment: @Marcin I'm sorry, it is not. I have studied programming languages for a while now. I wouldn't answer if I didn't study that.
Answer: They are the basic of Turing Machine and are composed of
Right: Move the Machine's head to the right of the current square
Left: Move the Machine's head to the left of the current square
Print: Print a symbol on the current square
Scan: Identify any symbols on the current square
Erase: Erase any symbols presented o the current square
Nothing/HALT: Do nothing
The idea is that with those six primitives you can program anything.
Comment: @StaticX When I started typing there wasn't anything + this question is basically "Let me google it for you" he could have found the answer within the first 3-4 results without any previous knowledge in machine learning
Comment: @Wald I agree. I usually research much more before posting a question here. Sadly, many people don't.
Comment: This is the same as the answer I posted before.
Comment: @StaticX Yes, but your answer is misleadingly - arguably incorrectly - worded.
Answer: Right move ,Left move ,Read ,Write ,erase and donothing
Comment: This answer has nothing to add compared to the accepted one that has been posted years ago. It should be removed.
Comment: Please add further details to expand on your answer, such as working code or documentation citations.


anchor tag assigned span tag inner html

Question: I have dynamically assigned anchor tag between span tag using javascript.
But anchor tag href formed incorrectly.
javascript
var HF1Id , HF2Id , SpanId ,
HF1Id = '<%=Request("HF1Id") %>' ;
HF2Id = '<%=Request("HF2Id") %>' ;
SpanId = '<%=Request("SpanId")  %>';

var a = "View";

alert(a);

opener.document.getElementById('<%=Request("SpanId")%>').innerHTML = String(a);

alert(opener.document.getElementById('<%=Request("SpanId")%>').innerHTML);

First Alert Shows correct order as per given.
But second alert shows incorrectly order.
Comment: Please can you provide the output of the two alerts.
Answer: I am assuming that the output being passed through innerHTML should be html, however you are converting it to a string with String(a);
From w3schools:
The String() function converts the value of an object to a string.
Also your string should use only single apostrophes as the are surrounding the text with double quotes meaning the apostrophes don't need to be escaped.
"<a id='anc'  href='javascript:void(0)' tabindex='-1' alt='Download'"
Comment: When removing one apostrophes it works fine.. Thanks

anchor tag assigned span tag inner html


Ubuntu 20.04 LTS xorg-dev repos busted is there work around?

Question: Fresh install of Ubuntu 20.04 LTS with all updates applied. Running in Oracle VirtualBox VM.
ubuntu-bug is completely busted. When I tried to report it took me to the Web site and demanded I enter a package name, would not allow "I don't know" button to be checked. When trying to search for a package there were no packages in the list. Nice, very nice.
The repos for 20.04 LTS have xorg-dev and libglu1-mesa-dev completely broken at least as far as dependencies are concerned. Many many of the dependencies fail just like this:
developer@a-developer-VirtualBox:~$ sudo apt-get install libfontenc-dev zlib1g-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 zlib1g-dev : Depends: zlib1g (= 1:1.2.11.dfsg-2ubuntu1) but 1:1.2.11.dfsg-2ubuntu1.2 is to be installed
E: Unable to correct problems, you have held broken packages.

The needed -dev package is forced to depend on a version that is no longer the one the repos will try to install.
developer@a-developer-VirtualBox:~$ sudo apt-get install libglu1-mesa-dev libgl1-mesa-dev libgl-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libgl-dev : Depends: libgl1 (= 1.3.1-1) but 1.3.2-1~ubuntu0.20.04.1 is to be installed
             Depends: libglx-dev but it is not going to be installed
 libgl1-mesa-dev : Depends: libglvnd-dev but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Right now the official repo is in such a state nobody can install xorg-dev libglu1-mesa-dev. One cannot even report bugs.
Is there a work around for getting xorg-dev and libglu1-mesa-dev installed with all development dependencies?
We chose Ubuntu 20.04 LTS because the LTS releases aren't supposed to have things like this in the repos.
The following packages have unmet dependencies:
 libglib2.0-dev : Depends: libglib2.0-0 (= 2.64.6-1~ubuntu20.04.3) but 2.64.6-1~ubuntu20.04.4 is to be installed
                  Depends: libglib2.0-bin (= 2.64.6-1~ubuntu20.04.3)
 libmount-dev : Depends: libmount1 (= 2.34-0.1ubuntu9) but 2.34-0.1ubuntu9.1 is to be installed
                Depends: libblkid-dev but it is not going to be installed
 uuid-dev : Depends: libuuid1 (= 2.34-0.1ubuntu9) but 2.34-0.1ubuntu9.1 is to be installed
 zlib1g-dev : Depends: zlib1g (= 1:1.2.11.dfsg-2ubuntu1) but 1:1.2.11.dfsg-2ubuntu1.2 is to be installed
E: Unable to correct problems, you have held broken packages.

Answer: I must have been caught up in some kind of push. Seems to be fixed now.
Comment: No, your other question didn't answer it. The default repos were in place. I simply tried a few hours later and it worked. Either Canonical was pushing updates out or the mirrors were out of sync. You should NOT have closed this question.


square root commutes with multiplication for positive elements in a $C^*$ algebra?

Question: Let $A$ be a unital $C^*$ algebra.  If $z\in A$ is invertible, then so is $z^*$ and $z^*z$ and, furthermore, $z^*z$ is positive, so we can define using the functional calculus $|z|=\sqrt{z^*z}$.  My book then claims that $|z|$ is invertible with inverse $\sqrt{(z^*z)^{-1}}$.  Why is $|z|*|z|^{-1}=1$?  To me this looks like trying to say that $\sqrt{z^*z}*\sqrt{(z^*z)^{-1}}=\sqrt{(z^*z)(z^*z)^{-1}}=\sqrt1=1$, but I don't see why you can pull the product inside the square root like you can for reals (I don't know if this is actually how to prove the claim).
I don't see how some of the basic properties about continuous functions pass through the functional calculus and still hold inside of $A$.
Comment: Probably $a$ and $b$ have to commute, if you want to deduce that $\sqrt a \sqrt b = \sqrt {ab}$.
Comment: Maybe if you're looking to have that $\sqrt{ab}=\sqrt{ba}$, but otherwise I don't see why $ab=ba$ is important.
Comment: It also think it is not always true that $ab$ is positive (or normal), if $a$ and $b$ are.
Comment: edited for clarity
Answer: By definition, the (continuous) functional calculus associated to a normal operator $x$ is a continuous $*$-homomorphism $\varphi:C(\sigma(x))\to A$ sending the inclusion function $\sigma(x)\to\mathbb{C}$ to $x$, where $\sigma(x)$ is the spectrum of $x$.  In your case, $x=z^*z$, and $|z|$ is defined as $\varphi(f)$ where $f$ is the square root function.  Similarly, $|z|^{-1}$ is $\varphi(g)$, where $g$ is the function $g(t)=1/\sqrt{t}$ (which in $C(\sigma(x))$ since $0\not\in\sigma(x)$).  So $|z|\cdot|z|^{-1}=\varphi(f)\varphi(g)=\varphi(fg)$.  But the pointwise product of the functions $f$ and $g$ is just the constant function $1$, so $\varphi(fg)=\varphi(1)=1$.
More generally, the entire point of the functional calculus is that you can do everything "like you can for reals" (as long as you are only applying functions to a single normal operator, or more generally a commutative $*$-subalgebra), because addition and multiplication in $C(\sigma(x))$ are just pointwise addition and multiplication of ordinary numbers.
(If your definition of $|z|$ and/or $|z|^{-1}$ is not via the functional calculus on $x$, you can easily verify that the above functional calculus definitions meet the criteria of whatever other definition you have and thus coincide.)
Answer: Note that
 $$\lvert z \rvert ^{-2} = ( \lvert z \rvert ^2)^{-1} = (z^*z)^{-2}
$$
Taking square roots gives the result.
Comment: What do you mean by $|z|^{-2}$, i.e. what is raising to the power -2?
Comment: By that, I mean $(\lvert z \rvert^{-1})^{2}$.
Answer: Let $a=z^*z$ and $b=(z^*z)^{-1}=z^{-1}(z^*)^{-1}=z^{-1}(z^{-1})^*$. Then $a$ and $b$ are positive commuting elements for which $ab=1=ba$. Let $\sqrt{a}$ and $\sqrt{b}$ be the positive square roots of $a$ and $b$. Then $\sqrt{a}\sqrt{b}=\sqrt{b}\sqrt{a}$ because $\sqrt{a}$ and $\sqrt{b}$ are limits of polynomials in $a$ and $b$, respectively. Hence, $\sqrt{a}\sqrt{b}=\sqrt{b}\sqrt{a}$ is positive and
$$
            (\sqrt{a}\sqrt{b})^2 =ab=1.
$$
Therefore
$$
              (\sqrt{a}\sqrt{b}-1)(\sqrt{a}\sqrt{b}+1)=0.
$$
Because $\sqrt{a}\sqrt{b}$ is positive, then $\sqrt{a}\sqrt{b}+1$ is invertible. Hence $\sqrt{a}\sqrt{b}-1=0$, which is what you wanted to show:
$$
         \sqrt{a}^{-1}=\sqrt{b} \\
      \sqrt{z^*z}^{-1} = \sqrt{(z^*z)^{-1}}.
$$


Can't Understand The Program and The Output

Question: #include <iostream>
using namespace std;
int main()
  {

    int i=10, j=5;
    int modResult;
    int divResult;
    modResult = i%j;
    cout << modResult;
    divResult = i/modResult;
    cout << divResult;
    return 0;
}

I can't understand the code above. I got this one from my referral book in debugging exercise. I have debugged the program. But I can't Understand what is it and how it works so plz help.
Answer: In the above program, you've imported iostream, which is a header file that is part of the C++ standard library. You can have a look at this answer if you want to know why using namespace std is used in your code.
int main() is a function that has a return type of an integer.
You've declared two integers i and j which store 10 and 5 respectively. 'modResult' and 'divResult' are two pre defined integers where you can store computed values during program execution.
modResult stores the reminder of the result 10/5, which is zero as the reminder is 0 in this case.
divResult stores the quotient of the result 10/5, which is 2 in the case you divide i by j i.e. i/j but i divided by modResult is the case of infinite.
These two values are printed using cout>> statement.
Good luck with your learning C++. :)
Comment: You'd get `+inf` if the operands were `float`s, but integer division by zero is undefined behaviour.
Comment: Thanks It was Really very Helpful And I easily Understood The Program


Two identical TF2 items with different levels?

Question: I discovered two items with different levels. They have identical names, symbols, and descriptions in my backpack:

Why are the levels different? Are the items identical? If there is a difference, what is it?
Comment: There was a time when item levels of weapons were random. These days, weapon item levels are fixed, but cosmetics have random levels.
Comment: @Powerlord I read about cosmetics that they have a level if there are fewer than 100 people who crafted the item before you did. If your item's number is bigger than 100, no number is displayed. But there apparently are 3rd party tools which can display the number anyways. I wouldn't call that random.
Answer: According to TF2 Wiki:

The majority of items in Team Fortress 2 have levels associated with them. Levels, viewed with the item name in the loadout menu, are purely cosmetic and do not modify the effectiveness of any weapon or item.

The item level is purely cosmetic.  It serves no other purpose.  So basically, yes these weapons are the same.


How do I route to a different angular page when the window size is below 800px?

Question: I am creating an Angular 8 browser that displays a table. Since there are many columns, when that window size is too small, I would like to display a table with less columns that can be expanded downward to show more information. I have both of these different layouts already created in different html files. Is there a way to route to the file with the expanded-rows view once the screen reaches a certain size and then route back to the file with the regular table view when the screen is large enough? How is this done?
Comment: What have you tried so far?
Comment: I wouldn't route to a new page on window resize. I'd listen to the window resize it in your parent component and then use an ngIf or similar to switch between large / small table components. Navigation seems overkill for what is really a deletion / addition of columns on the same table.
Answer: You can do so in the parent component to load a suitable child component using BreakPointObserver in the following manner.
import {BreakpointObserver} from '@angular/cdk/layout';

...
constructor(private bpo: BreakpointObserver){}

...
ngOnInit(){

    // Listen to changes in screen width
    this.bpo.observe(['(min-width: 800px)'])
    .subscribe(result => {
        if (result.matches) {
        // Navigate to larger view
        } else {
        // Navigate to smaller view
        }
    });
}

Check this StackBlitz to play around. Change the screen size of the output window to see that larger or smaller component is loaded accordingly.
EDIT:
To unsubscribe, you need to store the subscription and unsubscribe on the subscription, like  -
private bpoSubscription: Subscription;

....
this.bpoSubscription = this.bpo.observe(['(min-width: 800px)'])
                       .subscribe(result => {
                         if (result.matches) {
                         // Navigate to larger view
                         } else {
                         // Navigate to smaller view
                         }
                        });

...
ngOnDestroy(){
   this.bpoSubscription.unsubscribe();
}

Check this updated Stackblitz
Comment: Thanks, this worked! How do I make it check this page only for the min-width? It is checking all pages and navigating to the smaller view for my other pages that are not related to this table with the different view options.
Comment: If you `unsubscribe` from the listener attached in the `ngOnDestroy` of that particular component, that should do the trick.
Comment: I received this error :              core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[ListComponent -> Subscription]:
  StaticInjectorError(Platform: core)[ListComponent -> Subscription]:
    NullInjectorError: No provider for Subscription!
NullInjectorError: StaticInjectorError(AppModule)[ListComponent -> Subscription]:
  StaticInjectorError(Platform: core)[ListComponent -> Subscription]:
Comment: Updated in the answer. Check if that works for you @BDev14


Passing a number to a python script

Question: I am working in Linux using Ansible.
I am trying to run a script from a playbook, but I need to pass the script a few arguments: a string and 2 numbers. The first number is the number of times I need to retry to run the script, the second number variable is the retry attempt (which comes from a implement retry counter).
cat playbook.yml
---

- name: Increment variable
      ansible.builtin.set_fact:
        attempt_number: "{{ attempt_number | d(0) | int + 1 }}"

- name: Running Script
      command: "{{ my_dir }}/script.py {{ string }} {{ max_retries }} {{ attempt_number | int }}"

The python script looks like this:
cat script.py
var1=sys.argv[0]
var2=sys.argv[1]
var3=sys.argv[2]

print "String %s" % var1
print "Num1 %d" % var2
print "Num2 %d" % var3

First I am just trying to check If the variable are being passed to the python script but I am getting this error:

"  File "", line 6, in ", "TypeError: %d format: a
number is required, not str"]

What am I doing wrong? How can I change this, so my python script receive all the 3 parameters?
Comment: The parameters are all strings. So just wrap them in `int()`, like `int(var2)` or `int(sys.argv[1])`. Although a bigger problem is that this script is written in Python 2, but that's been deprecated for over 3 years. You generally should use Python 3 unless you have a really specific reason to dig up Python 2.
Answer: Command line argument values are always strings. If you mean for them to be something else (e.g. int) you have to do that yourself - including any error handling when users pass in the wrong thing:
var1 = sys.argv[0]
var2 = int(sys.argv[1])
var3 = int(sys.argv[2])

try:
    int_arg = int(sys.argv[1])
except ValueError:
    print("invalid command; usage: ...")

Answer: Your issue is because command line args in sys.argv are strings. You need to cast them to an int before you can use them (int(sys.argv[0]).
Would also recommend using Python3 instead of Python2. Python2 is deprecated and should not be used for any purposes.
As Python2 is a requirement for your task:
var1=sys.argv[0]
var2=int(sys.argv[1])
var3=int(sys.argv[2])

print "String %s" % var1
print "Num1 %d" % var2
print "Num2 %d" % var3

You may want to consider looking at importing from the __future__ module if you are on Python 2.6+. This will allow you to use the print function instead of the keyword. See this Stack Overflow thread for more info.
Python3 would allow you to use f strings for printing:
foo = sys.argv[0]
bar = sys.argv[1]

print(f"First arg is {foo}")
print(f"Second arg is {bar}")

Comment: I am working with python 2, as this is a must of a technology which I am using
Comment: That is extremely unfortunate. The first part of the answer still applies, however. I have made some edits to give some more information and tips on Python2.
Answer: Another way of doing this would be to use f strings (Only for python 3+). It looks very clean, and it's easy to read.
var1=sys.argv[0]
var2=sys.argv[1]
var3=sys.argv[2]

print(f"String {var1}")
print(f"Num1 {var2}")
print(f"Num2 {var3}")

Passing a number to a python script


Java WebStart 'Mandatory update' dialogue always shown

Question: We have an application that is launched through Web Start with a JNLP using the following to ensure application is run only with newest code:
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="6.0+"
 codebase="$$codebase" href="$$codebase/"app name...."jnlp">

  <update check="always" policy="prompt-run"/>
    <information>
      <title>title....</title>
      <vendor>vendor name...</vendor>
      <shortcut online="true">
        <desktop/>
       <menu submenu="@start.menu.title@" />
       </shortcut>
    </information>
 <security>
  <all-permissions/>
 </security>
 <resources>

    <j2se version="1.6+"
      initial-heap-size="128m"
      max-heap-size="512m"
          href="http://java.sun.com/products/autodl/j2se"/>

    <jars....>
    <properties....>

  </resources>
   <application-desc
  name="name..."
     main-class="main class....">
   </application-desc>
</jnlp>

This works fine in most environments to notify of update and invoke download of new resources. However, in one test environment, the "mandatory update is available.." dialogue is shown on every launch of the application. After clicking the "OK" button though, the application downloads nothing and proceeds to run normally.
I haven't found any good documentation that tells what timestamp is being compared to determine if an update is available.
Any one else seen this issue or have any ideas or information to share?
Also, I saw a forum post on Oracle's site from a few months ago but with only a couple of postings and no answers. When I attempted to post a reply, the site went down (which seems to be a common occurrence with Oracle...).
Comment: Maybe `policy="prompt-run"` is the problem. Try changing it to `prompt-update`
Comment: Supplement: For a good control over the update process, you should use the version tag. See http://download.oracle.com/javase/6/docs/technotes/guides/javaws/developersguide/syntax.html
Comment: Well, if I'm not mistaken, with `prompt-update` the user has a choice to update or just run the cached version. On this application the project owners want to make sure that the user has the most up-to-date version.
Comment: Then `` is your friend.
Comment: Yep! That's what I was thinking. However, they don't want me to get rid of the "Mandatory update..." message. They're afraid there's an underlying issue between the application and Web Start. Looks like I'm stuck to figure out why the check is showing an update is necessary. This is just the latest in a long list of issues related to Web Start and this application.
Comment: JWS in productive environment is really a pain. We use the download servlet (http://download.oracle.com/javase/6/docs/technotes/guides/javaws/developersguide/downloadservletguide.html) with version management but sometimes the jnlp gets broken and an update is not possible. Customers are really annoyed about such behaviour but Oracle doesn't seem to update the jnlp api to solve such issues.
Comment: Yeah, we're using it as well. However, I think he only use we're currently getting out of it is the populating of `$$codebase`. We actually have a defect on file because of the download servlet throwing 'Broken pipe' exceptions in the logs on the server.
Comment: That JNLP appear to be invalid in at least 2 ways.  Make sure it is validated using [JaNeLA](http://pscode.org/janela/).
Answer: in my case, i used:
<update check="always" policy="always" />

And it works without the warn when i don't have things to update.
Maybe it can help you too.


Mongoose replaces updated object at array index with undefined before running update query

Question: I have a layer document in mongodb containing points on a map.  The points are an array.  To update a point at a specific index, I use the following code:
            var query;
            if (req.body.isNew)
                query = { $push: { 'points': point } }
            else
                query = { $set: { ['points.' + pointIndex]: point } };

            console.log("QUERY IS: ", query)
            Layers.update({ _id: layer._id }, query, (err, result) => {
                if (err || !layer) {
                    console.error(err);
                    res.status(400).json({ "error": "error updating" })
                    return;
                }
                res.status(200).json({ success: true });
            });
            console.log("RAN query");

What you will see is that the query is correctly generated to update a specific code a given index.   However, when mongoose runs the query, IT REPLACES THE POINT WITH undefined!  Why is it doing this?  This is the console output (I have mongoose set to log queries it runs):
QUERY IS:  { '$set':
   { 'points.0':
      { _id: '58389c52d1fc2dcb1d9f06d1',
        lat: 39.605688178320804,
        lng: -98.9208984375,
        customFieldValues: {},
        tasks: [],
        name: 'abcd',
        updatedAt: 2016-11-25T20:17:32.995Z,
        updatedBy: 'email@example.com' } } }
RAN query
Mongoose: layers.update({ _id: ObjectId("58387d06b549e03c588993eb") }, { '$set': { 'points.0': undefined } }, {})

Answer: Downgraded to Mongoose 4.5.3 and it works!  This is why I should be using yarn instead of NPM.


ways to convert chm to djvu

Question: I was wondering how to convert chm to djvu?  Command line, GUI or online solutions are both fine. My OS is 10.10.
Thanks and regards!
Answer: You'll probably have to convert the chm file through an intermediary file format such as PDF.
Two packages are available in synaptic manager/software center, pdf2djvu and chm2pdf
Suggested conversion syntax for an example.chm file:
chm2pdf --book example.chm
pdf2djvu -o example.djvu example.pdf

Comment: chm2pdf cannot start if the chm-filename contains parentheses (and other funny characters). Renaming the file helps.

ways to convert chm to djvu


Append only if item doesn't exists in array

Question: I have 3 select boxes,
one for country,  another for cities and another one for radius around a city.
I want whatever the user choses  to appear in a div before sending and saving all data in db.
I'm trying to make this work, but I dont know why I'm having strange results.
It does nothing!, but if I remove the " ! " it kinda works for the first one , but then i get duplicates again.
I dont understand what am i doing wrong.
Here is the code:
var citySet = new Array;
function appendCity(){

    if(!$.inArray($("#businessCityTarget option:selected").text(),citySet)){

        $("#cityContainer").append($("#businessCityTarget option:selected").text() + "
");
        citySet.push($("#businessCityTarget option:selected").text());

    }

}

Any light shed will be gratfull
Comment: You know that its too damn difficult to read unformatted code, right?
Comment: Why are there duplicates in the first place?
Answer: Try:
if(citySet.indexOf($("#businessCityTarget option:selected").text()) < 0){
    $("#cityContainer").append($("#businessCityTarget option:selected").text() + "
");
    citySet.push($("#businessCityTarget option:selected").text());
}

Answer: can you try this:
var citySet = new Array;
function appendCity(){

        if($.inArray($("#businessCityTarget option:selected").text(),citySet)===-1){

            $("#cityContainer").append($("#businessCityTarget option:selected").text() + "
");
            citySet.push($("#businessCityTarget option:selected").text());

        }

    }

Hope this helps..
Comment: if `!==-1` is true, it means element is present in array. Here as Op wants its opposite
Answer: You should check === -1 or < 0
var citySet = new Array;

function appendCity() {
    if ($.inArray($("#businessCityTarget option:selected").text(), citySet) === -1) {
        $("#cityContainer").append($("#businessCityTarget option:selected").text() + "
");
        citySet.push($("#businessCityTarget option:selected").text());
    }
}

From docs

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.


Copying the string of pointer to other pointer

Question: Folks,
   I have basic and simple question on pointers. The below is code is giving a segmentation fault.
int main()

{

    char *str = "hello, world\n";

    char *strc = "good morning\n";

    strcpy(strc, str);

    printf("%s\n", strc);

    return 0;

}

Can't we copy from pointer to other.

if i have char *strc = "good morning\n", can't i do like this
strc[5] = '.';. Why this also giving a seg fault.
Comment: Please note that with `char strc[] = "good morning\n"`, the literal string itself will still be allocated in a RO memory segment, but every time the function is called, that string will be copied into the stack (i.e., into the `strc[]` array).
Comment: Similar questions have been asked here 10,000 times. No you can't, variable `strc` is pointing to a RO memory segment within the executable image. Change `char *strc` to `char strc[]` and it will be pointing to (allocated on) the stack.
Comment: Yes, i know that. i want to know, what is the reason.
Answer: You may not change string literals. It is what you are trying to do in statement
strcpy(strc, str);

that is you are trying to overwrite string literal "good morning\n" pointed to by pointer strc.
Of cource you may use pointers in function strcpy. The valid code can look like
#include <stdio.h>
#include <string.h>

int main()
{
    char *str = "hello, world\n";

    char strc[] = "good morning\n";

    strcpy(strc, str);

    printf("%s\n", strc);

    return 0;
}

Or
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char *str = "hello, world\n";

    char *strc = malloc( 14 * sizeof( char ) );
    strcpy( strc, "good morning\n" );

    //...

    strcpy(strc, str);

    printf("%s\n", strc);

    free( strc );

    return 0;
}


Access URL that 404'd in Spring MVC

Question: I'm trying to get the URL that returned a 404 status to display on my error page.
I have this in my web.xml
<error-page>
    <error-code>404</error-code>
    <location>/errors/404.html</location>
</error-page>

And this controller set up
@Controller
public class HTTPErrorController {

@RequestMapping(value="/errors/404.html", method = RequestMethod.GET)
    public String handle404(Model model, HttpServletRequest request) {
        model.addAttribute("referer", request.getRequestURL());

        return "error404";
    }
}

That gives me the /error/404.html URL.
If I try to access the "referer" header from the HttpServletRequest:
request.getHeader("referer");

It's always null.
I would like to pass the URL through the model so I can display it on my error page.
So, for example, if I go to "http://www.example.com/garbage" in my application and that 404s, it will display the "error404" view, and I want "http://www.example.com/garbage" to be available on the view.
Comment: topher-which version of spring you are using?
Comment: I'm using spring 3.1.1
Answer: https://tomcat.apache.org/tomcat-7.0-doc/servletapi/constant-values.html
static final java.lang.String ERROR_REQUEST_URI
The name of the request attribute that should be set by the container when custom error-handling servlet or JSP page is invoked. The value of the attribute is of type java.lang.String. See the chapter "Error Handling" in the Servlet Specification for details.
Since:
Servlet 3.0
See Also:
Constant Field Values

Access URL that 404'd in Spring MVC


Please correct my Query

Question: Select empno,sum(cast(substring(othours,0,3)as float)) as
Hour,sum(cast(substring(othours,4,5)as float)) as Minutes from tmstrans
group by empno,othours

it is showing data like following

1 , 10
1 , 30
2 , 10
2 , 30

i need data like following

1 , 40
2 , 40

please help
Comment: remove `othours` from the `group` by clause
Answer: Assuming you want to SUM both Hour and Minutes columns, you've to remove the othours column from the GROUP BY clause. Test it like this:
SELECT empno,
       SUM(CAST(SUBSTRING(othours,0,3) AS float)) AS Hour,
       SUM(CAST(SUBSTRING(othours,4,5) AS float)) AS Minutes
FROM tmstrans
GROUP BY empno

Please correct my Query


How do I mark certain checkboxes as checked in a dynamic list group? .NETCore / Bootstrap / Razor Pages

Question: I am building a tool to add contacts to distribution lists and one contact can be in multiple distribution lists.  I am using a List Group with checkboxes for users to display and select the  distribution lists.  On the edit contact page I need to check the checkboxes in the list group of the distribution lists that the contact is already a member of.  I simply cannot work out how to do this.  I am using asp.net core with page models (no controllers) and razor pages
This on my cshtml page:
Select a Distribution List

        @foreach (var item in Model.CreateContactViewModel.DistributionLists)
        {

<input type="checkbox" name="DistributionListSelectID" id="@item.DistributionListId" value="@item.DistributionListId" aria-label="@item.ListName" /> @item.ListName

        }

This is on my code behind page
Contact = await _context.Contacts.FirstOrDefaultAsync(m => m.ContactId == id);

if (Contact == null)
{
    return NotFound();
}

CreateContactViewModel = new ContactViewModel()
            {
                DistributionLists = _distService.GetAllLists().Where(d => d.IsDeleted == false).OrderBy(d => d.ListName).ToList(),
                ListsAndContacts = _linkService.GetListsForContact((int)id).ToList()
            };

foreach (var dlitem in CreateContactViewModel.ListsAndContacts)
{
    // Do something here to populate the checkboxes
}

return Page();

There are two interfaces, one to get the full list of DLs, and one to get a list of DLs that contact belongs to.
Thanks
Answer:
On the edit contact page I need to check the checkboxes in the list
group of the distribution lists that the contact is already a member
of.

Do you mean check if the name in one distribution list and in  a List Group  too?
Try to make an if judgment for the checkbox. If the name(contact) is already a member of  the  distribution list, input checkbox will be checked="checked".
Demo: The ContactViewModels has 8 items:AA,BB,CC,DD,EE,FF,GG,HH; The Contacts has 5 items:AA,BB,CC.DD,EE.
Code:
Select a Distribution List

        @foreach (var item in Model.ContactViewModels)
        {

               @*@if (Model.Contacts.Where(c => c.Name == item.Name).Count() != 0)*@//First method
                @if (Model.Contacts.Any(c => c.Name == item.Name))      //Second method
                {
                  <input type="checkbox" checked="checked" name="DistributionListSelectID" id="@item.Id" value="@item.Id" aria-label="@item.Name" />
                }
                else
                {
                    <input type="checkbox" />
                }

                @item.Name

        }

Result:


SQL Server stored procedure error . invalid identifier

Question: I have a stored procedure, but when I execute it from my front-end I get this error:

The name 'CREATE    TABLE tmp_148_58 (affili_item_id
  varchar(250),academic_id varchar(250),college_id
  varchar(250),item_value_quantity_college_entry
  varchar(250),item_value_notes_college_entry
  varchar(250),college_enter_on varchar(250),college_enter_by
  varchar(250),affili_category_colleges_autoid varchar(20))' is not a
  valid identifier.

My procedure code:
ALTER PROCEDURE [dbo].[SpPortal_AppForAffi_Upd_Both_Lbl_And_Vals1]
   (@columnList TEXT
    ,@insScript nvarchar(1000)
    ,@collegeId INT
    ,@LoginId BIGINT)
AS
BEGIN
   DECLARE
       @tmpTableName VARCHAR(200),
       @effectCount INT = 0,
       @effectCountTotal INT = 0,
       @ExeQuery nvarchar(1000),
       @InsertQuery nvarchar(1000)

    SET @tmpTableName = CONCAT('#tmp_',@collegeId,'_',@LoginId);

    SET @ExeQuery = CONCAT('DROP TABLE IF EXISTS ', @tmpTableName);

    EXECUTE @ExeQuery ;

    -- create temp table..  --
    SET @ExeQuery = CONCAT ('CREATE TABLE ' , @tmpTableName , ' (',@columnList,')' ) ;       -- here column list should be come from froent end...
    EXECUTE @ExeQuery;

    -- # create temp table..   --
    --  load data into temp table --
    SET @InsertQuery =  CONCAT(' ' , @insScript);

    EXECUTE @InsertQuery;

    -- # load data into temp table.. --
    -- updating  affili_items_colleges master table--
    SET @effectCount=0;
    -- SET param_sp_success=0;
    Begin TRANSACTION
         Begin Try
        -- SET param_sp_success = 0;
        SET @effectCount = 0;
        SET @effectCountTotal = 0;

        SET @ExeQuery = CONCAT(' UPDATE ', @tmpTableName,' AS tmp ,affili_item_label afil,affili_items afi
        SET afil.item_lable_name = tmp.item_value_quantity_college_entry
    ,afil.enter_on=tmp.college_enter_on
    ,afil.enter_by= tmp.college_enter_by
    WHERE  tmp.affili_item_id=afil.affili_item_id AND tmp.affili_item_label_id = afil.affili_item_label_id
    AND afi.is_label = 1 AND  tmp.academic_id=afil.academic_id  AND tmp.college_id=afil.college_id
    AND tmp.affili_item_id = afi.affili_item_id  AND afi.active_status = 1 ');

    EXECUTE @ExeQuery;

    SET @ExeQuery = CONCAT(' UPDATE ', @tmpTableName,' AS tmp ,affili_items_colleges afic,affili_items afi
    SET afic.item_value_quantity_college_entry = tmp.item_value_quantity_college_entry
    ,afic.item_value_notes_college_entry=tmp.item_value_notes_college_entry
     ,afic.college_enter_on=tmp.college_enter_on
     ,afic.college_enter_by= tmp.college_enter_by
    WHERE tmp.affili_item_id=afic.affili_item_id AND tmp.affili_item_label_id = afic.affili_item_label_id
     AND tmp.academic_id=afic.academic_id  AND tmp.college_id=afic.college_id
     AND tmp.affili_item_id = afi.affili_item_id AND afi.is_label <> 1 AND afi.active_status = 1 ');

    EXECUTE @ExeQuery;

    declare @te int=0

    SET @ExeQuery = CONCAT ('SELECT  COUNT(tem.affili_item_id)  INTO @te
    FROM ',@tmpTableName,' tem INNER JOIN affili_items afi ON tem.affili_item_id = afi.affili_item_id AND afi.is_label <> 1
    WHERE afi.active_status = 1 ') ;

    EXECUTE @ExeQuery;

     SET  @effectCount=0;
     SET @effectCount =  @te ;

         IF(@effectCount>0)
         BEGIN

         SET @effectCountTotal= @effectCount+1;

         END

    -- SET param_sp_success = effectCountTotal;
 IF(@@TRANCOUNT>0)
        BEGIN
            COMMIT TRANSACTION
        END
    ELSE
        BEGIN
            ROLLBACK TRANSACTION
        END
    END TRY

    BEGIN CATCH
        ROLLBACK TRANSACTION
    END CATCH

END

Can anyone help me out in solving it? I converted above query from mysql to SQL Server.
Comment: Also, why are you creating the temporary table like this?
Comment: The table `tmp_148_58` is not created/referenced at all in your code. The error is being thrown from elsewhere. Please find the relevant code section and post it.
Answer: First of all - I really wondering why you are using all of this dynamically created statements. As I can see from your script - the only reason for it is unique name of temporary table you're creating.
But you don't really need your temporary table to have unique name, as this table is visible only in the scope of stored procedure where it was created (and also in the scope of 'child' procedures called from that one).
Also, as per your error it looks like your script tries to create real, not temporary table - see CREATE TABLE tmp_148_58 - name of table doesn't contains #. So you may have no right to create real tables under account you've running your sp.
I suggest you to rewrite your code without that confusing dynamics and error should go away ;)
Comment: @Skumar, again - there's no real need for your temporary table name to be unique and thus created dynamically
Comment: I am using dynamic controls in my form and in my procedure i Concatenate like this to get temp table name SET @tmpTableName = CONCAT('#tmp_',@collegeId,'_',@LoginId);