text:
Q: How do you exclude a specific UIButton from an extension in Swift? I am a beginner so bear with me.
I created a basic timer app and rounded the corners of two buttons. The button was still clickable outside of the circle, I needed to fix that so I found a solution online that said to insert the code into the UIButton's subclass or extension. I found solutions for both ways and chose extension option because the code was easier to read and I could understand it better.
The issue now is that I have a third UIButton that is being affected by the extension and I would like to exclude it. I'm not sure if this is even practical (or possible) so please correct me if there is a better way to approach this. The button I need to exclude from the extension is resetButton.
import UIKit

extension UIButton {
    open override func draw(_ rect: CGRect) {
        self.layer.cornerRadius = 50.0
        self.layer.masksToBounds = true
        //exclude resetButton???
    }
    private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}
    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return touchPath.contains(point)
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var stopButton: UIButton!
    @IBOutlet weak var resetButton: UIButton!

    var timeRemaining: Int = 10
    var timer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        //// Moved to an extension in order to
        //// remove the clickable areas outside
        //// of the circle
        //startButton.layer.cornerRadius = 50.0
        //stopButton.layer.cornerRadius  = 50.0
    }

    @IBAction func start(_ sender: Any) {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(step), userInfo: nil, repeats: true)

    }

    @IBAction func stop(_ sender: Any) {
        timer?.invalidate()
    }

    @IBAction func reset(_ sender: Any) {
        timer?.invalidate()
        timeRemaining = 10
        label.text = "\(timeRemaining)"
    }

    @objc func step() {
        if timeRemaining > 0 {
            timeRemaining -= 1
        } else {
            timer?.invalidate()
        }
        label.text = "\(timeRemaining)"
    }

}

A: For your case, extension is not the right option as the methods invoked from extension will apply to the type itself (all UIButton objects in this case).
One option for you is to make a subclass of UIButton instead of extension. Something like this:
class RoundedButton: UIButton {
  open override func draw(_ rect: CGRect) {
      self.layer.cornerRadius = 50.0
      self.layer.masksToBounds = true
  }
  private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}
  open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
      return touchPath.contains(point)
  }
}

And hence you can select the buttons that should inherit the custom layout from the class above:
@IBOutlet weak var startButton: RoundedButton!
@IBOutlet weak var stopButton: RoundedButton!
@IBOutlet weak var resetButton: UIButton! // Will not get the style applied for startButton and stopButton


text:
Q: Find produces an error in case of hidden rows I have a method for copying certain cells from range. Range is defined by two words on Worksheet.
Here is method:
Private Sub copyOptionsToTable(RowToPaste As Integer, OperatingWorksheet As Worksheet)

    Dim OptionsRange As Range
    Dim cell, x

    Set OptionsRange = OperatingWorksheet.Range(OperatingWorksheet.Cells.Find( _
    "[OPTIOONS START]").Offset(1, 0), OperatingWorksheet.Cells.Find( _
    "[OPTIOONS END]").Offset(-1, 0))

    x = 0

    ' Copy - Paste process
    For Each cell In OptionsRange.Cells
        If Not IsEmpty(cell.Value) And cell.Value <> "OPT" Then
            With ThisWorkbook.Worksheets("TableForOL").Range("B" & RowToPaste)
                .Offset(x, 0).Value = cell.Offset(0, -20).Value
                .Offset(x, 3).Value = cell.Offset(0, 2).Value
            End With
            x = x + 1
        End If
    Next cell

End Sub

Here is example of calling it:
Sub 123()

copyOptionsToTable 18, CalculationItemOM1

End Sub

I have recently noticed that if rows with words that are defining range are hided, I am getting an error pointing at:
Set OptionsRange = OperatingWorksheet.Range(OperatingWorksheet.Cells.Find( _
"[OPTIOONS START]").Offset(1, 0), OperatingWorksheet.Cells.Find( _
"[OPTIOONS END]").Offset(-1, 0))

Is there any options to get this working with hidden rows? Preferably without unhiding hidden rows, because then I need to store information about what is hidden and what is not before running this code and then after it is ready get back as it was before its execution.

A: I have got it working with a little bit different approach:
  Private Sub copyOptionsToTable(RowToPaste As Integer, OperatingWorksheet As Worksheet)

        'On Error Resume Next

        Dim OptionsRange As Range
        Dim cell, x

        Dim FirstCell As Range
        Dim LastCell As Range

        Set FirstCell = Cells.Find(what:="[OPTIOONS START]", LookIn:=xlFormulas, lookat _
            :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
            False, SearchFormat:=False)
        Set LastCell = Cells.Find(what:="[OPTIOONS END]", LookIn:=xlFormulas, lookat _
            :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
            False, SearchFormat:=False)

        x = 0

        ' Copy - Paste process
        For Each cell In OperatingWorksheet.Range(FirstCell.Offset(1, 0), LastCell.Offset(-1, 0)).Cells
            If Not IsEmpty(cell.Value) And cell.Value <> "OPT" Then
                With ThisWorkbook.Worksheets("TableForOL").Range("B" & RowToPaste)
                    .Offset(x, 0).Value = cell.Offset(0, -20).Value
                    .Offset(x, 3).Value = cell.Offset(0, 2).Value
                End With
                x = x + 1
            End If
        Next cell

    End Sub

A: As far as I know, Find method doesn't work with hidden data. But, you may temporary copy and paste the data (values only) from entire sheet to another sheet which won't contain hidden data and apply Find within the new sheet. After performing the search, just delete or clear the new sheet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: General form of this integral functional equation? So I was doing some physics and I can recover a variant of the Maxwell distribution (the answer is a gaussian)
$$P(k)dk = \int_{-\infty}^\infty P(k-x)P(x) dx dk
$$
I was trying to extend this to the relativistic case. How would one find the general form of this probability distribution $P$? (Is it some kind of Bessel function?)
$$P(k) dk= \int_{0}^\infty P(\lambda)P(k/ \lambda) d \lambda dk
$$
Edit:
Calculations of the first claim:
$$P(k) dk = \int_{-\infty}^\infty (a^2/ \pi) e^{-a^2(k-x)^2-a^2x^2} dx dk= (a^2/ \pi) \int_{-\infty}^\infty e^{-a^2 (k^2  - 2x^2 - 2kx)}dx dk =  (a^2/ \pi) \int_{-\infty}^\infty e^{-a^2 (2(k/2 +x)^2  +k^2/2)}dx dk$$
Taking $x \to k/2 + x$
$$(a^2/ \pi) \int_{-\infty}^\infty e^{-a^2 (2x^2  +k^2/2)}dx dk= |a| \sqrt{\frac{2}{\pi}}   e^{-a^2k^2/2} dk $$
where $k \to \sqrt2 k$
$$\frac{|a|}{\sqrt{\pi}}   e^{-a^2k^2} dk = P(k) dk$$

A: I agree with previous posters that a Gaussian is not a solution of $P*P=P$, as can be seen easily by working in Fourier space $\hat P \cdot \hat P = \hat P$ can only be solved if $\hat P =1$. Your mistake is precisely where you write $k \to \sqrt2 k$, which means you are replacing $P(k)$ with $P(\sqrt 2 k)$. I suppose you want to say something like $P(x)*P( x)=P(\sqrt 2 x)$. This shouldn't be a surprise since this is an expression for the distribution of the sum of two Gaussian random variables (as @Andrew has pointed out in the comments above).
In order to deal with equations like the second part
$$\int_{0}^\infty P(\lambda)P(k/ \lambda)d\lambda $$, one performs the equivalent of the Fourier transform, but in scale space: the Mellin transform.
$$\int_0^\infty k^\alpha \int_{0}^\infty P(\lambda)P(k/ \lambda)d\lambda dk$$ I wont go into the math, but if you look carefully, you will see that what is going on here is that ${k\over \lambda} = e^{\log(k)-\log(\lambda)}$ so $\log(k),\log(\lambda)$ behave like $k,x$ in the convolution example. Please note that you probably also have a normalization issue in the second integral as well which you should fix, before attempting to solve.

A: Notice that, in the integral
$$P(k) \; \textrm{d}k = \int_{-\infty}^{\infty} P(k-x)P(x)\; \textrm{d}x\; \textrm{d}k $$
the $\textrm{d}k$ term is really problematic. Wouldn't it be nice if we could just divide both sides by it? Well, if we do, we get the following:
$$P(k) = \int_{-\infty}^{\infty} P(k-x)P(x)\; \textrm{d}x $$
or
$$P(k) = (P*P)(k) $$
In other words, the function $P$ is precisely equal to the convolution of itself with itself!
This implies that $P(k)=0$ or $P(k)=\delta(k)$ for all $k$.
Edit 1: I've realized that $1*1$ doesn't really make any sense and just blows up to infinity, so I've replaced the latter equation with $P(k)=\delta(k)$.
Edit 2: $P(k)$ cannot be $e^{-k^2}$ because, if it was, then that would imply that $P(k)=\dfrac{\sqrt{\pi}}{2}e^{-2k}$ (check out Find the derivative of the function $f(x)=\int_{0}^\infty e^{-y^2-(x/y)^2} dy$), so you're wrong about that part. And yes, $(P*P)(k)$ returns a Gaussian-type function when $P$ itself is a Gaussian function, but it isn't the same.
Edit 3: This is the closest answer you're gonna get, OP. Suppose we have a function,
$$P(k) = \int_0^\infty P(\lambda)P\left(\dfrac{k}{\lambda}\right)\textrm{d}\lambda$$
By the substitution $u=\dfrac{k}{\lambda}$, we obtain the following:
$$P(k) = \int_0^\infty P(u)P\left(\dfrac{k}{u}\right)\cdot\dfrac{1}{u^2}\textrm{d}u$$
or
$$P(k) = \int_0^\infty P(\lambda)P\left(\dfrac{k}{\lambda}\right)\cdot\dfrac{1}{\lambda}\cdot\dfrac{1}{\lambda}\textrm{d}\lambda$$
Observe that
$$P(k) = \int_0^\infty P(e^{\ln(\lambda)})P\left(e^{\ln(k)-\ln(\lambda)}\right)\cdot\dfrac{1}{\lambda}\cdot\dfrac{1}{\lambda}\textrm{d}\lambda$$
Look at the first part of the integral and ignore the second $\dfrac{1}{\lambda}$:
$$\int_0^\infty P(e^{\ln(\lambda)})P\left(e^{\ln(k)-\ln(\lambda)}\right)\cdot\dfrac{1}{\lambda}\textrm{d}\lambda$$
Let $u = \ln(\lambda)$
$$\int_{-\infty}^\infty P(e^{u})P\left(e^{\ln(k)-u}\right)\textrm{d}u$$
Now let $G(k)=P(e^k)$
$$\int_{-\infty}^\infty G(u)G\left(\ln(k)-u\right)\textrm{d}u$$
Anyone can easily see that this is equal to
$$(G*G)(\ln(k))$$
Unfortunately, I'm not sure if I can even do better than that. Other users have given some nice answers as well, so you should check them out.

A: It is fact that if $f,g\in L^1(\textbf{R})$, then if we define the convolution of $f,g$ as
$$
(f*g)(x)=\int^{\infty}_{-\infty}f(x-t)g(t)dt,\tag 1
$$
we have
$$
\widehat{(f*g)}(\gamma)=\widehat{f}(\gamma)\widehat{g}(\gamma),\tag 2
$$
where we have used the notation $\widehat{f}(x):=\int^{\infty}_{-\infty}f(t)e^{-it x}dt$.
Hence with no loss of information we can write
$$
P(k)dk=\int^{\infty}_{-\infty}P(k-x)P(x)dxdk\Leftrightarrow
$$
$$
\int^{\infty}_{-\infty}P(k)e^{-iks}dk=\int^{\infty}_{-\infty}e^{-iks}\left(\int^{\infty}_{-\infty}P(k-x)P(x)dx\right)dk\Leftrightarrow
$$
$$
\int^{\infty}_{-\infty}P(k)e^{-iks}dk=\widehat{P}(s)\widehat{P}(s)\Leftrightarrow \widehat{P}(s)=1\Leftrightarrow P(k)=\delta(k),
$$
where $\delta(k)$ is the usual Dirac delta function.
Remark.
There are no functions $f,d$ in $L^1(\textbf{R})$, such that $f*d=f$. A more justified answer is in Charles K. Chui:"An introduction to Wavelets". Academic Press. Inc. (Hancourt Brace Jovanovich Publishers) Boston, San Diego, New York, London, Syndney, Tokyo, Toronto. 1992. pg.28


text:
Q: How do you remove Gerrit's REST API's magic prefix in the response body with Groovy code? My code:
@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')
@Grab('oauth.signpost:signpost-core:1.2.1.2')
@Grab('oauth.signpost:signpost-commonshttp4:1.2.1.2')
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*

def gerrit = new RESTClient('http://localhost:8080/gerrit')
gerrit.auth.basic "gerrit", "password123"
gerrit.get( path: 'changes/1234/reviewers' )

As per https://gerrit-review.googlesource.com/Documentation/rest-api.html#authentication
"To prevent against Cross Site Script Inclusion (XSSI) attacks, the JSON response body starts with a magic prefix line that must be stripped before feeding the rest of the response body to a JSON parser:"
  )]}'
  [ ... valid JSON ... ]

My error:
WARNING: Error parsing 'application/json; charset=UTF-8' response
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ')' with an int value of 41
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
)]}'

A: Sorry, I'm not very familiar with Groovy, but there is no way to remove this prefix from Gerrit unless you want to modify the source code and roll your own release.
The solution is to use a different Groovy API to get the raw data, strip off the first 5 characters, and then feed this into the Groovy JSON parser.  Again, sorry, but I can't help out with what Groovy API might be an option.
As the docs mention, these characters are annoying at times, but an important security feature of Gerrit to prevent any XSS hacks.

A: I found the answer.
@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')
@Grab('oauth.signpost:signpost-core:1.2.1.2')
@Grab('oauth.signpost:signpost-commonshttp4:1.2.1.2')
import groovyx.net.http.RESTClient
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*
import groovy.json.JsonSlurper

public class GerritRestClient {
    def gerrit

    GerritRestClient(config) {
        def username = config.username
        def password = config.password
        this.gerrit = new RESTClient(config.endpoint)
        this.gerrit.auth.basic config.username, config.password
    }

  def sendRequest(path) {
    this.gerrit.request(GET,TEXT) { req ->
      uri.path = path // overrides any path in the default URL
      response.success = { resp, json ->
        assert resp.status == 200
        def fixedJson = json.text.replaceAll('\\)]}\'', '').trim() // remove magic prefix
        def jsonSlurper = new JsonSlurper()
        return jsonSlurper.parseText(fixedJson) // parse the fixed json body and return
      }
      // called only for a 404 (not found) status code:
      response.failure = { resp ->
        println "My response handler got response: ${resp.statusLine}"
        return null
      }
    }
  }

  def getChangeReviewers(changeNumber) {
    def requestPath = "changes/${changeNumber}/reviewers"
    return sendRequest(requestPath)
  }

}


text:
Q: What ensure Netty handlers will get GCed I have written http server and have couple of custom handlers too. Sometimes I want to explicitly close the client connection if some error occurs etc. So in that case what I do is channelHandlerContext.close(). Will this enough to let this handler object GCed. Do I have to do override channelInactive() and do something more ?

A: This will be enough as the pipeline will be cleared on close


text:
Q: Plotting signal from samples in matlab I am given 321 samples of signal y(t) with sampling frequency of 80Hz on the time interval 0 to 4s. I am trying to reconstruct y(t) and plot it in matlab but am getting this error. Here is my work
T=1/80;
n=1:321;
t=n*T;
y(t)=signal(n);

Subscript indices must either be real positive integers or logicals.

I am not sure what I am doing wrong here. My data is stored in 'signal' file so signal(n) retrieves the value of signal at index n. I want to find y(t) and plot y(t) versus t. Can somebody help me with this . Thank you.

A: All indices into vectors must be positive integers.  The vector t does not contain integers due to the multiplication by T.  Try:
y=signal(n);


text:
Q: Swiftmailer Spam Test I've decided on what I'm going to use (Postmarkapp) to check the spam value of my e-mails before sending them out. However, to get a true answer from Postmarkapp, I need to send the full e-mail with headers. I am using swiftmailer.
How can I get the full header message using swiftmailer BEFORE it actually gets sent?

A: instead of:
mailer->send();

You just go:
mailer->toString();

Keep in mind, this does not have ALL headers, because I think more is added by the receiving server before being passed along. Which means, you really do have the raw version of it, but it won't help that much with identifying server factors that could influence your spam score, as it most definitely does affect your spam score. However, it's still a decent indicator for a quick copy spot check...


text:
Q: I cant get this conditional update or insert statement to work in SQL Server This code is supposed to update a record if the name of the person in table 1 is the same as the name of the person in table 2 and if it is not then just insert the name and age of the person as a new record into table 1.
 SELECT
    CASE
    WHEN
    [Name] = @Name
    THEN
    UPDATE
    dbo.EmployeeInfo
    SET
    dbo.EmployeeInfo.Age = V.Age
    FROM dbo.EmployeeInfo I
    INNER JOIN
    dbo.UpdateEmployeeInfo V
    ON
    V.[Name] = I.[Name]

    ELSE

    SELECT * INTO dbo.EmployeeInfo
    FROM dbo.UpdateEmployeeInfo
    WHERE [Name] = @Name

    END
    FROM dbo.EmployeeInfo

I have edited the code just to use IF conditions yet it still does not work
IF
dbo.EmployeeInfo.[Name] = @Name
THEN
UPDATE
dbo.EmployeeInfo
SET
dbo.EmployeeInfo.Age = V.Age
FROM dbo.EmployeeInfo I
INNER JOIN
dbo.UpdateEmployeeInfo V
ON
V.[Name] = I.[Name]

ELSE

SELECT * INTO dbo.EmployeeInfo
FROM dbo.UpdateEmployeeInfo
WHERE [Name] = @Name

A:
update a record if the name of the person in table 1 is the same as the name of the person in table 2 and if it is not then just insert the name and age of the person as a new record into table 1.

You also could use merge
merge table1 as t
using table2 as s
on s.name=t.name
when matched then
update
set t.name=s.name
when not matched by target
then
insert (name,age)
values(age,name)

Merge has some issues as per this thread by Paul White..You could also use seperate statements like below  in a transaction as per your need
update t
set t.name=s.name
from table1 t1
join
table2 s
on s.name=t.name

if @@rowcount=0
insert into table1
(name,age)
values
(10,'a')


text:
Q: Final PDF include table of contents "\thesection" prefixes when im solving a list of exercises i tend to modify \thesection like this:
\renewcommand\thesection{Questão \arabic{section}}

I want to have these on my final PDF toc, not the one who is printed in the first page, but the one who is read by the pdf reader.
Here a simple demonstration of the problem:
\documentclass[12pt]{article}

% Clickable Table of contents
\usepackage[hidelinks]{hyperref}

% Table of contents
\usepackage{tocloft}
\setlength{\cftsecnumwidth}{25mm}       % Fix section width
\setlength{\cftsubsecnumwidth}{12mm}
% Fix space between subsection items on toc
\renewcommand\cftsubsecafterpnum{\vskip5pt}

% Multicols
\usepackage{multicol}

% Maths
\usepackage{amssymb}
\usepackage{amsmath}

% Section, Subsection and subsubsection Customization
\renewcommand\thesection{Questão \arabic{section}}
\renewcommand\thesubsection{%
    \arabic{section} - \alph{subsection})%
}
\renewcommand\thesubsubsection{(\roman{subsubsection})}

\begin{document}

\setcounter{tocdepth}{2}
\tableofcontents

\break

% Q1
\section{}

\begin{multicols}{2}

% Q1 (i)
\subsubsection{$\alpha$}
\begin{flalign*}
&
=   2\,\beta + \theta
&
\end{flalign*}

% Q1 (ii)
\subsubsection{$\beta$}
\begin{flalign*}
&
=   1+3
&
\end{flalign*}

\end{multicols}

\break

% Q2
\section{}

% Q2 - a)
\subsection{}
\begin{flalign*}
&
    \text{random calculations}\cdots
&
\end{flalign*}

% Q2 - b)
\subsection{Pie}
\begin{flalign*}
&
=   \pi
&
\end{flalign*}

\end{document}

The resulting table of contents of the code above gives:

Where i want in the blue area of the image above to be read: "Questão 1"
The solution as provided by Simon Dispa:
\documentclass[12pt]{article}

% Linguagem
\usepackage[portuguese]{babel}  % Babel

% Table of contents
\setcounter{tocdepth}{2}    % remove subsubsection from toc

% Multicols
\usepackage{multicol}

% Maths
\usepackage[fleqn]{amsmath}
\usepackage{amssymb}

% hyperref
\usepackage[hidelinks]{hyperref}

% Solutuion by Simon Dispa =====================>

% questions, subquestions and subsubquestions

% question
\newcounter{question}[section]
\renewcommand{\thequestion}{Questão \arabic{question}}
\newcommand{\question}[1]{
     % reset inner counters
     \setcounter{subquestion}{0}
     \setcounter{subsubquestion}{0}
     % add section*
     \refstepcounter{question}
     \section*{\thequestion\quad#1}
     % add to toc
     \addcontentsline{toc}{section}{%
        \thequestion\quad#1%
    }
}

% subquestion
\newcounter{subquestion}[subsection]
\renewcommand\thesubquestion{%
    Q\arabic{question} - \alph{subquestion})%
}
\newcommand{\subquestion}[1]{
    % reset inner counters
    \setcounter{subsubquestion}{0}
    % add subsection*
     \refstepcounter{subquestion}
     \subsection*{\thesubquestion\quad#1}
     % add to toc
     \addcontentsline{toc}{subsection}{%
        \thesubquestion\quad#1%
    }
}

% subsubquestion
\newcounter{subsubquestion}[subsubsection]
\renewcommand{\thesubsubquestion}{(\roman{subsubquestion})}
\newcommand{\subsubquestion}[1]{
    % add subsubsection*
     \refstepcounter{subsubquestion}
     \subsubsection*{\thesubsubquestion\quad#1}
     % add to toc
     \addcontentsline{toc}{subsubsection}{%
        \thesubsubquestion\quad#1%
    }
}

% Solutuion by Simon Dispa =====================>

\begin{document}

\setcounter{tocdepth}{2}
\tableofcontents

\break

% Q1
\question{}

\begin{multicols}{2}

% Q1 (i)
\subsubquestion{$\alpha$}
\begin{flalign*}
&
=   2\,\beta + \theta
&
\end{flalign*}

% Q1 (ii)
\subsubquestion{$\beta$}
\begin{flalign*}
&
=   1+3
&
\end{flalign*}

\end{multicols}

\newpage

% Q2
\question{}

% Q2 - a)
\subquestion{}
\begin{flalign*}
&
    \text{random calculations}\cdots
&
\end{flalign*}

% Q2 - b)
\subquestion{}

% Q2 - b) (i)
\subsubquestion{Pie}
\begin{flalign*}
&
=   \pi
&
\end{flalign*}

\newpage

% Q3
\question{}

% Q3 - a)
\subquestion{}

% Q3 - b)
\subquestion{}

% Q3 - c)
\subquestion{}

\newpage

% Q4
\question{}

\begin{multicols}{2}

% Q4 (i)
\subsubquestion{$\alpha$}
\begin{flalign*}
&
    E = mc
&
\end{flalign*}

% Q4 (ii)
\subsubquestion{$\beta$}
\begin{flalign*}
&
   E = mc^2
&
\end{flalign*}

% Q4 (iii)
\subsubquestion{$\gamma$}
\begin{flalign*}
&
    E = mc^3
&
\end{flalign*}

% Q4 (iv)
\subsubquestion{$\delta$}
\begin{flalign*}
&
    E = mc^4
&
\end{flalign*}

\end{multicols}

\end{document}

Resulting in the following output:

Thanks in advance

*

*Edit 1: Adding MWE as requested by Peter Wilson

*Edit 2: Adding solution by Simon Dispa

A: Instead of re-defining \section , \subsection , etc. I defined three new commands with their own counters.
\question that behaves like a \section*{} typesets Questão <question number> and adds a section entry to the TOC.
\option behaves like \subsection{} typesets <question number> - < option number>)  and adds a subsection entry to the TOC.
\optionM{optitle}  behaves like \subsubsection{title} and typesets  (optionM number) optitle.
\option and \optionM work also in two columns mode. They must be used after a \question.
The bookmarks in the pdf are created by the package bookmark.
The hyperref can also be used but I found bookmark easier to setup.
Option #2: \usepackage[bookmarks,bookmarksopen,bookmarksdepth=2,hidelinks]{hyperref}
Your question

This is the code.
\documentclass[12pt]{article}

% Table of contents
\usepackage{tocloft}
\setlength{\cftsecnumwidth}{25mm}       % Fix section width
\setlength{\cftsubsecnumwidth}{12mm}
% Fix space between subsection items on toc
\renewcommand\cftsubsecafterpnum{\vskip5pt}

% Multicols
\usepackage{multicol}

% Maths
\usepackage{amssymb}
\usepackage{amsmath}

\newcounter{question}[section]
\newcommand{\question}{% starts a question numbered sequentially
    \setcounter{option}{0} % reset inner counters
    \setcounter{optionM}{0}
    \refstepcounter{question}%
    \section*{Questão \thequestion}%
    \addcontentsline{toc}{section}{Questão \thequestion}% add section* to toc
}

\newcounter{option}[subsection]
\newcommand{\option}{%
    \refstepcounter{option}%
    \subsection*{\thequestion-\alph{option})}%
    \addcontentsline{toc}{subsection}{\thequestion-\alph{option}}%
}

\newcounter{optionM}[subsubsection]
\newcommand{\optionM}[1]{%
    \refstepcounter{optionM}%
    \subsubsection*{(\roman{optionM}) #1}%
%   \addcontentsline{toc}{subsubsection}{\thequestion (\alph{optionM})}% optional for \setcounter{tocdepth}{3} <<<<
}

% Clickable Table of contents
\usepackage[hidelinks]{hyperref}% option #1
\usepackage[open]{bookmark}% option #1

%\usepackage[bookmarks,bookmarksopen,bookmarksdepth=2,hidelinks]{hyperref} % option #2

\begin{document}

\setcounter{tocdepth}{2}
\tableofcontents
\newpage

% Q1
\question

\begin{multicols}{2}

% Q1 (i)
\optionM{$\alpha$}
\begin{flalign*}
&
=   2\,\beta + \theta
&
\end{flalign*}

% Q1 (ii)
\optionM{$\beta$}
\begin{flalign*}
&
=   1+3
&
\end{flalign*}

\end{multicols}

%\newpage

% Q2
\question
% Q2 - a)
\option
\begin{flalign*}
&
\text{random calculations}\cdots
&
\end{flalign*}

\option % Q2 - b)
%   \subsection{Pie}
\begin{flalign*}
&
=   \pi
&
\end{flalign*}

%\newpage

\question %Q3

\option % Q3 - a)

\option % Q3 - b)

\option % Q3 - c)

%\newpage

% Q4
\question

\begin{multicols}{2}
    % Q4 (i)
    \optionM{$\alpha$}
    \begin{flalign*}
        &
    E   =   mc
        &
    \end{flalign*}

    % Q4 (ii)
    \optionM{$\beta$}
        \begin{flalign*}
        &
        E   =   mc^2
        &
    \end{flalign*}

        % Q4 (iii)
    \optionM{$\gamma$}
        \begin{flalign*}
        &
        E   =   mc^3
        &
    \end{flalign*}

    % Q4 (iv)
    \optionM{$\delta$}
        \begin{flalign*}
        &
        E   =   mc^4
        &
    \end{flalign*}
\end{multicols}

\end{document}

Note If you want \optionM to behave like \option, appearing in the TOC and in the bookmarks, use
\newcounter{optionM}[subsection]
\newcommand{\optionM}[1]{%
\refstepcounter{optionM}%
\subsection*{(\roman{optionM}) #1}%
\addcontentsline{toc}{subsection}{\thequestion (\alph{optionM})}
}


text:
Q: How do I determine the equation to calculate the Eigenvalues of a PDE? Let's say I have the following boundary value problem:
$$ \partial_t u(x,t)=\partial_{xx}u(x,t)-u(x,t)+sin(\pi x),  \quad x\in(0,1),\quad t>0 $$
$$ u(0,t)=0, \quad t>0 $$
$$ u_x(1,t)=0, \quad t>0 $$
$$ u(x,t)=a, \quad x\in(0,1) $$
To find the Eigenvalues and Eigenvectors  I found the equation for this to be:
$$ \phi''(x)+\lambda\phi=0, \quad x\in (0,1) $$
$$ \phi(0)=\phi_x(1)=0 $$
However: I couldn't figure out why I have to use this equation. And how do I find the equation for other boundary-value problems? Is there a general way for this?

A: First we solve the homogeneous problem using separation of variables; Let us suggest a solution of the form - $u(x,t)=X(x)T(t)$. Plugging this into the PDE we get:
$$T'X-TX''+TX=0$$
$$\frac{X''}{X}=\frac{T'}{T}+1$$
Since both sides of the equation depend strictly on two independent variables, we conclude that they are both equal to some constant $-\lambda$ (the minus sign is for convenience). We thus get an equation for the term that depends on $x$:
$$X''+\lambda X=0$$
Which is the equation you were given. From the given boundary conditions we know that - $$X(0)=X_x(1)=0$$
(since the result needs to be independent of the function $T$)
This explains why you need to use this equation. You can now solve the equation in order to find the part of the solution that depends on $X$. You will get a set of eigenfunctions that span the space of solutions. You can then use the temporal initial condition and the in-homogeneous part of the equation in order to find the complete solution.


text:
Q: Преобразование tuple в аргументы функции Есть функция real_func из модуля:
def real_func(FirstVar, *OtherVars)
    # какой-то код

def pre_func(First, *Other):
    # мои преобразования
    real_func(First, Other)

Вызывать ее нужно из другой функции pre_func. Как видно, на входе можно подать несколько значений, к примеру 3 штуки. Но если на входе в переменную pre_func я подаю integer, то на входе в real_func идет уже tuple, и функция это не принимает, т.к. сама потом оборачивает OtherVars в tuple. Хорошо видно на примере:
def real_func(FirstVar, *OtherVars):
        print("-- real func --")
        print("%s is %s" % (FirstVar, type(FirstVar)))
        print("%s is %s" % (OtherVars, type(OtherVars)))
        print("%s is %s" % (OtherVars[0], type(OtherVars[0])))

def pre_func(First, *Other):
        print("-- pre func --")
        print("%s is %s" % (First, type(First)))
        print("%s is %s" % (Other, type(Other)))
        real_func(First, Other)

pre_func(1, 2, 3)

Вывод:
-- pre func --
1 is <class 'int'>
(2, 3) is <class 'tuple'>
-- real func --
1 is <class 'int'>
((2, 3),) is <class 'tuple'>
(2, 3) is <class 'tuple'>

*

*Я не могу менять код real_func - здесь это пример. Реальная функция же падает с ошибкой, т.к. не понимает tuple в tuple.

У меня никак не получается передать в real_func значения типа integer, а не tuple. Надеюсь на помощь.

A: Просто добавьте * перед коллекцией, чтобы распаковать ее в аргументы функции:
real_func(First, *Other)


text:
Q: In EntityFramework after insert to db, DBset returns same value The problem is DbSet returns same value all time but database changes.
Here is a sample code (I used Repository Pattern and Database First Approach and MVC). After insert or delete method, Database saves changes but in View I can't see result.
The code below is a part of my project. There are rooms and lectures and roomlectures table in db. and it adds selected roomlecture to table.
you can check it on Github
BaseRepository.cs
public class BaseRepository<TEntity> where TEntity : class
{
    protected MusicSchoolContext db;
    protected DbSet<TEntity> table;

    public BaseRepository()
    {
        db = new MusicSchoolContext();
        table = db.Set<TEntity>();
    }
    public int Insert(TEntity entity)
    {
        table.Add(entity);
        return Save();
    }

Controller.cs
public ActionResult Detail(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Index");

            Room room = DataService.Service.roomService.SelectOne(x => x.Id == id);
        }

[HttpPost]
    public ActionResult AddOrRemoveLecture(RoomLecture rl)
    {
        if (ModelState.IsValid)
        {
            rl.AddedDate = DateTime.Now;

            RoomLecture item = DataService.Service.roomLectureService
                .SelectOne(x => x.LectureId == rl.LectureId && x.RoomId == rl.RoomId);

            if (item != null)
                DataService.Service.roomLectureService.Delete(item.Id);
            else
                DataService.Service.roomLectureService.Insert(rl);
        }

        return RedirectToAction("Detail", new { id = rl.RoomId });
    }


text:
Q: Using Powershell to loop through Excel files and check if Spreadsheet name exists I'm trying to write a powershell script that will loop through each excel file in the given directory, check the file for a specifically named worksheet, and then copy that file to another location if it's a match.
Please see below for what I've already tried:
[void][reflection.assembly]::Loadwithpartialname("microsoft.office.excel")

$Excel = New-Object -ComObject Excel.Application
$tempLocation = "C:\Test\"     # Path to read files
$files = Get-ChildItem C:\Test

ForEach ($file in $files)
{
#Check for Worksheet named TestSheet

     $WorkBook = $Excel.Workbooks.Open($file)
     $WorkSheets = $WorkBook.WorkSheets

     foreach ($WorkSheet in $Workbook.Worksheets) {
     If ($WorkSheet.Name -eq "TestSheet")
    {$path = $tempLocation + "\" + $file
         Write "Saving $path"
         Copy-Item c:\Test\$file c:\Confirmed}
     Else {Write "$path does not contain TestSheet"}
     $WorkBook.Close()
}
}

This script returns no errors in PowerShell, but just sits there without writing anything or copying any files.  Any ideas?
EDIT:  Here's my final script that is now running successfully
$ErrorActionPreference= 'silentlycontinue'
$tempLocation = "C:\Source"     # Path to read files
$targetlocation = "C:\Target"
Write "Loading Files..."
$files = Get-ChildItem C:\Source
Write "Files Loaded."
ForEach ($file in $files)
{
#Check for Worksheet named TestSheet
     $Excel = New-Object -ComObject Excel.Application
     $Excel.visible = $false
     $Excel.DisplayAlerts = $false
     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "TestSheet"}

     if($WorkSheets) {
     $path = $tempLocation + "\" + $file
     $dest = $targetlocation + "\" + $file
     Write "Saving $path"
     $WorkBook.SaveAs($dest)
     }
     $Excel.Quit()
     Stop-Process -processname EXCEL
}
Read-host -prompt "The Scan has completed.  Press ENTER to close..."
clear-host;

A: There were several issues with my script's logic.  The following script ran successfully!  It took hours of research...
$ErrorActionPreference= 'silentlycontinue'
$tempLocation = "C:\Source"     # Path to read files
$targetlocation = "C:\Target"
Write "Loading Files..."
$files = Get-ChildItem C:\Source
Write "Files Loaded."
ForEach ($file in $files)
{
#Check for Worksheet named TestSheet
     $Excel = New-Object -ComObject Excel.Application
     $Excel.visible = $false
     $Excel.DisplayAlerts = $false
     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "TestSheet"}

     if($WorkSheets) {
     $path = $tempLocation + "\" + $file
     $dest = $targetlocation + "\" + $file
     Write "Saving $path"
     $WorkBook.SaveAs($dest)
     }
     $Excel.Quit()
     Stop-Process -processname EXCEL
}
Read-host -prompt "The Scan has completed.  Press ENTER to close..."
clear-host;

A: You don't need this line:
[void][reflection.assembly]::Loadwithpartialname("microsoft.office.excel")

($Excel = New-Object -ComObject Excel.Application is sufficient here)
I don't think you're referencing the full path to your Excel files.  Try modifying this line:
$WorkBook = $Excel.Workbooks.Open($file)

Amend to:
$WorkBook = $Excel.Workbooks.Open($file.Fullname)

Additionally, consider adding a filter to your Get-ChildItem command, if there are sub-directories or non-Excel files, they will cause errors:
$files = Get-ChildItem C:\Test -filter "*.xls"


text:
Q: Psuedo element to display behind parent divs text but in front of parent div I have a psuedo element which is a pink background inside a div like so:

  Hello

div {
  background-color: green;
  display: inline-block;
  padding: 20px;
  position: relative;
}

div::after {
  content: "";
  background-color: pink;
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Also here is a codepen to show what I mean: http://codepen.io/acha5066/pen/oXVPzg I want the pink background in front of the green background but behind the text Hello. How can I achieve this?

A:

div {
  background-color: green;
  display: inline-block;
  padding: 20px;
  position: relative;
  z-index: 0 /* we etablish a new stacking context */
}

div::after {
  content: "";
  background-color: pink;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1
}

  Hello

A good article that will help you to understand the stacking context: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context


text:
Q: A Constructor for Incremental Loading Collection Helpers in UWP C# How can I add a constructor to my IncrementalLoadingCollection. I want to add a constructor to pass arguments to the GetPagedItemsAsync method to load data from an API.
My Incremental Loading Collection:
public class PeopleSource : IIncrementalSource<Person>
{
    private readonly List<Person> people;

    public PeopleSource(int maxValue)
    {
        // Creates an example collection.
        people = new List<Person>();

        for (int i = 1; i <= maxValue; i++)
        {
            var p = new Person { Name = "Person " + i };
            people.Add(p);
        }
    }

    public async Task<IEnumerable<Person>> GetPagedItemsAsync(int pageIndex, int pageSize)
    {
        // Gets items from the collection according to pageIndex and pageSize parameters.
        var result = (from p in people
                        select p).Skip(pageIndex * pageSize).Take(pageSize);

        // Simulates a longer request...
        await Task.Delay(1000);

        return result;
    }
}

The above code is an example from Microsoft. There is a constructor for People which takes an Argument named maxValue.
var collection = new IncrementalLoadingCollection<PeopleSource, Person>();

The above code is an Initialization of the Incremental Loading class. But where do I pass on the maxValue Argument?? Please Help me...

A: What you're trying to do doesn't make much sense because functions/methods and constructors are fundamentally different things.
GetPagedItemsAsync is a function that returns a value (a Task<IEnumerable<Person>>). Constructors only ever return new instances of objects; in this case, a new instance of PeopleSource.
You cannot create a PeopleSource constructor that takes int maxSource and have it return a Task<IEnumerable<Person>>.
EDIT:
As an alternative, you could create a method that creates a new PeopleSource, then executes the GetPagedItemsAsync method.
public static Task<IEnumerable<Person>> GetPagedItemsAsync(int maxValue, int pageIndex, int pageSize)
{
    var instance = new PeopleSource(maxValue);
    return instance.GetPagedItemsAsync(pageIndex, pageSize);
}

Note that this is less than optimal, because if you have to invoke GetPagedItemsAsync multiple times, it will repopulate the PeopleSource instance every time you invoke it. This can be very expensive if the data comes from a database.
It's generally better to create the PeopleSource, store it in a variable, and then invoke GetPagedItemsAsync as many times as you need to off of the same instance.


text:
Q: How to integrate custom database table in Wordpress and using Wordpress functions I'm on Wordpress 3.0.4 and I'm having a hard time deciding which way to go. The following is my problem:
I have a mysql database table widgets, with about 10 properties like id, size, color etc.
Now I'd like to integrate this table into Wordpress, preferably in such a way that I can get paginated lists of the widgets, show information on a single widget and have a flexible layout.
Preferably, I would like the ability to change a custom template in such a way that I can change the position of each property on the page (So maybe I'd like to put e.g. the size-property on top of the page on the left, later I might want to put it on the right bottom).
What would be the best way to store the widgets, retrieve them by using as much Wordpress build-in functions and how can I get this flexible layout as well?
I've written my own plugins before, so I have more than basic knowlegde on Wordpress/PHP/MySQL.

A: This is precisely what custom post types are for.
If it were my project, I'd scrap the custom table you have, set up a custom post type for your "widgets", add all your existing widgets as regular WP content, and use standard WordPress functions and templates to query and display them.
It's a bit of investment in the short term (if you have a lot of existing data you need to migrate), but in the long run it's best to have all your content in standard WordPress tables and display it using standard WordPress functions and templates--unless there's a really compelling reason not to.

A: If this table is in same database as your WordPress installation you can use $wpdb to get data from it. Otherwise you can instantiate your own wpdb object with connection details for other database.
I am not sure what do you mean by widgets in this case, doesn't sound like same thing as WordPress widgets? Since I am fuzzy on this I have no suggestions how to handle template for those.

A: FWIW, we've done something like this where we ARE pulling the data from an external data source. We created custom post types and created functions that are triggered by different wordpress hooks, with the result that we can show everything both up front to site visitors and in wp-admin. The posts are not stored in wpdb, not even as "proxy" posts.
So it IS possible to do it that way, although we have yet to figure out a way to use the trash can to delete them, and I ended up adding in my own wp-admin pagination links using JQuery.
Unless you have a very good reason to do it this way, I agree with @MathSmath: create a custom post type and store them as "real" wordpress posts.

A: As far as I know what you wanted to do can be easily achieved using Caspio. You don't even have to use any database. They provide a online database on top of which you can create all sorts of database-driven functioinalites. Here's a video I saw from them that shows how to build and embed a searchable contacts database on a WP site in just a few mins without any coding: https://www.youtube.com/watch?v=BgHV7ZPplo0
Hope this helps!


text:
Q: How can I properly see lyrics in DeaDBeef? The solution should be the Infobar plugin - but in my case it doesn't look properly.
It should look like this (from the author's site)

but instead it looks like this, with a large empty space above the tabs:

Does anybody knows a solution or has the same problem?

A: The latest DeaDBeef 0.5.5 doesn't seem to have this problem - the empty space disappears and the player looks fine with lyrics: but only as long as the File Browser plugin (or maybe some other plugin) is not used. Similar problems with other plugins are very possible.
The cause of this is explained by the author of infobar (here) as follows:
"Unfortunatelly, deadbeef doesn't provide API which allows to integrate third-party UI plugins into its interface (situation gonna be changed with release of version 0.6.0). In this situation infobar and filebrowser plugins use hacks to integrate themselves into deadbeef's interface and can't work together."
In v. 0.5.6 the Filebrowser and the gtk2 version of Infobar have the same incompatibility. But there is a gtk3 version of Infobar, and Deadbeef v. 0.5.6 has a gtk2-gtk3 GUI switch.

 Installing Infobar gtk3 and the File-browser, which is gtk 2, will result in using the two plugins alternatively: in the gtk2 GUI of Deadbeef only the file-browser will be visible, in the gtk3 GUI, only the Infobar. Switching between GUIs will switch between plugins too.
When lyrics are not found by Deadbeef/Infobar, use Foobar in wine and install the lyrics grabber addon.

But usually would not need that (the difference with Foobar is that it embeds the lyrics into the file: Deadbeef displays them from internet)


text:
Q: Meaning of "Truth, like gold, is to be obtained not by its growth, but by washing away from it all that is not gold." Leo Tolstoy said,

Truth, like gold, is to be obtained not by its growth, but by washing away from it all that is not gold.

Would love to know the exact implication that is indicated through the comparison with gold. Did he refer to the fact that too much gold makes us greedy and it is better to have less but pure gold? If so, how is it related to truth? I'd believe he meant that truth should not be murky, but I can't be sure in regard to the nature of comparison with gold.
Some insight would be helpful!

A: What Tolstoy meant was that you get truth by removing everything from it that is not truth. You obtain elements (including gold) from the earth the same way, by washing away everything clumped to it that is not what you seek.
I don't have any sources for this -- it seems plain by sheer reason.

A: The simile refers to the way that gold is mined by panning. In a gold mine, the gold nuggets are mixed with soil. The soil is put into a pan, which is then washed with water. This causes the different constituent materials to separate, and the gold is extracted.
Similarly, you can obtain truth from a mixture of information by washing away all the obvious falsehoods.


text:
Q: Can django-pagination do multiple paginations per page? If it can't then are there any other alternatives (either Django's native pagination or an alternate package) that allows multiple paginations per page?
I would like to display a list of about 5 objects with each object having its own pagination context.
For convenience, here is the documentation for django-pagination.

A: I know this post is old, but it is still relevant. The following will work for Django 1.9.
This is how to do it,
views.py
def myview():
    Model_one = Model.objects.all()
    paginator = Paginator(Model_one, 6)
    page = request.GET.get('page1')
    try:
        Model_one = paginator.page(page)
    except PageNotAnInteger:
        Model_one = paginator.page(1)
    except EmptyPage:
        Model_one = paginator.page(paginator.num_pages)

    Model_two = Model_other.objects.all()
    paginator = Paginator(Model_two, 6)
    page = request.GET.get('page2')
    try:
        Model_two = paginator.page(page)
    except PageNotAnInteger:
        Model_two = paginator.page(1)
    except EmptyPage:
        Model_two = paginator.page(paginator.num_pages)

    context = {'Model_one': Model_one, 'Model_two': Model_two}
    return render(request, 'template.html', context)

The important thing above is the 'page1' and 'page2'.
In the template,
    {% if model_one %}

        {% for item in model_one %}
        ..... iterates through model_one.....
        {% endfor %}

            {% if model_one.has_previous %}
                 previous
            {% endif %}

                Page {{ model_one.number }} of {{ model_one.paginator.num_pages }}

            {% if model_one.has_next %}
                 next
            {% endif %}

      {% endif %}
      {% if model_two %}

        {% for item in model_two %}
        ..... iterates through model_two.....
        {% endfor %}

            {% if model_two.has_previous %}
                 previous
            {% endif %}

                Page {{ model_two.number }} of {{ model_two.paginator.num_pages }}

            {% if model_two.has_next %}
                 next
            {% endif %}

      {% endif %}

Again using 'page1' and 'page2' to distinguish the pagination for each model.

A: Sure, it is possible. I can't speak for the django-pagination package, but it definitely is possible using the default Django's Paginator class. You can create as many of them as you want inside your view. Just choose different GET parameters to specify the page for each of them and you're good to go.


text:
Q: scipy.optimize.minimize for constrained optimization in python In the below problem I'm using scipy.optimize.minimize function to solve a constrained optimization problem with 5 parameters, named params. When I debug my script in Python the optimal params returned a vector of 5-nan elements. Any ideas?
from scipy.optimize import minimize

xdata = np.arange(0, 17.5, 0.125)*0.1
xdata= xdata[60:85]
ydata = 1.0/xdata

plt.plot( xdata, ydata , 'ro', label='data')
plt.show()

def getvar(xobs, params) :
    yobs = np.asarray( [0.0]*len(xobs) )
    for i in range(len(xobs)):
        yobs[i] = params[0] + params[1] *(params[2]*(  math.log(xobs[i]) - params[3] ) +  math.sqrt( ( math.log(xobs[i]) - params[3]   )**2 + params[4]**2)  )
    return yobs

def resi(params):
    return getvar(xdata, params) - ydata

def sum_resi(params) :
    return sum( resi(params)**2 )

#Unconstrained
guess = np.asarray( [1.0,1.0,1.0,1.0,1.0] )
pwithout,cov,infodict,mesg,ier=scimin.leastsq(resiguess,full_output=True)

ylsq = getvar( xdata, pwithout)
plt.plot(xdata, ylsq,  'b--', label='fitted plot')
plt.show()

#Constrained: Use the guess from the unconstrained problem

cons = ( {'type': 'ineq','fun' : lambda params: np.array([params[0]       +   params[1]*params[4]* math.sqrt( 1 - params[2]**2 ) ]  )})
bnds = ( (None, None), (0, None), (-1,1),(None, None),(0, None) )
pwith=scimin.minimize(sum_resi,pwithout, method='SLSQP', bounds=bnds,
    constraints=cons, options={'disp': True})
ylsqconst = getvar( xdata, pwith.x)
plt.plot(xdata, ylsqconst,  'g--', label='fitted plot')
plt.show()

Notes
You can see in each iteration that all parameters satisfy the conditions. Set a debug point at i) the line defining the constraints: cons = ( {'type': 'ineq','fun'... and at ii) the line returning the sum of residuals:      return sum(resi(params)**2 ). Please let me know if you can see an error that I can't see.

A: I think the issue might be a simple typo. In the line
pwithout,cov,infodict,mesg,ier=scimin.leastsq(resiguess,full_output=True)

shouldn't it be leastsq(resi, guess, ...)?


text:
Q: PHP considers null is equal to zero In PHP, ($myvariable==0)
When $myvariable is zero, the value of the expression is true; when $myvariable is null, the value of this expression is also true. How can I exclude the second case? I mean I want the expression to be true only when $myvariable is zero. Of course I can write
($myvariable != null && $myvariable == 0)

But is there other elegant way to do this?

A: Try ($myvariable === 0) which will not perform type coercion.

A: Use the php function is_null( ) function along with the === operator. !== also works the way you'd expect.

A: You hint at a deep question: when should an expression be true?
Below, I will explain why what you are doing isn't working and how to fix it.
In many languages null, 0, and the empty string ("") all evaluate to false, this can make if statements quite succinct and intuitive, but null, 0, and "" are also all of different types. How should they be compared?
This page tells us that if we have two variables being compared, then the variables are converted as follows (exiting the table at the first match)
Type of First  Type of Second   Then
null/string    string           Convert NULL to "", numerical/lexical comparison
bool/null      anything         Convert to bool, FALSE < TRUE

So you are comparing a null versus a number. Therefore, both the null and the number are converted to boolean. This page tells us that in such a conversion both null and 0 are considered FALSE.
Your expression now reads, false==false, which, of course, is true.
But not what you want.
This page provides a list of PHP's comparison operators.
Example   Name                Result
$a ==  $b  Equal              TRUE if $a equals $b after type juggling.
$a === $b  Identical          TRUE if $a equals $b, AND they are of the same type.
$a !=  $b  Not equal          TRUE if $a not equals $b after type juggling.
$a <>  $b  Not equal          TRUE if $a not equals $b after type juggling.
$a !== $b  Not identical      TRUE if $a not equals $b, or they are not of the same type.
$a  <  $b  Less than          TRUE if $a is strictly less than $b.
$a  >  $b  Greater than       TRUE if $a is strictly greater than $b.
$a <=  $b  Less than/equal    TRUE if $a is less than or equal to $b.
$a >=  $b  Greater than/equal TRUE if $a is greater than or equal to $b.

The first comparator is the comparison you are using now. Note that it performs the conversions I mentioned earlier.
Using the second comparator will fix your problem. Since a null and a number are not of the same type, the === comparison will return false, rather than performing type conversion as the == operator would.
Hope this helps.

A: To identify as null or zero by:

*

*is_int($var) if a variable is a number or a numeric string. To identify Zero, use is_numeric($var) is also the solution or use $var === 0

*is_null($var) if a variable is NULL

A: $myvariable === 0

read more about comparison operators.

A: The second solution wouldn't work either. The === operator is the solution to your problem.

A: If your zero could be a string, you should also considere checking the "zero string"
($myvariable === 0 || $myvariable === '0')

A: I hade faced a similar issue in one of my projects, with a minor difference that I was also using the values ZERO as a valid value for my condition. here's how I solved it using simple logic to separate NULL from zero and other values.
    if (gettype($company_id) === 'NULL') {
        $company = Company::where('id', Auth::user()->company_id)->first();
    } else {
        $company = Company::where('id', $company_id)->first();
    }

A: $myvariable===0

$a === $b

Identical TRUE if $a is equal to $b, and they are of the same type

A: There's an is_null function, but this will just replace your $myvariable!=null

A: For my case i found this soulution and it works for me :
if ($myvariable === NULL) {
    codehere...
}


text:
Q: What relation between vitality and HP max of character in FF7? I search the formula between vitality carac and HP MAX? in Final Fantasy 7
It's increased by level, but how first HP max are determined? And after how is determinated HP MAX by vitality?

A: It's not

From GameFAQs

HP Baseline = Base +  (Level - 1) * Gradient
MP Baseline = Base + [(Level - 1) * Gradient / 10]

And from the same guide, here are the variables:
=============================================================================
        L 2-11   L12-21   L22-31   L32-41   L42-51   L52-61   L62-81   L82-99
 Char   Grd Bs   Grd Bs   Grd Bs   Grd Bs   Grd Bs   Grd Bs   Grd Bs   Grd Bs
=============================================================================
Cloud   20  15   10  16   10  16    8  17    8  17    8  17    7  18    6  19
Barret  15  14    8  15    8  15    7  15    6  16    5  17    4  18    3  20
Tifa    20  14   10  15   10  15    9  16    9  17   10  17   10  17    6  20
Aeris   18  14    8  15    8  15    8  16    8  16    5  18    7  17    7  17
Red     18  14    8  15    8  15    8  16    8  16    5  18    7  17    7  17
Yuffie  20  16   10  17   10  17   10  17    8  18   10  18   10  18    9  19
Cait    20  14   10  15   10  15    9  16    9  17   10  17   10  17    6  20
Vince   20  14   10  15   10  15    9  16    9  17   10  17   10  17    6  20
Cid     15  14    8  15    8  15    7  15    6  16    5  17    4  18    3  20
=============================================================================


text:
Q: MySQL count elements in a database based on how many unique values there are in a field (Sorry for the title, I don't really know how to phrase that :-) )
I have a table that has a date and a uid fields.
I need to get the number of uid for each date, currently I'm doing it in php running multiple queries like this one:
SELECT COUNT(uid) FROM users where Date = 'xxx';

Is there a simple way to achieve this with only an sql query?

A: Use the group by clause:
SELECT Date, COUNT(uid) FROM users group by Date;

A: To count the number of unique values use DISTINCT:
SELECT COUNT(DISTINCT uid) AS cnt
FROM users
GROUP BY `Date`

If your column is a datetime then you should use the DATE function to get the date part only:
SELECT COUNT(DISTINCT uid) AS cnt
FROM users
GROUP BY DATE(`Date`)

A: SELECT Date, COUNT(uid) FROM users GROUP BY Date


text:
Q: Pentaho removed SolutionRepositoryService services? I'm updating my Java client code from Pentaho BA v3.7 to 5.1.
Many things are still working, except that my code can't find the SolutionRepositoryService services.
The URL http:// localhost:8080/pentaho/SolutionRepositoryService?component=XXX is not working on the new version.
What is the URL for these services? Do I have to install anything else?
Thanks and regards.

A: Yes, they changed in v5.0 their whole API, and now they use a REST API.
Here is de descriptor file:
http://javadoc.pentaho.com/bi-platform500/webservice500/application.wadl
Import it to SoapUI and you're good to go to test the services.


text:
Q: Data modeling on cassandra? I have an email marketting project, after long time researched, I decided to
use cassandra to store my data.
My business is to allow my customers to create campaign, then import users from my users database,
then send an email to them. After receive our email, the user maybe do some actions (open, view item, buy, complain, unsubscribe ...), I will log this actions based on its campaign.
My data structure is :

*

*Each custommer can create one or more campaigns.

*Each campaign include a alot of users.

*Each user can do zero or many actions on a campaign.

This is my first time with cassandra, I've searched and read many source from google but was still
confusing about how my data modeling.
Update: my queries
I need to do the below queries:

*

*List all campaigns in system

*List all campaigns for a customer

*Insert the action log whenever user did an action on a campaign

*List all users in a campaigns with the actions that they did, including the occurred
time for each action (as a table, with paging)

*

*The columns is actions

*Each row is an user

*Each cell is the occurred time for action on user

Please give me an idea or introduce some articles for me on how to model my data?
Thanks very much.

A: In Cassandra, you model your tables according to your queries; not to the relation between your entities. This means duplicated data is ok, normal and encouraged. Remember, there are no relations between your tables.
So if your query is about listing all campaigns that belong to a customer, this means that your 'customer' table should contains denormalized data. The same goes to rest of your queries.


text:
Q: why are multiple shared_future objects needed to synchronize data A pointer to a data structure is shared with multiple threads via std::promise and std::shared_future.
From the book 'C++ concurrency in action' by Anthony Williams (pg. 85-86), it seems that data is only correctly synchronized when each receiving thread uses a copy
of the std::shared_future object as opposed to each thread accessing a single, global std::shared_future.
To illustrate, consider a thread creating bigdata and passing a pointer to multiple threads that have read-only access.
If data synchronization between threads is not handled correctly, memory reordering may lead to undefined behavior (eg. a worker_thread reading incomplete data).
This (incorrect ?) implementation uses a single, global std::shared_future:
#include <future>

struct bigdata { ... };

std::shared_future<bigdata *> global_sf;

void worker_thread()
{
    const bigdata *ptr = global_sf.get();
    ...  // ptr read-only access
}

int main()
{
    std::promise<bigdata *> pr;
    global_sf = pr.get_future().share();

    std::thread t1{worker_thread};
    std::thread t2{worker_thread};

    pr.set_value(new bigdata);
    ...
}

And in this (correct) implementation, each worker_thread gets a copy of std::shared_future:
void worker_thread(std::shared_future<bigdata *> sf)
{
    const bigdata *ptr = sf.get();
    ...
}

int main()
{
    std::promise<bigdata *> pr;
    auto sf = pr.get_future().share();

    std::thread t1{worker_thread, sf};
    std::thread t2{worker_thread, sf};

    pr.set_value(new bigdata);
    ....

I am wondering why the first version is incorrect.
If std::shared_future::get() was a non-const member function, it would make sense since accessing a single std::shared_future from multiple threads would then be a data race itself.
But since this member function is declared const, and the global_sf object is synchronized with the threads, it is safe to access concurrently from multiple threads.
My question is, why exactly is this only guaranteed to work correctly if each worker_thread receives a copy of the std::shared_future ?

A: Your implementation using a single, global shared_future is completely fine, if slightly unusual, and the book appears to be mistaken.

[futures.shared_future] ¶2
[ Note: Member functions of shared_future do not synchronize with themselves, but they synchronize with the shared state. — end note ]

Notes are non-normative, so the above is redundantly making explicit a fact which is already implicit in the normative wording.

[intro.races] ¶2
Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location.
¶6
Certain library calls synchronize with other library calls performed by another thread.
[...Additional paragraphs defining happens before in terms of synchronizes with...]
¶19
Two actions are potentially concurrent if they are performed by different threads... The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other...
[res.on.data.races] ¶3
A C++ standard library function shall not directly or indirectly modify objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's non-const arguments, including this.

So we know that calls to global_sf.get() in different threads are potentially concurrent unless you accompany them with additional synchronization (e.g. a mutex). But we also know that calls to global_sf.get() in different threads do not conflict, because it is a const method and hence forbidden from modifying objects accessible from multiple threads, including *this. So the definition of a data race (unsequenced, potentially concurrent conflicting actions) is not satisfied, the program does not contain a data race.
One would usually wish to avoid global variables anyway, but that is a separate issue.
Note that if the book is correct, then it contains a contradiction. The code which it claims is correct still contains a global shared_future which is accessed from multiple threads when they create their local copies:
void worker_thread()
{
    auto local_sf = global_sf; // <-- unsynchronized access of global_sf here

    const bigdata *ptr = local_sf.get();
    ...
}


text:
Q: Decrypted String always returning Null Data fetched from server using
var request = var request = URLRequest(url: URL(string: "http://www.example.com/test.php")!)
        request.httpMethod = "POST"
        let akey:String =  txt_key.stringValue;
        let email:String = txt_email.stringValue
        let VAL:String="test"
        var data="blah"
        let postString = data
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 /
                print("error=\(error)")
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           /
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
            let responseString = String(data: data, encoding:  .utf8)
            print(responseString)
        }
        task.resume()

Decryption using
   func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
            let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCDecrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      data.bytes, data.length,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
                return unencryptedMessage
            }
            else {
                return nil
            }
        }
        return nil
}

Even when responseString is not null,The following code always returns
optional("")
 let unencode = String(describing: responseString!).aesDecrypt(key: "123456789012asdsadasd", iv: "iv-salt-string--")

Why is this happening ? Please advice.

A: Per MartinR's comment:

I have verified that "JDoNBXk21oJ9x15Bkv12uw==" is exactly the result of encrypting an empty string with your key and iv. The error is in your PHP script, not in the Swift code.

Therefore you need to resolve the error on the server.


text:
Q: I want to draw one element out from a tibble variable in R I have a dataframe that consist of multiple variables, and some of them are tibbles.
i have variables like:

[ID, name, symbol, category, urls,....,slug]

In this case slug is a tibble and consist of multiple urls of interst such as [Website, facebooksite, twitter,..,reddit]
I would like to draw out only webpage for each asset as a new variable.
So far I figured out I can get the webpage for
ID=1 data$urls[[1]][1,] and for ID=2 crypto.info1$urls[[2]][1,]

output is
A tibble: 1 x 2
  name    url
  <chr>   <chr>
1 website https://bitcoin.org/

but I want for every ID in a new variable. I hope someone can assist me.
Data example:
| ID |  Name   |Category |   Urls    |
| -- | --------|---------|-----------|
| 1  | Bitcoin |Coin     |2 variables|
| 2  | Litecoin|Coin     |3 variables|
| .  | ........|......   |...........|

when urls is opened it looks like:
Data example:
|  Name   |              url           |
| --------|----------------------------|
| Website |https://bitcoin.org/        |
| Reddit  |https://reddit.com/r/bitcoin|
| ........|......                      |

A: With lack of context, you can use a for loop. Since you just want the website you can edit the indexing slightly like how I did in the code below.
Disclaimer: I have not ran this code, if you see an error please let me know.
Also: I know this is with a for loop and not vectorized.
urls <- c()

for(i in 1:length(data$urls)){

urls[i] <- data$urls[[i]][1,2]
}

If I understand your problem correctly, with the above code urls will be a vector of the websites extracted.
Hope this helps.

A: urls <- c()

for(i in 1:length(data$urls)){

urls[i] <- data$urls[[i]][1,2]
}
data$Website <- urls

Thanks to Bensstats send me in the right direction

A: If you don't mind the made-up example, here's an alternative approach:
library(tidyverse)

# Made-up data
df <- tribble(~id, ~name, ~url,
        1, "website", "bitcoin.org",
        1, "twitter", "#this",
        2, "website", "bitcoin.net",
        2, "twitter", "#that",
        3, "website", "bitcoin.biz",
        3, "twitter", "#other",
        ) |>
  nest(slug = -id)

# Pluck the url
df |> mutate(website = map_chr(slug, pluck, "url", 1))
#> # A tibble: 3 × 3
#>      id slug             website
#>   <dbl> <list>           <chr>
#> 1     1 <tibble [2 × 2]> bitcoin.org
#> 2     2 <tibble [2 × 2]> bitcoin.net
#> 3     3 <tibble [2 × 2]> bitcoin.biz

Created on 2022-05-26 by the reprex package (v2.0.1)


text:
Q: How to solve org.apache.http.NoHttpResponseException I'm using apache httpclient 4.4 to do https requests, and I can constantly to see  org.apache.http.NoHttpResponseException.
Here's my code to create the httpclient.
   TrustManager[] trustAllCerts =
         new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
               return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs,
                  String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs,
                  String authType) {
            }

         } };
   SSLContext sslcontext = null;
   try {
      sslcontext = SSLContext.getInstance("SSL");
      sslcontext.init(null, trustAllCerts, new java.security.SecureRandom());
   } catch (NoSuchAlgorithmException e) {
      logger.warn(e.getMessage());
   } catch (KeyManagementException e) {
      logger.warn(e.getMessage());
   }
   // Allow TLSv1 protocol only
   final SSLConnectionSocketFactory sslsf =
         new SSLConnectionSocketFactory(sslcontext,
               new String[] { "TLSv1" }, null, NoopHostnameVerifier.INSTANCE);

   Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
         .<ConnectionSocketFactory> create().register("https", sslsf)
         .build();
   PoolingHttpClientConnectionManager cm =
         new PoolingHttpClientConnectionManager(socketFactoryRegistry);

   // Increase max total connection to 200
   cm.setMaxTotal(200);
   // Increase default max connection per route to 20
   cm.setDefaultMaxPerRoute(20);

Before execute the request, I do cm.closeExpiredConnections(); and conMgr.closeIdleConnections(30, TimeUnit.SECONDS).  I added this after I read the answer of this question
Anything more I need to do?

A: Another way around this issue is to configure your org.apache.http.impl.client.AbstractHttpClient httpClient to never reuse connections:
httpClient.setReuseStrategy(new NoConnectionReuseStrategy());

The same can be configured on a org.apache.http.impl.client.HttpClientBuilder builder:
builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());

A: Finally figured it out on my own.  If the previous response gives header, "connections=close", next request always gets this exception.  So, when seeing this header, put 2 more lines
conManager.closeExpiredConnections();
conManager.closeIdleConnections(0, TimeUnit.SECONDS);

to let connection manager close the connection so that the connection won't be used by the next request.


text:
Q: A set of bounded and continuous functions under supnorm is a commutative algebra with a multiplication identity Question:
Let $(X, d)$ be a metric space. Denote all bounded and continuous functions from $X \rightarrow \mathbb{R}$ as $BC(X,\mathbb{R})$, the topology of which is supnorm. Show that $BC(X,\mathbb{R})$ is a commutative algebra with a multiplication identity
Thoughts:
(1) I define some basic settings: $(f + g)(x) = f(x) + g(x)$ and $(fg)(x) = f(x)g(x)$. Also, for $\alpha \in \mathbb{R}$, define $(\alpha f)(x) = \alpha f(x)$.
(2) Then I think I need to prove it in three steps, but I don't know how to do it, especially what I should do about $\circ$:
(i) $BC(X,\mathbb{R})$ is an algebra:
for every $a$, $b$, $c \in BC(X,\mathbb{R})$, they satisfy:
$a \circ (b \circ c) = (a \circ b) \circ c$
$a \circ (b+c) = (a \circ b) + (a \circ c)$
$(a+b) \circ c = (a \circ c) + (b \circ c)$
(ii) $BC(X,\mathbb{R})$ is a commutative algebra:
$a \circ b = b\circ a$ for all $a$, $b \in A$
(iii) $BC(X,\mathbb{R})$ has a multiplicative identity:
$a \circ 1 = 1 \circ a = a$ for all $a \in A$
I am having a hard time to transform $\circ$ to something related to the supnorm that I can compute. Can anyone give me some hints on it? I feel like I can solve the rest of the problem.

A: Now what you've done so far is almost complete. You've not shown that $B(X,\Bbb R)$ is closed under the operations of point wise multiplication and addition. But that is easy:
If $f,g$ are bounded and continuous on $X$, then $\|f+g\| \leq \|f\| +\|g\|$(where $\| \|$ is the sup norm). I've used the famous triangle ineqaulity here. If you've not encountered this before, take it as an exercise(it follows from the triangle inequality for real numbers). This shows that $f+g$ is bounded. I'll leave it to you to show that $f+g$ is continuous. Hence $B(X,\Bbb R)$ is closed under point wise addition.
Similar arguments show that $B(X,\Bbb R)$ is closed under multiplication. With this and what you've done, what you sought out to prove is complete.


text:
Q: MongoServerError: bad auth : Authentication failed. despite all solutions Hi all so I went through the MERN Stack tutorial: https://www.mongodb.com/languages/mern-stack-tutorial.
Am not able to connect successfully to MongoDB.
Server is running on port: 8080
MongoServerError: bad auth : Authentication failed.
    at Connection.onMessage (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/connection.js:227:30)
    at MessageStream.<anonymous> (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/connection.js:60:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
    at MessageStream._write (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at TLSSocket.ondata (node:internal/streams/readable:766:22)
    at TLSSocket.emit (node:events:513:28) {
  ok: 0,
  code: 8000,
  codeName: 'AtlasError',
  connectionGeneration: 0,
  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }

The 'config.env' file contains this:
ATLAS_URI=mongodb+srv://correctusername:correctpassword@atlascluster.zgubjgl.mongodb.net/employees?retryWrites=true&w=majority
PORT=8080

The 'conn.js' contains:
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

var _db;

module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      // Verify we got a good "db" object
      if (db)
      {
        _db = db.db("employees");
        console.log("Successfully connected to MongoDB.");
      }
      return callback(err);
         });
  },

  getDb: function () {
    return _db;
  },
};

Solutions attempted:

*

*Ensured that the username and password do not have '<>' enclosing them.

*Created a new user in 'Database Access' in MongoDB itself with 'readWriteAnyDatabase@admin' access to mirror the ending of the ATLAS_URI connection string, same error.

*Removed 'employees' in connection string and tried again, same error.

*Tried another database name in both 'config.env' and 'conn.js' files, same error.

*Ensured that my 'Network Access' in MongoDB itself is '0.0.0.0/0  (includes your current IP address)'.

*Ensured that cluster name matches.

All of the solutions above are things I tried based off what I have researched on Stack. Is the problem that I don't have an employees database set up on MongoDB itself? Or is it a security setting on my Mac that is causing an issue?
Please help - feeling very downtrodden that I have reached this obstacle as I have a really good platform idea to start a business based on.


text:
Q: EStyleSheet Media queries and window resize I'm using React Native Extended StyleSheet to build a React Native app for WINDOWS.
When I use Media queries I get the query of the moment the app is launch, however I need It to be dynamic.
When I resize my app window I don't see my styles changing accordingly to the rules I have created. All the rules works, but none are fired by window resize.
Does anyone has a solution for that?

A: I recreate my eStylesheet when I detect the change. I don't think it does that automatically for you.


text:
Q: How to display elements of array inside an object I am having a JSON data file from I have to extract some information and display it using react js. I am getting stuck in display the elements of the array.
This is my data.js file
const details = [
  {
    environment: "prod",
    account_number: "057346956084",
    regions: [
      {
        region_one: "10.0.0.0/24"
      }
    ],
    bu: "CIO and Central Tech",
    account_alias: "tr-novus-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "749444856751",
    regions: [
      {
        region_one: "172.31.0.0/16",
        region_three: "172.30.0.0/16"
      }
    ],
    bu: "CIO and Central Tech",
    account_alias: "tr-gcs-normalization-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "238963201434",
    regions: [
      {
        region_one: "10.37.128.0/20",
        region_three: "10.37.144.0/20"
      }
    ],
    bu: "dcis",
    account_alias: "tr-tax-cp-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "209911870440",
    regions: [
      {
        region_one: "10.150.8.0/21",
        region_three: "10.168.0.0/21"
      }
    ],
    bu: "tax",
    account_alias: "tr-learning-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "933497097166",
    regions: [
      {
        region_six: "10.39.176.0/22",
        region_one: "10.39.160.0/21",
        region_three: "10.39.168.0/21",
        region_four: "10.39.124.0/22"
      }
    ],
    bu: "Corporates",
    account_alias: "tr-integrationpoint-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "777737700635",
    regions: [
      {
        region_nine: "10.152.158.0/24",
        region_ten: "10.97.207.0/24",
        region_one: "10.97.203.0/24",
        region_five: "10.97.205.0/24",
        region_four: "10.97.206.0/24",
        region_three: "10.97.204.0/24"
      }
    ],
    bu: "dcis",
    account_alias: "tr-isrm-ad-prod",
    resource_name: "account_info"
  },
  {
    environment: "nonprod",
    account_number: "586447969888",
    regions: [
      {
        region_one: "10.226.208.0/21",
        region_three: "10.39.8.0/21"
      }
    ],
    bu: "CIO and Central Tech",
    account_alias: "tr-content-console-preprod",
    resource_name: "account_info"
  },  {
    environment: "nonprod",
    account_number: "755189330144",
    regions: [{}],
    bu: "CIO and Central Tech",
    account_alias: "tr-quicksight-preprod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "460300312212",
    regions: [
      {
        region_one: "10.152.140.0/22",
        region_four: "10.152.136.0/22"
      }
    ],
    bu: "dcis",
    account_alias: "tr-enterprise-cicd-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "470717676343",
    regions: [{}],
    bu: "CIO and Central Tech",
    account_alias: "tr-wellarchitected-tool-prod",
    resource_name: "account_info"
  },
  {
    environment: "prod",
    account_number: "249922119495",
    regions: [
      {
        region_one: "10.97.248.0/21",
        region_three: "10.62.56.0/21"
      }
    ],
    bu: "CIO and Central Tech",
    account_alias: "tr-authorities-prod",
    resource_name: "account_info"
  },
  {
    environment: "nonprod",
    account_number: "043533679309",
    regions: [
      {
        region_five: "10.60.168.0/22",
        region_four: "10.60.164.0/22",
        region_ten: "10.37.212.0/23",
        region_one: "10.37.224.0/20",
        region_seven: "10.60.160.0/24",
        region_two: "10.37.214.0/23",
        region_three: "10.60.144.0/20"
      }
    ],
    bu: "corporate",
    account_alias: "tr-tax-proflgcy1-nonprod",
    resource_name: "account_info"
  },
]

This is my code where I have to display the data in the table.
import React, { Component } from "react";
import $ from "jquery";
import "./../css/index.css";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import details from '../data';

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = { //state is by default an object
      accounts : details
   }
  }
  renderTableData() {
    return this.state.accounts.map((account, index) => {
       const { environment, account_number,regions,bu,account_alias,resource_name } = account; //destructuring
       return (

             {account_number}
             {account_alias}
             {bu}
             {account_alias}
             {environment}
              {regions}

       )
    })
  }
  render() {
    return (

                  Account Number
                  Account Alias
                  us-east-2
                  us-east-1
                  us-gov-west-1
                  us-gov-east-1

            {this.renderTableData()}

    );
  }
}

export default Table;

when I am trying to map through the data and destructure the elements when I am trying to display the element I am getting error

Error: Objects are not valid as a React child (found: object with keys
  {region_one}). If you meant to render a collection of children, use an
  array instead.

Could anyone please help me

A: You are getting the error because each element of details contains a nested object array by the name of regions. What you can do is remove the "{" and "}" inside the regions array and then refer to it as a simple array while rendering

A: You cannot have a javascript Array/Object or anything really inside HTML(without the  tags). You can do what Willy Wonka above has said. Just put the values of the object inside the array as
['172.31.0.0/16','172.30.0.0/16']

or just have an object as value of regions as
  {
    region_one: "172.31.0.0/16",
    region_three: "172.30.0.0/16"
  }

You can iterate through the regions in the object as
let regionString = ''
for(let region in regions){
    regionString+ = region + ' '
}

Then you can have a string where you will put the string in the data cell as {regionString} sth like that. Hope you got it :)


text:
Q: Как исправить ошибку «Строки нельзя программным способом добавить в коллекцию строк DataGridView, если элемент управления привязан к данным.»? Есть форма, на ней два DataGridView: первый берет данные из реестра и заполняется при загрузке формы, второй пустой и в него мы переносим строки из первого. При переносе с первого во второй все работает как нужно, а при переносе из второго в первый вылазит ошибка

Строки нельзя программным способом добавить в коллекцию строк DataGridView, если элемент управления привязан к данным.

Как ее исправить?
Вот сама форма:

Кнопка "Добавить в список" работает как надо, а вот "Удалить из списка" нет, вот ее код:
private void minus_program_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in Yes_white.SelectedRows)
        {
            object[] items = new object[row.Cells.Count];
            for (int i = 0; i < row.Cells.Count; i++)
            {
                items[i] = row.Cells[i].Value;
            }
            Not_white.Rows.Add(items);
            Yes_white.Rows.Remove(row);
        }
    }

Ошибка вылазит вот на этой строчке:
Not_white.Rows.Add(items);

Как исправить данную ошибку?

A: Схематично покажу
Берете 2 листа
private readonly BindingList<ВашТипДанных> list1 = new BindingList<ВашТипДанных>();
private readonly BindingList<ВашТипДанных> list2 = new BindingList<ВашТипДанных>();

Закидываете в DataSource, можно даже в конструкторе формы однократно это сделать.
dataGridView1.DataSource = list1;
dataGridView2.DataSource = list2;

Затем заполняете их как нужно в методе загрузки данных.
Чтобы перекинуть выделенный элемент из списка 1 в список 2, достаточно сделать
if (dataGridView1.SelectedRows.Cast<DataGridViewRow>().FirstOrDefault()?.DataBoundItem is ВашТипДанных item)
{
    list1.Remove(item);
    list2.Add(item);
}

Всё, больше ничего не надо. Обратная операция выглядит точно так же.


text:
Q: How to make a Pausable Executor notify user of paused state I have implemented a pausable executor following exactly the example given in the documentation: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
 class PausableThreadPoolExecutor extends ThreadPoolExecutor {
   private boolean isPaused;
   private ReentrantLock pauseLock = new ReentrantLock();
   private Condition unpaused = pauseLock.newCondition();

   public PausableThreadPoolExecutor(...) { super(...); }

   protected void beforeExecute(Thread t, Runnable r) {
     super.beforeExecute(t, r);
     pauseLock.lock();
     try {
       while (isPaused) unpaused.await();
     } catch (InterruptedException ie) {
       t.interrupt();
     } finally {
       pauseLock.unlock();
     }
   }

   public void pause() {
     pauseLock.lock();
     try {
       isPaused = true;
     } finally {
       pauseLock.unlock();
     }
   }

   public void resume() {
     pauseLock.lock();
     try {
       isPaused = false;
       unpaused.signalAll();
     } finally {
       pauseLock.unlock();
     }
   }
 }

In my program, the tasks are composed of simulations that take a while to finish. When the user triggers pause, the currently running simulations will proceed but the next ones in queue will have to wait until the user triggers resume.
In that sense the pause is not instantaneous: there is a wait time between the user triggers pause and the actual paused state.
How do I modify this code block to signal back to the user that the program is in the actual paused state i.e. the last running tasks have finished and the next in queue are waiting for the resume trigger?


text:
Q: AKS cluster creating additional route table, additional NSG and its not using existing custom route table and NSG I've recently started working on terraform with azure. As part of it i've gone through the documentation as much as possible to create resources. in this i'm trying to create AKS cluster. I was able to created successfully. but i've few concerns( which i felt bugs, correct if i'm wrong).
At present during AKS cluster provision, aks-engine will create route table & Network security automatically. i don't see any option to prevent these in terraform documentaion. As i wanted use existing route-table and NSG as because i'm under corporate network.
expected behavior : ASK should pick existing route table and NSG instead of creating new resources.
here is my code snippet. kindly help me.
provider "azurerm" {
    version = "~> 2.15"
    features {}
 }

resource "azurerm_resource_group" "aks" {
    name     = var.resource_group
    location = var.location
}
#fetch existing subnet
data "azurerm_subnet" "aks" {
    name                 = var.subnetname
    virtual_network_name = var.virtual_network_name
    resource_group_name  = var.vnet_resource_group
}

resource "azurerm_subnet_network_security_group_association" "aks" {
    subnet_id                 = data.azurerm_subnet.aks.id
    network_security_group_id = var.network_security_group
}

resource "azurerm_route_table" "aks"{
    name                          = var.subnetname
    resource_group_name           = azurerm_resource_group.aks.name
    location                      = azurerm_resource_group.aks.location
    disable_bgp_route_propagation = false

    route{
        name                = var.route_name
        address_prefix      = var.route_address_prefix
        next_hop_type       = var.route_next_hop_type
    }

}
resource "azurerm_subnet_route_table_association" "aks" {
    subnet_id      = data.azurerm_subnet.aks.id
    route_table_id = azurerm_route_table.aks.id
}
resource "azurerm_kubernetes_cluster" "aks" {
    name                    = azurerm_resource_group.aks.name
    resource_group_name     = azurerm_resource_group.aks.name
    location                = azurerm_resource_group.aks.location
    dns_prefix              = "akstfpoc"   #The dns_prefix must contain between 3 and 45 characters, and can contain only letters, numbers, and hyphens. It must start with a letter and must end with a letter or a number.
    kubernetes_version      = "1.15.10"
    private_cluster_enabled = false
    node_resource_group     = var.node_resource_group

    api_server_authorized_ip_ranges = [] #var.api_server_authorized_ip_ranges
    default_node_pool {
        enable_node_public_ip   = false
        name                    = "agentpool"
        node_count              = var.node_count
        orchestrator_version    = "1.15.10"
        vm_size                 = var.vm_size
        os_disk_size_gb         = var.os_disk_size_gb
        vnet_subnet_id          = data.azurerm_subnet.aks.id
    }

    linux_profile {
        admin_username = var.admin_username
        ssh_key {
            key_data = var.ssh_key
        }
    }
    service_principal {
        client_id     = var.client_id
        client_secret = var.client_secret
    }

    role_based_access_control {
        enabled = true
    }
    network_profile {
        network_plugin = "kubenet"
        #dns_service_ip     = "172.17.1.10"
        #service_cidr       = "172.16.0.0/14"
        pod_cidr           = "172.40.0.0/16"
        network_policy     = "calico"
        outbound_type      = "loadBalancer"
        load_balancer_sku  = "Standard"

        # load_balancer_profile {
        #     managed_outbound_ip_count = []
        #     outbound_ip_address_ids   = []
        #     outbound_ip_prefix_ids    = [""]

        # }
    }
            addon_profile {
            aci_connector_linux {
            enabled = false
        }

        azure_policy {
            enabled = false
        }

        http_application_routing {
            enabled = false
        }

        kube_dashboard {
            enabled = false
        }

        oms_agent {
            enabled = false
        }
    }

}

A: To use a private Subnet, you should use the
network_plugin = "azure"
this will allow you to tie your AKS cluster to a pre existing Subnet which you will have full control over the Route Table and the NSG (you can pre create them and associated them with your subnet with Terraform)
Have a look at the documentation on how to use the azure-cli
https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni
for Terraform you will need to set
vnet_subnet_id on the default_agent_pool: https://www.terraform.io/docs/providers/azurerm/r/kubernetes_cluster.html#vnet_subnet_id
https://www.terraform.io/docs/providers/azurerm/r/kubernetes_cluster.html#network_profile


text:
Q: Python 3 - Writing data from struct.unpack into json without individual recasting I have a large object that is read from a binary file using struct.unpack and some of the values are character arrays which are read as bytes.
Since the character arrays in Python 3 are read as bytes instead of string (like in Python 2) they cannot be directly passed to json.dumps since "bytes" are not JSON serializable.
Is there any way to go from unpacked struct to json without searching through each value and converting the bytes to strings?

A: You can use a custom encoder in this case. See below
import json

x = {}
x['bytes'] = [b"i am bytes", "test"]
x['string'] = "strings"
x['unicode'] = u"unicode string"

class MyEncoder(json.JSONEncoder):
    def default(self, o):
        if type(o) is bytes:
            return o.decode("utf-8")
        return super(MyEncoder, self).default(o)

print(json.dumps(x, cls=MyEncoder))
# {"bytes": ["i am bytes", "test"], "string": "strings", "unicode": "unicode string"}


text:
Q: Redirect www.domain.com/post/ to www.domain.com/post.html wordpress htaccess I want to remove year and month and redirect my old post from google search from
here is my htaccess code
BEGIN WordPress
 <IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^m=1$
RewriteRule ^(.*)$ /$1? [R=301,L]
Options -MultiViews
RedirectMatch 301 ^/[0-9]{4}/[0-9]{2}/([a-z0-9\-/]+) https://newkannada.com/$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ $1.html [L,R=301]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

But it appending .html to categories also
any help thanks in advance


text:
Q: Point icons disappearing in OpenLayers? I have a very simple setup where I have a feature vector layer on top of an OSM layer in OpenLayers 2.13.1. However, I notice that the icons of my points in the vector layer begin to 'become invisible' despite their SVG DOM bounds being positioned where the icon should be, making them sort of invisible as I zoom in.
The layer that holds my features is not overly exciting:
var ooiLayer = new OpenLayers.Layer.Vector('OOI Layer');

And here is how I create my feature vectors:
// Declared elsewhere but added for completeness sake
var ooiStyle = $.extend({}, OpenLayers.Feature.Vector.style['default'], {
    graphicWidth: 25,
    graphicHeight: 25,
    fillOpacity:.7,
    externalGraphic: 'img/ooi.png'
});

function add(ooi) {
    var wkt = new OpenLayers.Format.WKT(ooi);

    // The following line looks more complicated than it is. Assume the variable holds something like "POINT (31.123 34.321)" after evaluation.
    var wktData = ooi.entityInstancesGeometry[0].geometry.geometry.wellKnownText;
    var vector = wkt.read(wktData);
    if (ooi.entityTypeId == 14 && vector.geometry instanceof OpenLayers.Geometry.Point)
        this.createArea.call(this, vector.geometry.x, vector.geometry.y, ooi);
    else {
        var actualVector = new OpenLayers.Feature.Vector(
            latLon(vector.geometry.x, vector.geometry.y), // just a helper function that applies the correct projection if required; works as intended, so no worries here
            ooi,
            $.extend({}, ooiStyle, {
                title: ooi.entityName,
                externalGraphic: graphicFor(ooi.entityTypeId) // returns an URL to a 25x25 PNG
             })
        );

        ooiLayer.addFeatures(actualVector);
    }
}

From the looks of it, it almost appears as if the first icon on the map sets the visual bounding box for all the other icons. I've created a small example to illustrate this behavior: http://youtu.be/_axFRI6Pw1U
What is wrong here?

A: I am not sure if this is the actual underlying problem, but it would appear that not using the SVG renderer (which OpenLayers seems to use by default for Chrome) fixes this issue. If anyone needs a solution, this did the trick for me:
var ooiLayer = new OpenLayers.Layer.Vector('OOI Layer', { renderers: ["Canvas", "SVG", "VML"] });

A: Try adding a zIndex to your markers like this.
map.addLayers( [ooiLayer] );
ooiLayer.setZIndex( 1001 );

Note:  the value of 1001 is probably excessive and a single digit value will probably be enough


text:
Q: How to fix this OpenCV Error: Assertion failed ((unsigned)i < (unsigned)cn) in cv::Vec::operator (), file I'm setting up an random aria for an object from an image at image processing for an exercise in my desktop application for school. Where do I need to put the value of my colour(there are the 3 colour of canals) magenta?
`
void first(Mat img, Vec3b magenta)
{
    int H = 255;
    int W = 255;
    int n = 255;
    int aria=0;

    for (int r = 0; r < H - 1; r++){
        for (int c = 0; c < W - 1; c++){
            int pixel = img.at<uchar>(r, c);
            for (int i = 0; i < n; i++){
                if (pixel = magenta(i))
                    aria++;

            }

        }
    }
    printf("Aria obiectului este:%d \n", aria);
}

void MyCallBackFunc1(int event, int x, int y, int flags, void* param)
{
    //More examples: http://opencvexamples.blogspot.com/2014/01/detect-mouse-clicks-and-moves-on-image.html
    Mat* src = (Mat*)param;
//  int aria;
    if (event == CV_EVENT_LBUTTONDOWN)
    {
        printf("Pos(x,y): %d,%d  Color(RGB): %d,%d,%d\n",
            x, y,

            (int)(*src).at<Vec3b>(y, x)[2],
            (int)(*src).at<Vec3b>(y, x)[1],
            (int)(*src).at<Vec3b>(y, x)[0]);
        Vec3b magenta;
        magenta[0] = (int)(*src).at<Vec3b>(y, x)[0];
        magenta[1] = (int)(*src).at<Vec3b>(y, x)[1];
        magenta[2] = (int)(*src).at<Vec3b>(y, x)[2];
        Mat img = ((Mat*)param)->clone();
        first(img, magenta);

    }
}

void testMouseClick1()
{
    Mat src;
    // Read image from file
    char fname[MAX_PATH];
    while (openFileDlg(fname))
    {
        src = imread(fname);
        //Create a window
        namedWindow("Window", 1);

        //set the callback function for any mouse event
        setMouseCallback("Window", MyCallBackFunc1, &src);

        //show the image

        imshow("Window", src);

        // Wait until user press some key
        waitKey(0);
    }
}

My function is called First and it calculates the aria of an object image given by the parameter Mat img. I'm usingmy function in TheCallBackFunc1 where I call the TestMouseClick1 which prints the position of the mouse coordinates.

A: I discover that there is a problem with '=' and I put '==' and the problem still persist.
First-chance exception at 0x76CB18A2 in OpenCVApplication.exe: Microsoft C++ exception: cv::Exception at memory location 0x00B2E484.
If there is a handler for this exception, the program may be safely continued.