text:
Q: Will this particular use of an anonymous Runnable cause a memory leak? private class ProductFragment extends Fragment implements OnGetProductFromDBListener {

    Activity a;

    void onCreate {
         a = getActivity();
        new GetProductFromDB();
    }

    void onGetProductSuccess(Product product) { // This is not called from the main thread because of the implementation of GetProductFromDB
        a.runOnUiThread(new Runnable() {

            void run() {
                // do some UI and Views related stuff
            }

        });
    }

}

Now, the Runnable being an anonymous class should hold an explicit reference to the Fragment, right? And this would prevent the Fragment from being Garbage Collected?
Should I worry about a memory leak occurring and how should I prevent it?
Will it help if I instantiate a class that extends Runnable and make it static?
private static class RunnableTask extends Runnable {

  ProductFragment fragment;

   public RunnableTask (ProductFragment fragment) {
       this.fragment = fragment;
    }

    void run() {

       if(fragment.someBoolean) {
           fragment.doSomething();
       }

    }
}

RunnableTask runnable = new RunnableTask();
a.runOnUiThread(runnable)

A: Strictly speaking, it won't necessarily result in a memory leak. BUT - for the duration of the thread's run it will hold a reference to the outer class (ProductFragment in your case). So whether it's a memory leak will depend on how long the thread will run for, and whether it ends up being the only reference left to the ProductFragment class.
Your suggestion of breaking it out into a static inner class is a good one as this will remove that reference to the outer class and hence remove any chance of the potential memory  leak.
HOWEVER - In your case, seeing as your proposed static class holds on to a reference of the outer class instance anyway, there is no benefit from doing this.


text:
Q: React Js dynamic modal page for every product with scroolY localstorage I want to get dynamic content for my products inside modal view instead of having pages for them but i am working with someonelses code so i don't want to mess with it
Here is the code for image link creator for products pages

            <Row className="">
                {/* {props.products&&props.products.map((p,index)=>
                    <Col md={3} sm={6} xs={6} className="mb-3 productOverviewCol">
                        <Card className="pt-3 pb-3" className="prodOverviewCard" id={p.ProdNo}> */}
                {props.products && props.products.map((p, index) =>
                    // {props.products&&props.products.slice(((props.page - 1)*(props.itemsPerPage)),(props.page)*(props.itemsPerPage)).map((p,index)=>
                    <Col md={3} sm={6} xs={6} className="productOverviewCol">
                        <Card className="pt-3 pb-3 prodOverviewCard" id={p.ProdNo}>

                                    <Link to={{
                                        pathname: `/ProductDetail`,
                                        search: `?id=${p.ProdNo}`,
                                        state: { productType: type, Products: props.products, pageToLoad: props.pageToLoad, customerNo: props.custNo, totalProducts: props.totalProducts }
                                    }} onClick={() => {
                                        setScrollYStore(window.scrollY);
                                        window.localStorage.setItem('scrollY', window.scrollY);
                                    }}>
                                        {/* <CardImg top src={p.Small_Img === "" || p.Small_Img === undefined ? bkry : p.Small_Img} alt="Image" />  */}
                                        <CardImg top src={p.Small_Img === "" || p.Small_Img === undefined ? bkry : p.Small_Img} alt="Image" />
                                    </Link>

                                {p.Price_type_name !== undefined && p.Price_type_name !== "Kundpris" ? {p.Price_type_name} : null}
                                {/* <AccountCircleIcon className="AccountCirculrIcnprdList" /> */}

                            <CardBody className="ProductOverviewCardBody">
                                <CardTitle className="titleTxt my-3">{p.Descr}</CardTitle>

                                <CardText className="CommercialText text-center pb-1">{p.BrandName + ' ' + p.Size_Contains}</CardText>
                                {acessToken ? <><CardSubtitle className="mb-2 greenText">{p.newPrice !== null && p.newPrice !== undefined ? p.newPrice.toFixed(2) : null} kr</CardSubtitle>
                                    <CardText className="Compartiveprice">Jmf.pris : {p.Comp_Price !== null && p.Comp_Price !== undefined ?  p.purchased_Unit === "Kart" ? p.box_com_cart_price.toFixed(2) : p.Comp_Price.toFixed(2) : null}/{p.comp_unit}</CardText></> : null}
                                {p.Campaign === 1 ? <CardText className="priceValidText mb-1">Pris gäller t.o.m {p.CampaignEndDate}</CardText> : null}
                                {acessToken ?
                                    <>
                                        <Row>
                                            <Col>
                                                <CardText className="text-center LadaSelectWp" >

                                                    {(p.Conv_facor_CART === null || p.Conv_facor_CART === 0) && (p.Conv_facor_ST === null || p.Conv_facor_ST === 0) && (p.Conv_facor_KG === null || p.Conv_facor_KG === 0) ? null :
                                                        <select className="minimal" name="select" id="exampleSelect" value={p.default_value}
                                                            onChange={(e) => props.onChangeUnit(e, index, p.ProdNo, p.Standard_orderunit, p.Comp_Price, p.Price_broken, p.Price_cart, p.Conv_facor_KG, p.Conv_facor_ST, p.Conv_facor_CART, p.default_price)}
                                                            disabled={p.Conv_facor_CART === 0 && p.Conv_facor_KG === 0 ? true : p.Conv_facor_ST === 0 && p.Conv_facor_KG === 0 ? true : p.Conv_facor_ST === 0 && p.Conv_facor_CART === 0 ? true : false}>
                                                            {p.Conv_facor_KG === 0 ? null :
                                                                <option value={p.Conv_facor_KG} keyid="Kg">{p.comp_unit === 'Liter' ? `Liter` : `KILO`}</option>}
                                                            {p.Conv_facor_ST === 0 ? null :
                                                                <option value={p.Conv_facor_ST} keyid="Styck">{`${p.Conv_facor_ST} ST`}</option>}
                                                            {p.Conv_facor_CART === 0 ? null :
                                                                <option value={5} keyid="Kart"> Kolli ({(p.Standard_orderunit === "Kart") && p.Conv_facor_ST === 0 ? p.Conv_facor_CART + ' ' + "ST" : (p.Standard_orderunit === "Kart") && p.Conv_facor_ST !== 0 ? p.Conv_facor_CART / p.Conv_facor_ST + ' ' + "ST" : p.Standard_orderunit === "Styck" ? p.Conv_facor_CART + ' ' + "ST" : (p.Standard_orderunit === "Kg") ? p.Conv_facor_CART + ' ' + "KG" : null}) </option>}
                                                        </select>}
                                                </CardText>

                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col md={12} className="IncrementListItemWpr">
                                                <CardText className="text-center" >
                                                    <ListGroup horizontal className="my-2 text-center" style={{ margin: '0 auto' }}>
                                                        <ListGroup.Item disabled={p.Min_Quantity === p.newQuantity ? true : false} onClick={() => props.DecreaseItem(p.newQuantity, index, p.ProdNo, p.newPrice, p.Min_Quantity)}>-</ListGroup.Item>
                                                        {p.purchased_Unit === "Kg" && p.comp_unit !== 'Liter' ?
                                                            <Input
                                                                type={"text"}
                                                                className="InputincrementClass"
                                                                // id="depositedAmount"
                                                                pattern="[+-]?\d+(?:[.,]\d+)?"
                                                                id={index}
                                                                data-min="1"
                                                                onChange={(e) => props.onChangeQty(e, index, p.newPrice, p.Min_Quantity, p.ProdNo, p.purchased_Unit,p.Max_Quantity)}
                                                                value={p.hiddenText ? p.newQuantity + " KG" : p.newQuantity}
                                                                onClick={() => props.onclcikEvent(p.ProdNo)}
                                                                onBlur={(e) =>
                                                                props.onMouseLeaveEvent(p.ProdNo)}
                                                            /> :
                                                            p.purchased_Unit === "Kg" && p.comp_unit === 'Liter' ?
                                                                <Input
                                                                    type={"text"}
                                                                    className="InputincrementClass"
                                                                    // id="depositedAmount"
                                                                    pattern="[+-]?\d+(?:[.,]\d+)?"
                                                                    id={index}
                                                                    data-min="1"
                                                                    onChange={(e) => props.onChangeQty(e, index, p.newPrice, p.Min_Quantity, p.ProdNo, p.purchased_Unit,p.Max_Quantity)}
                                                                    value={p.hiddenText ? `${p.newQuantity} L` : p.newQuantity}
                                                                    onClick={(e) => props.onclcikEvent(p.ProdNo)}
                                                                    onBlur={(e) =>
                                                                    props.onMouseLeaveEvent(p.ProdNo)}
                                                                /> :
                                                                <Input
                                                                    type="text" data-min="1"
                                                                    autoComplete="off"
                                                                    className="InputincrementClass"
                                                                    size="1" name={p.newQuantity}
                                                                    data-max="999"
                                                                    id={index}
                                                                    onChange={(e) => props.onChangeQty(e, index, p.newPrice, p.Min_Quantity, p.ProdNo, p.purchased_Unit,p.Max_Quantity)}
                                                                    value={p.hiddenText ? p.newQuantity + " ST" : p.newQuantity}
                                                                    onClick={() => props.onclcikEvent(p.ProdNo)}
                                                                    onBlur={(e) =>
                                                                    props.onMouseLeaveEvent(p.ProdNo)}
                                                                />}
                                                        <ListGroup.Item onClick={(e) => props.IncrementItem(p.newQuantity, index, p.ProdNo, p.newPrice, p.Min_Quantity,p.Max_Quantity)} >+</ListGroup.Item>
                                                    </ListGroup>
                                                </CardText>
                                            </Col>
                                        </Row>
                                    </>
                                    : null}

                                {/* {acessToken?
                                    <Button className="w-100 btnAddShop mt-1" onClick={()=>{saveToCart(p)}}>Add to Cart</Button> :
                                    <Button className="w-100 btnAddShop mt-1" onClick={() => handleShowLogin()}>LOGIN TO SHOP</Button>
                                  }
                               */}
                            </CardBody>
                            <Row>
                                <Col md={12} className="absoluteBtnCol">
                                    {acessToken ?
                                        <Button className="w-100 btnAddShop mt-1" onClick={() => { saveToCart(p) }}>
                                            {/* Add to Cart */}
                                            LÄGG I VARUKORGEN
                                        </Button> :
                                        <Button className="w-100 btnAddShop mt-1" onClick={() => handleShowLogin()}>
                                            {/* LOGIN TO SHOP */}
                                            LÄGG TILL I KUNDVAGN
                                        </Button>
                                    }
                                </Col>
                            </Row>
                        </Card>

                    </Col>
                )}
            </Row>
            {

            props.loading?:
                props.productCount === 0 ?
                    <Row className="justify-content-end">
                        <Col xs={12} className="my-3 text-center">
                            {/* "No result for display" */}
                            Inget resultat för visning
                        </Col>
                    </Row> :
                    props.productCount === props.totalProducts ?
                        null :
                        <Row className="justify-content-end">
                            <Col xs={12} className="my-3 text-center">
                                <button onClick={props.loadMore} className="btn loadingbtn">
                                {`LADDA ${(Number(props.totalProducts)-Number(props.productCount))>=24?24:(Number(props.totalProducts)-Number(props.productCount))} AV ${Number(props.totalProducts)-Number(props.productCount)} PRODUKTER`}
                                </button>
                            </Col>
                        </Row>
            }

I have tried to use link to code into modal body with pathname search and state . now product list overview page is like this Product List Overview

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIKit - Swift - Allow tableHeaderView to scroll up, but not down I have a UIViewController with a navigation bar and a tab bar. Other than that, the whole screen is made up of a UITableView.
I have a large tableHeaderView that has the same background color as the navbar.
When I drag the content up (scrolling down) everything looks fine.
But if I drag it up, there is an ugly disconnection between the navigation bar and the header view.
Is there any way I could anchor it to the top when dragging down, while allowing it to scroll when dragging up?

A: You can try creating a view and placing it behind the tableView, as the table view scrolls, the height of the view is updated.
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        return tableView
    }()

    let backView : UIView = {
        let view = UIView()
        view.backgroundColor = .red
        return view
    }()

    var backViewHeight : NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "ViewController"

        self.view.addSubview(backView)
        backView.translatesAutoresizingMaskIntoConstraints = false
        backView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
        backView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        backView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        backViewHeight = backView.heightAnchor.constraint(equalToConstant: 0)
        backViewHeight?.isActive = true

        self.view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
        tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        tableView.register(Cell.self, forCellReuseIdentifier: "cell")
        tableView.register(Header.self, forHeaderFooterViewReuseIdentifier: "header")
        tableView.backgroundColor = .clear

        self.navigationController?.navigationBar.barTintColor = .red
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y < 0 {
            backViewHeight?.constant = -scrollView.contentOffset.y
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        return cell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header")
        header?.contentView.backgroundColor = .red
        let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 100))
        headerLabel.textAlignment = .center
        headerLabel.text = "Header"
        header?.addSubview(headerLabel)
        return header
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }

}

class Cell: UITableViewCell {

    let label : UILabel = {
        let label = UILabel()
        label.text = "One Label"
        return label
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = .clear
        setupViews()
    }

    func setupViews() {
        self.backgroundColor = .white
        self.addSubview(label)
        label.frame = self.frame
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class Header : UITableViewHeaderFooterView {

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

If you copy paste this code in an empty project you can have a look at the behavior. Don't forget to embed the ViewController in a NavigationController. Hope it helps

A: 1) If an unwanted white space on the top of tableview is permanent and the constraints are correct this is the solution.
the scroll view insets adjusted automatically if you disable it should remove it
if #available(iOS 11.0, *) {
    tableView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

2) if u just have it when u pull down and it goes back to its normal state. It means is that the tableview bouncing is enabled and that is normal behaviour according to iOS documentation:
If the value of this property is true, the scroll view bounces when it encounters a boundary of the content. Bouncing visually indicates that scrolling has reached an edge of the content. If the value is false, scrolling stops immediately at the content boundary without bouncing. The default value is true.
you can uncheck the bouncing from the tableview in your storyboard or xib file. Or u can use this snippet:
tableView.bounces = false
tableView.alwaysBounceVertical = false

Note: that is not recommended to disable the scroll bouncing since it would make things feel very unnatural for iOS.
and also if you want to use pull to refresh it will not work.
So finally if u choose to not disable it you will have to change the background color of the parent of your tableview and it will solve it.
I hope that makes sense!


text:
Q: Integrating social network connections into website I have a client who has a web site that requires membership.  He wants to allow his users to find other users with whom they might have a existing friendship/relationship on a social networking site (Facebook, Twitter, etc).
Does anybody have any experience with this type of problem?  If so, what to packages/APIs did you use?  Right now I'm evaluating Janrain and Gigya, but we're still in the decision-making phase so I'm open to other solutions.  This is mostly a JSP shop, but again, we're open.
Thanks in advance,
Chip

A: Both are good, and come with best practices. Each one has a documentation page. I prefer Gigya since it's easy to learn and the flow is more logical.
Janrain Documetation
Gigya Documentation

A: I assume you mean visitors should have the ability to find existing friendships before their decision to register (ie. they'll be more inclined to register if they see [x] number of friends are already using the site).
If you're just interfacing with Facebook, try using their Facepile plugin. It's a quick way for non-registered users to see which Facebook friends are using the application (assuming a valid FB session).
If you're interested in multiple networks, Gigya is a really good solution. One feature you might find useful is their getFriendsInfo() method. If you set the siteUsersOnly parameter to true, Gigya will only return social network friends who are also registered users of the site.
Regardless of your choice, one piece of advice is to make sure visitors understand they aren't registering for the site just by signing-in with their social network account and checking for friends. For some users, this distinction isn't always clear.
Hope some of this helps.


text:
Q: setTimeout not called in android webkit On my android phone (2.1) I'm seeing a strange behavior with setTimeout when keeping a finger pressed on the touchscreen for a while.
This very simple code in fact works fine (1 call each second), until I scroll for a while the window (2-3 seconds are sufficient), when it stops being called
$(document).ready(function(){
    spam();
});

function spam(){
    console.log("cia")
    setTimeout(spam, 1000);
}

A: I has the same Problem.
The solution was for me to define the called function as a variable, than passing ist as parameter to the setTimeout.
Try this:
var spam = function(){
   console.log("cia")
   setTimeout(spam, 1000);
}

$(document).ready(function(){
   spam();
});

A: I had this issue before on my device when doing some development but neither of these solutions worked for me.
From the reading I did it's reasonably well documented that this does happens but seems to be no consistent way of resolving it.
What worked for me was closing the window I had my test site up down, clearing the cache, exiting the browser then opening task manager and shutting down the process. When I opened my browser again and went to my test site the standard code I had originally started working again.
My only guess is that the browser itself get's itself into some weird state where it doesn't run standard inbuilt browser functions (neither setTimeout() or setInterval() worked for me but both the javascript functions did exist).
I was testing with a Samsung Galaxy S running Android 2.1, I don't know if this will help anyone else but it's what worked for me.

A: try this
    function spam(){
        console.log("cia")
        setTimeout("spam()", 1000);
    }

setTimeout:
    /**
    @param {String|Function} vCode
    @param {Number} iMillis
    @return Number
    */
    window.setTimeout = function(vCode,iMillis) {};

A: For me Varriotts answer didn't work ... the only way I could get setTimeout working on the Android phone i used for testing (running v 2.something) is by the following notation:
function foo() {}
window.setTimeout(foo, 200);

This looks weird, passing just the name of a function, but after hours of trying around, it was the only way it worked.

A: I tried this and it solved my problem.
setTimout(function(){aFunction(text);}, 200);


text:
Q: Integration over Gaussian random matrices Let n=2 and C be a symmetric two by two matrix and let $X = \left(X_{1,j}; X_{2,j}\right)_{j=1}^T$ be a two by T real matrix matrix. We consider a following generating function.
\begin{equation}
U(t) := \frac{1}{n} \int\limits_{{\mathbb R}^{2 T}} Tr\left[ e^{\frac{\imath t}{T} X X^T} \right] \cdot e^{-\frac{1}{2} Tr\left[ C^{-1} X X^T \right]}
\frac{\prod_{j=1}^T dX_{1,j} dX_{2,j}}{\sqrt{(2\pi)^{2T}} \sqrt{\det(C)^T}}
\end{equation}
By expanding the first term in the integrand in a Taylor series in t we and integrating term by term we easily establish that:
\begin{eqnarray}
U(0) &=& 1 \\
\left.\frac{d U(t)}{d \imath t} \right|_{t=0} &=& Tr[C] \\
\left.\frac{d^2 U(t)}{d (\imath t)^2} \right|_{t=0} &=& Tr[C^2](1+\frac{1}{T}) + Tr[C]^2 \frac{2}{T} \\
\end{eqnarray}
Now, let us try to compute the generating function in a different way. We perform a singular value decomposition of the matrix X X^T. We have:
\begin{equation}
X X^T = U {\mathcal D} U^{-1}
\end{equation}
where $U$ is a unitary matrix and ${\mathcal D}$ is a diagonal matrix with real entries $s_1,s_2$. We have:
\begin{equation}
U(t) = \frac{1}{((2 \pi)^2 c_1 c_2)^{T/2}n}\int\limits_{{\mathbb R}_+^2} d s_1 d s_2 (s_2-s_1)^2 (s_1 s_2)^{\frac{T-3}{2}} \left(e^{\frac{\imath t s_1}{T}}+e^{\frac{\imath t s_2}{T}}\right) \cdot
\underbrace{\int\limits_{U(2)} dU e^{-\frac{1}{2}Tr\left(C^{-1} U {\mathcal D} U^{-1}\right)}}_{J}
\end{equation}
Here I used the formula for the joint-probability density of eigenvalues of an ensemble of random matrices (see http://en.wikipedia.org/wiki/Wishart_distribution for example). The last integral on the right-hand side is an integration over the group of two dimensional unitary matrices. We can do that integral owing to the Harish-Chandra-Itzykson-Zuber formula. We have:
\begin{equation}
J = {\mathcal A}_T \frac{(e^{-\frac{s_1}{2 c_1}-\frac{s_2}{2 c_2}} - e^{-\frac{s_1}{2 c_2}-\frac{s_2}{2 c_1}})}{(\frac{1}{c_1}-\frac{1}{c_2})(s_1-s_2)}
\end{equation}
where the proportionality constant ${\mathcal A}_T$ depends on $T$ only. Inserting the above into the equation for $U(t)$ we get:
\begin{equation}
U(t) = \frac{{\mathcal A}_T}{((2 \pi)^2 c_1 c_2)^{T/2}(\frac{1}{c_1}-\frac{1}{c_2})n}\int\limits_{{\mathbb R}_+^2} d s_1 d s_2 (s_2-s_1) (s_1 s_2)^{\frac{T-3}{2}} \left(e^{\frac{\imath t s_1}{T}}+e^{\frac{\imath t s_2}{T}}\right) \cdot
(e^{-\frac{s_1}{2 c_1}-\frac{s_2}{2 c_2}} - e^{-\frac{s_1}{2 c_2}-\frac{s_2}{2 c_1}})
\end{equation}
Now we set ${\mathcal A}_T=1$ and we use Mathematica to compute the value of our generating function and its derivatives at zero. We have:
\begin{eqnarray}
U(0) &=& {\mathcal B} \\
\frac{1}{\imath} U^{'}(0) &=& {\mathcal B}  \frac{T+1}{2 T} Tr[C] \\
\frac{1}{\imath^2} U^{''}(0) &=& {\mathcal B}  \frac{T+1}{2 T} \left[(1+\frac{1}{T})Tr[C^2]  + \frac{4}{T} (Tr[C])^2 \right]
\end{eqnarray}
where  ${\mathcal B} = 4 \sqrt{c_1 c_2} \pi^{-T} \Gamma[(T-1)/2] \Gamma[(T+1)/2]$. These results are clearly different from those stated on the very top.  What is the reason for this? I suspect that there is something wrong with the joint-denstity of eigenvalues in the integral over $s_1$ and $s_2$ but I cannot figure out what is wrong. Can anybody help me?

A: I have calculated this integral in Spectral density of a sample covariance matrix in a Gaussian Random Ensemble . There were two bugs in the above reasoning. Firstly, the Harish-Chandra-Itzykson-Zuber formula does not hold in here because we need to integrate over the orthogonal group rather than over the unitary group. In that former case there is no closed form expression for the integral in question but instead the integral is expressed through generalized Bessel functions. Secondly, there was also a bug in the Jacobian from the matrix elements to the eigenvalues.


text:
Q: Deploying a CDK Script through Service Catalog gives Authorization failures I've created an AWS CDK script which deploys an ECR image to Fargate.
When executing the script from an EC2 VM (using cdk deploy using the aws cli tool), I can add an IAM Role to the EC2 instance therefore granting all the permissions required. And the script deploys successfully.
However my aim is to cdk synth the script into a Cloudformation template manually, and then deploy from AWS Service Catalog.
This is where permissions are required, but I'm unsure where exactly to add them?
An example error I get is:
"API: ec2:allocateAddress You are not authorized to perform this operation. Encoded authorization failure message: "
I've looked into the aws cdk docs (https://docs.aws.amazon.com/cdk/api/v1/docs/aws-iam-readme.html) thinking the cdk script needs to have the permissions embedded, however the resources I'm trying to create don't seem to have options to add IAM permissions.
Another option is, like with native Cloudformation scripts, to add Parameters which allow attaching Roles upon provisioning the Product, though I haven't found a way to implement this in cdk either.
It seems like a very obvious solution would be available for this, but I've not found it! Any ideas?
The CDK script used:
from constructs import Construct
from aws_cdk import (
    aws_ecs as ecs,
    aws_ec2 as ec2,
    aws_ecr as ecr,
    aws_ecs_patterns as ecs_patterns
)

class MyConstruct(Construct):

    def __init__(self, scope: Construct, id: str, *, repository_name="my-repo"):
        super().__init__(scope, id)

        vpc = ec2.Vpc(self, "my-vpc", max_azs = 3)

        cluster = ecs.Cluster(self, "my-ecs-cluster", vpc=vpc)

        repository = ecr.Repository.from_repository_name(self, "my-ecr-repo", repository_name)
        image = ecs.ContainerImage.from_ecr_repository(repository=repository)

        fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(
            self,
            "my-fargate-instance",
            cluster=cluster,
            cpu=256,
            desired_count=1,
            task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions(
                image=image,
                container_port=3000,
            ),
            memory_limit_mib=512,
            public_load_balancer=True
        )


text:
Q: knitr and specifyModel() of sem package I keep getting an error when I try to compile a .rnw file with a model specified by specifyModel() from the sem package. knitr does not like the comma in F1 ->  X1, lam1, NA.
Here is an example that reproduces the error:
\documentclass{article}

\begin{document}

<<specify, include=FALSE, tidy=FALSE>>=
# Simple CFA Model
  # from: http://www.statmethods.net/advstats/factor.html
    library(sem)
    model.mydata <- specifyModel()
      F1 ->  X1, lam1, NA
      F1 ->  X2, lam2, NA
      F1 ->  X3, lam3, NA
      F2 ->  X4, lam4, NA
      F2 ->  X5, lam5, NA
      F2 ->  X6, lam6, NA
      X1 <-> X1, e1,   NA
      X2 <-> X2, e2,   NA
      X3 <-> X3, e3,   NA
      X4 <-> X4, e4,   NA
      X5 <-> X5, e5,   NA
      X6 <-> X6, e6,   NA
      F1 <-> F1, NA,    1
      F2 <-> F2, NA,    1
      F1 <-> F2, F1F2, NA

    model.mydata
# end
@

\end{document}

Here is the error:
#Quitting from lines 5-27 (test.rnw)
#Error in parse(text = x, srcfile = src) : <text>:5:16: unexpected ','
#5:     model.mydata <- specifyModel()
#6:       F1 ->  X1,

Any thoughts?

A: If you don't specify the file in specifyModel it will attempt to read from the standard input stream (stdin) -- while this may be possible within knitr I think it would be easier to read the model specifications in from a file.
For example
model <- readLines(con = textConnection('F1 ->  X1, lam1, NA
F1 ->  X2, lam2, NA
F1 ->  X3, lam3, NA
F2 ->  X4, lam4, NA
F2 ->  X5, lam5, NA
F2 ->  X6, lam6, NA
X1 <-> X1, e1,   NA
X2 <-> X2, e2,   NA
X3 <-> X3, e3,   NA
X4 <-> X4, e4,   NA
X5 <-> X5, e5,   NA
X6 <-> X6, e6,   NA
F1 <-> F1, NA,    1
F2 <-> F2, NA,    1
F1 <-> F2, F1F2, NA'))
cat(model, file = 'model.spec', sep = '\n')
model.mydata <- specifyModel(file = 'model.spec')

Alternatively you could simply create the model.spec file and read it in.


text:
Q: Parsing XML with duplicate root elements I am trying to programmatically clean up invalid XML with duplicate root elements in C# .NET 4.0. What I want to do is consolidate all of the inner elements into one root element and remove the duplicates roots, so that

    <c></c>

becomes

    <c></c>

However, the duplicated root element could also appear in the inner XML. In that case, we would not want to replace it, so that

    <c></c>

becomes

    <c></c>

Also, the duplicated root element isn't guaranteed to always be ; it could have any name.
Thus far I've been trying to think of some sort of elegant Regex to accomplish this task, such as /<((.|\n|\r)*?)>(.|\n|\r)*<\/\1>/, but the problem with this is that a greedy match on the inner XML matches too much, and non-greedy match on the inner XML matches too little.
I was hoping I wouldn't have to resort to creating a stack to count open and close tags to identify when I was back to the root of the document. I'm looking for a simple and elegant way of solving this problem.
Open source, third-party libraries are potentially acceptable solutions if one of them handles this kind of situation, but I'd rather avoid them.
Does anyone have any ideas?

A: It may be better to actually read XML as XML... You should be able to create reader with ConformanceLevel set to Fragment and read all fragments as normal XML. And than use normal XML processing to select/copy Xml nodes.

A: Someone had a good answer that they just deleted. Get the name of the root node, and just remove all of those nodes. It should be easy to get the name of the first node, regardless of what it is.
This will leave the document basically how you want it, then just wrap the whole thing back up in one of those nodes. Done.


text:
Q: Angular 1.5.8 - How do I perform an action when angular finishes binding data to an element? I have an angular app in which I want to wait until data is bound to a selection drop down until before I apply a jquery method to the selection drop down.
In my previous related question I was able to populate the drop down successfully using the following code.
 <select name="shippingState" id="shippingState" ng-model="accountAddresses.shippingState"  ng-options ="state.abbreviation for state in states track by state.abbreviation" class="state form-control" size="1">
                       </select>

AngularJS (1.5.8) - How do I populate a select option list directly from within controller that gets a json object?
Now I want to apply the jquery method (a custom selectbox dropdown styling library).
When data loads, I am able to apply the method manually in the browser console.
The problem is I can only do the action in the browser console manually.
When the drop down data is fetching I can not run the same method in angular.
Question:
How do I can trigger an action when data binding finishes in Angular?
EDIT - I created a directive and modified my html to trigger the directive.
Still I do not get a custom styled element.
Directive Chained to the Root Controller
  directive('onDataBind', function (id) {
                        alert(id);
                          function link(elem, id) {
                            elem.ready(function(id){
                              $scope.CreateDropDown(id);
                              });
                            }
                          })

HTML Modified
           <select name="billingState" id="billingState" ng-model="accountAddresses.billingState"  ng-options ="state.abbreviation for state in states track by state.abbreviation" on-data-bind="CreateDropDown('billingState')" class="state form-control" size="1">
           </select>

Create Drop Down at the Scope Level
   $scope.CreateDropDown = function(id){
      $("#"+id).selectbox();
      //selectbox is the following library - https://github.com/olivM/jQuery-Selectbox
    }

A: The following directive code helped resolve the issue.  I used a directive and timeout as suggested.
directive('onDataBind', function () {
                  function link(scope, elem) {
                    var id = elem.attr("id");
                    elem.ready(function(){
                     setTimeout(function () {
                       $("#"+id).selectbox();
                     }, 1000);
                      //$('#'+id + ' .sbHolder > .sbOptions').wrap("

");
                      //$("#"+id + " .sbHolder > a.sbToggle, "+id+" + .sbHolder a.sbSelector").wrapAll("

");
                    })(id);
                    }
                    return {
                      link: link,
                      restrict: 'A',
                    };
                  })


text:
Q: How to add a reverse proxy for authentication & load balancing in Kuberenetes (GKE)? Okay, I have a DB consisting of several nodes deployed to GKE.
The deployment.yaml adds each node as ClusterIP, which makes sense. Here is the complete deployment  file:
https://github.com/dgraph-io/dgraph/blob/master/contrib/config/kubernetes/dgraph-ha/dgraph-ha.yaml
For whatever reason, the DB has zero security functionality, so I cannot expose any part using a LoadBalancer service because doing so would give unsecured access to the entire DB. The vendor argues that security is solely the user's problem. The AlphaNode comes with an API endpoint, which is also unsecured, but I actually want to connect to that API endpoint from an external IP.
So, the best I can do is adding an NGNIX as a (reverse) proxy with authentication to secure access to the API endpoint of the Alpha node(s). Practically, I have three alpha nodes so adding load balancing makes sense. I found a config that does load balancing to three alpha nodes in Docker Compose although, without authenication.:
https://gist.github.com/MichelDiz/42954e321620159c872c35c20e9d85c6
Now, the million-dollar question I have is, how do I add an NGNIX load balance to Kubernetes that authenticates and load balances incoming traffic to my (ClusterIP) alpha nodes?
Any pointers?
Any help?

A: If you want to do it that hard way, you can deploy your own nginx deployment and expose it as LoadBalancer Service. You can configure it with different authentication mechanisms that nginx support.
Instead, you can use Ingress resource backed by an IngressController that supports authentication. Check if your kubernetes distribution provides an IngressController and if it is supports auth. If not, you can install nginx or Traefik IngressControllers which supports authentication.
Looks like GKE ingress has recently added support for IAP bassed authentication which is still in beta - https://cloud.google.com/iap/docs/enabling-kubernetes-howto
If you are looking for more traditional type of authentication with ingress, install nginx or traefik and use the kubernetes.io/ingress.class annotation so that only IngressController claims your ingress resource - https://kubernetes.github.io/ingress-nginx/user-guide/multiple-ingress/


text:
Q: addeventlistener to a dynamically generated element triggers event on all dynamically generated elements after him I have a webpage where I have added the possibility of highlighting specific parts of texts. Whenever I select some text and press ctrl+c, the text selected is inserted into a span and highlighted.
The HTML looks like that when an element is highlighted.

    Vestibulum ante ipsum primis in faucibus orci "luctus
 "et ultrices posuere cubilia Curae;"

I'm trying to create a functionality to change the highlighted colour when the span is clicked on.
To do so, i created a function below called everytime a new element is highlighted. It selects all spans within the text, supposedly selects the relevant span thanks to its ID to change its class, and adds the event listener.
function eventHighlighted() {

  //select all spans within the text into an HTML collection.
  let textToAnnotate = document.querySelector('#text');
  let spansExisting = textToAnnotate.querySelectorAll('span');

 // function to change the highlighted colour
  function changeColour () {
    let selectedText = document.getElementsByClassName("highlight")[this.id];
    selectedText.className = "highlight-clicked";
    }

// add eventListener to all spans.
  for (var i = 0; i < spansExisting.length; i++) {
     var existingSpan = spansExisting[i];
     existingSpan.addEventListener("click", changeColour);
     }
  }

This function is called everytime a new bit of text is highlighted. (I gather this is not very memory efficient, as it can possibly add unnecessary event listeners on some spans that don't need one anymore.)
The problem i have is that it works nicely for the first element highlighted. Whenever i click on this bit of highlighted text, the highlight changes colour.
However, when I highlight a second bit of text, for instance with this example

        Vestibulum ante ipsum primis in faucibus orci "luctus
     "et ultrices" posuere cubilia " Curae;"

if i clicks on the first span (luctus), it will trigger the class change on it but also on the second span below.
When i select the second one, however, it will work as expected and only trigger the class change on the second span.
I cannot really figure out why. I gather my function triggered on the first span actually instructs him to change the class for all spans within the HTML collection. I don't understand why it does not does instruct him to do this specifically only for him.
Thank you !

A: You don't need an extra attribute in span tags. Take a look at my solution. Hope this helps.

function initHighlights() {
  var highlights = document.querySelectorAll('.highlight');

  for (var i = 0; i < highlights.length; i++) {
    highlights[i].onclick = function() {
      // this - refers to span HTMLElement
      this.classList.toggle("highlight-clicked");
    };
  }
}

initHighlights();
.highlight {
  background: lightgrey;
  cursor: pointer;
  user-select: none;
}

.highlight-clicked {
  background: yellow;
}

Vestibulum ante ipsum primis in faucibus orci "luctus"et ultrices posuere cubilia Curae;"


text:
Q: Parsing terminal arguments Qt Mac OS X I have a simple text editor in which I would like to open a file when it's double-clicked from the system file manager.
I managed to do that without any problems under Ubuntu Linux (13.04), but in Mac OS X my code did not work.
After researching a bit, I found out that you need to add the --args argument in terminal in order to parse the arguments to main().
I fixed my code and now my application bundle can open files from the terminal, but when I double click a file in Finder (and select my app), my application launches as if did not receive any terminal arguments (creates a new file).
Here is the code of the main() function:
int main(int argc, char *argv[])
{
    QApplication MyApp(argc, argv);

    Textpad.setApplicationName("MyApp");
    Textpad.setApplicationVersion("0.7.2");

    Textpad.setWindowIcon(QIcon(":/app-icon/48x48/icon.png"));

    MainWindow *Window = new MainWindow();

    QString Arguments;
    QString FileLocation;

    if (argc != 1) {
        int i;
        for (i = 0; i < argc; i++)
            Arguments = argv[i];

        // Check if the OS is Mac OS X (Mac OS X is 3)
        if (Window->CheckOS() == 3)
            // Remove the "--args" so that we don't confuse it with the file location
            Arguments.replace("--args", "");

        if (Arguments == "--help") {
            // Show help
        }

        // Create a new file when Textpad is launched normally (under Linux)
        if (Arguments == "%U") {
            FileLocation.clear();
            // Load settings and create UI
            Window->Initialize();
            // Open the requested file
            Window->LoadFile(FileLocation);
        }

        else {
            FileLocation = Arguments;
            // Load settings and create UI
            Window->Initialize();
            // Open the requested file
            Window->LoadFile(FileLocation);
        }
    }

    else {
        // Create new file
        FileLocation.clear();
        // Load settings and create UI
        Window->Initialize();
        // Open the requested file
        Window->LoadFile(FileLocation);
    }

    return MyApp.exec();
}

As I said before my application opens files without probles from the terminal when I write the following:
open MyApp.app --args <location of my file>

But fails when I try to open a file from Finder.
What I am missing?
Thank you in advance.

A: First of all, you will have to link against the OX-X Framework. OSX works with Events similar to signal slots. The filename will also be given by an apple event. I`ve had this quite some time ago with another language, but i still found a reference:
Edit doc now in Qt archive:
https://doc.qt.io/archives/qq/qq12-mac-events.html


text:
Q: Adding multiple annotations of same type c# charting I am attempting to add multiple flags of similar types (arrows) to a live chart using a C# windows forms project. This is to provide a label when a value falls out of a pre-defined specification.
I am currently stuck in how to create new instances of the ArrowAnnotation class so if multiple events happen there will be multiple flags for the people checking the chart. I am able to create one instance and manipulate the position to the latest data point in the series (it shouldn't be a stretch to lock it to a historical point, I just haven't done that yet.)
I have an understanding of creating multiple instances of other classes and keeping track of them with lists/ dictionaries but this one has me stumped (or maybe I don't have as good an understanding as I think?)
I can't share the code I have directly but I think I can write some example code if needed.
edit-
I am looking into using a memberwise clone to copy common attributes of each arrow and add those objects to a dictionary.
Thanks

A: Okay, I have managed to figure out how to do this for my use case.
When updating the live chart I can call a method if a parameter falls out of specification. In that method I create a new instance of the annotation, and the properties that I want to use as a template. (these values can also be changed with conditional logic if you want slight variation, and can be passed in with the argument) than add that newly made annotation to the annotation group. I am still looking for improvements to the code. I am still wanting a way to assign a name to the arrow, than recall that one and modify it (if I wanted to). And change the pass/fail criteria than apply annotations for the new failure points (but that is going into new territory)
     // This is not the full method just the part that counts for this question.
    private ArrowAnnotation floatArrow;
    private void UpdateChart()
    {

        GenerateArrows(dateTime, sensorValue);
        this.chart1.Annotations.Add(floatArrow);enter code here
    }

    private void GenerateArrows(DateTime x, double y)
    {
        floatArrow = new ArrowAnnotation();
        floatArrow.Name = Convert.ToString(x);
        floatArrow.ToolTip = Convert.ToString(x);
        floatArrow.AxisXName = "ChartArea1\\rX";
        floatArrow.AxisYName = "ChartArea1\\rY";
        floatArrow.X = x.ToOADate();
        floatArrow.Y = y;
        floatArrow.Height = 5;
        floatArrow.Width = 0;
        floatArrow.BackColor = Color.Red;
    }


text:
Q: MVC DropDownListFor with ViewBag not passing value to controller I'm having a real hard time trying to set up a drop-down list to a related model/table in my create view. My Guest model has a reference to the PersonPrefix model in the following way:
Guest model:
public virtual PersonPrefix Prefix { get; set; }

PersonPrefix model:
public class PersonPrefix
{

    [Key]
    public int PersonPrefixID { get; set; }
    [StringLength(6)]
    public string Abbreviation { get; set; }
    [StringLength(255)]
    public string Name { get; set; }
    public virtual ICollection<Guest> Guests { get; set; }

}

I have done the following to be able to get the data from the database and show it in a dropdown:
Controller:
public ActionResult Create()
{
    ViewBag.PersonPrefixes = new SelectList(db.PersonPrefixes, "PersonPrefixID", "Abbreviation");
    return View();
}

and I've added the prefix object to the post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "GuestID,FirstName,MiddleName,Surname,BirthDate,SelectedPrefix")] Guest guest)
{
    if (ModelState.IsValid)
    {
        db.Guests.Add(guest);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(guest);
}

This is the relevant code in the view so far but it is not passing the value to the controller:

        @Html.LabelFor(model => model.Prefix, htmlAttributes: new { @class = "control-label col-md-2" })

            @*@Html.DropDownListFor(m => m.Prefix,  new SelectList(ViewBag.PersonPrefixes, "Value", "Text", 1))*@
            @Html.DropDownListFor(m => m.Prefix,
            new SelectList(ViewBag.PersonPrefixes, "Value", "Text", 1))

Thanks for your help!!

A: You cannot bind a <select> element to a complex object. All html form controls post back a single value (or in the case of <select multiple> an array of value types). If you selected an option with a value of (say) 5, then the DefaultModelBinder would try to set guest.Prefix = 5; which of course fails.
You need to bind to a value type (e.g. int, string etc). In your case you cannot even bind to the PersonPrefixID of PersonPrefix because validation would fail on the other properties of PersonPrefix. As always when editing, you should use a view model containing only those properties you need to edit.
public class GuestVM
{
  [Display(Name = "Prefix")]
  [Required(ErrorMessage = "Please select a prefix")]
  public int SelectedPrefix { get; set; }
  .... // other properties of Guest
  public SelectList PrefixList { get; set; }
}

Controller
public ActionResult Create()
{
  GuestVM model = new GuestVM();
  model.PrefixList = new SelectList(db.PersonPrefixes, "PersonPrefixID", "Abbreviation");
  .... // set other properties as required
  return View(model); // always return an instance of the model
}

View
@Html.LabelFor(m => m.SelectedPrefix)
@Html.DropDownListFor(m => m.SelectedPrefix, Model.PrefixList, "--please select--")
@Html.ValidationMessageFor(m => m.SelectedPrefix)

Then in the POST method, initialize a new instance of Guest data model and map its properties from the posted view model and finally save the data model.
public ActionResult Create(GuestVM model)
{
  if (!ModelSTate.IsValid)
  {
    model.PrefixList = new SelectList(db.PersonPrefixes, "PersonPrefixID", "Abbreviation");
    return View(model);
  }
  // Initialize a new instance of the data model and set its properties
  Guest guest = new Guest()
  {
    FirstName = model.FirstName,
    MiddleName = model.MiddleName,
    .... // other properties
    Prefix = db.PersonPrefixes.Find(model.SelectedPrefix)
  };
  db.Guests.Add(guest);
  db.SaveChanges();
  return RedirectToAction("Index");
}

Side note: You do not need to create another SelectList in the view (its already a SelectList) and the last parameter where you tried to set the selected value to 1 is ignored (its the value of the property your binding to which determines which option is selected) so if you want to pre-select an option with value="1", then set the value of SelectedPrefix = 1; in the controller before you pass the model to the view.

A: While it's better to use ViewModels, per Stephen's answer, what you're doing wrong specifically here is this:
First, your DropDownListFor is wrong.  Your ViewBag entry already contains a SelectList, so you don't need to create another one... you just have to cast the dynamic type.
@Html.DropDownListFor(m => m.Prefix.PersonPrefixID,
                           (SelectList)ViewBag.PersonPrefixes, "Select...")

The first parameter is the selected id from the list of objects in the PersonPrefixes...  So when the model is posted to the controller, it will contain the ID (but not the other data, so you will have to make sure to query the database to populate it).
Second, you will need to change your Post Action to this:
Create([Bind(Include = "GuestID,FirstName,MiddleName,Surname,BirthDate")] Guest guest)

And then on your PersonPrefix class use the Bind syntax:
[Bind(Include = "PersonPrefixID")]
public class PersonPrefix
{
    [Key]
    public int PersonPrefixID { get; set; }
    .....
}

Now, when you post, the rest of PersonPrefix will be empty, because this data is not present in the post, so you have to retrieve it from the database using the posted PersonPrefixID.
However, as I said, it's better to use ViewModels.  Even so, some of the same things I said here still apply.  Your DropDownListFor needs to be correct, and work with a selected id property.  And, if you're using a ViewModel, there is no reason to use the Bind attributes, since you're only binding the exact items you need.


text:
Q: Error connecting to SQL Server instance I already have SQL server 2008 R2 on my system. I also installed SQL server 2012 express. Then, I uninstalled it and installed SQL server 2012 commercial edition. I cannot connect to my DB via management studio. These weird errors happen to me all the time - 2005, 2008, 2012. The numbers change. TCP/IP is enabled, service is enabled. I just want to be able to connect and put some test databases for learning.
Please help me to fix the error below -

Cannot connect to SuperPC\SQLEXPRESS.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)

A: Make sure that the SQL Server Service is running. Go to services from start menu, and see SQL Server, if it's not running just right click and select Start.

A: When you uninstalled SQL Express you removed the SuperPC\SQLEXPRESS instance of SQL from your system.  You will need to use a different SQL instance name.  You would have set this name in the 2012 commercial version installation.
If the SQL 2008 R2 instance is the default instance on your system then the commercial SQL 2012 instance would have been installed as a named instance and you'd need to connect to it using the instance name you indicated during installation.  You would connect to it using SuperPC\[new instance name] where you replace [new instance name] with the name of the instance you set during installation.
If the SQL 2008 R2 instance is not the default instance, then the new SQL 2012 instance MAY have been installed as the default instance, in which case you just connect to it using SuperPC.  It COULD still have been installed as a named instance in which case you would need to follow the directions in the above paragraph.
EDIT:
Based on your comment on your question, try connecting with SuperPC\Sql2012.


text:
Q: $R$ be a commutative ring with unity , $|R^{\times}|=p$ an odd prime then is $R$ isomorphic to a quotient of $\mathbb Z_2[x]/\langle x^p-1\rangle$? Let $R$ be a commutative ring with unity such that its group of invertible elements has order $p$ an odd prime , then is it true that there exist a surjective ring homomorphism from $\mathbb Z_2[x]/\langle x^p-1\rangle$ onto $R$ ? I can see that since $-1\in R^{\times}$ and $(-1)^2=1$ and $2$ does not divide $p$ , so $-1=1$ , but I cannot proceed further . Please help . Thanks in advance .

A: The answer is No. The unit group of $\mathbb F_4[x]$ has size $3$, but this infinite ring is not a quotient of the $8$-element ring $\mathbb F_2[x]/(x^3-1)$.
But if $R$ is a commutative unital ring with $|R^{\times}|=p$, $p$ odd, then $R$ must be of characteristic $2$ (as you observed). If $R^{\times}$ is generated by $u$, then there is a homomorphism $\mathbb F_2[x]\to R\colon x\mapsto u$ which has kernel containing $x^p-1$. Thus there is a homomorphism $\mathbb F_2[x]/(x^p-1)\to R$ whose image contains $R^{\times}$. But, as the example shows, the image need not be all of $R$.


text:
Q: Can a valid URL usefully contain more than 1 question mark? URLs can obviously contain 0 question marks, e.g. www.google.com
Or they could contain exactly 1 question mark e.g. www.google.com?q=soccer
So far, I can see that most (all?) URL's still work when more '?' characters are added, and I also know that query strings are non-standard and implementation is client-specific, so, if I interpret that correctly, technically there's nothing stopping a developer from having URL's containing many ?'s, but it just might not fit within standard conventions.
Example: something like this still works, even though it's an odd URL: https://www.google.com/?????????
Question
So my question is can a valid url contain more than one question mark, and are the superfluous question marks ever useful? (obviously 1 question mark serves a very important purpose in many URL's - to delineate between the domain and the parameters)
Backgorund
Why would anyone care? I'm making a method that accepts a URL, and I'll provide a warning if there's > 1 question mark. (but I won't provide that warning if there are valid reasons for > 1 question mark in typical day to day use)

A: I think this is a great question and has been answered here.
Obviously, it is not something common that we usually see (some places even say that this should be not allowed), but I'm going to show a few more practical examples of that. Even though it is not common, I believe that "preventing URLs" with two question marks may not be so good and in the end, I'll say why.
Simple URL redirect service
Let's say that some redirection service has a code more or less like this:
<?php

if ($_GET['redirect_to']) {
  $url = $_GET['redirect_to'];
  if (filter_var($url, FILTER_VALIDATE_URL)) {
    //valid URL, redirect
    header("HTTP/1.1 302 Moved Temporarily");;
    header("Location: " . $url);
    die;
  }
}

As you can see, the code first validates the URL, if valid, redirect the user. If you access this, it will work:
http://localhost/?redirect_to=https://www.example.com/content?from=https://api.example.com/posts?id=2
There are multiple question marks there, one to define the redirect_to parameter, another one to the from parameter, and the last to the id parameter of the redirected URL. To PHP, all this (redirect_to content) is a valid URL. Also, the StackOverflow editor highlights the whole URL as a valid link (the generated answer does not, but I will keep it this way and you can check that if try to edit).
API's
You can download the JSON Placeholder API and create a new post on data.json like this:
{
  "userId": 1,
  "id": 1,
  "title": "Is multiple question marks useful??",
  "body": "Maybe"
}

After running with npm start, you can access http://localhost:3000/posts?title=Is%20multiple%20question%20marks%20useful?? and the post will be returned, so, this would be an example where someone would like to return a post that contains the question mark.
HOWEVER
It's pretty obvious that using multiple question marks on the URL is very weird, and not all clients can interpret this correctly, so it might also be a bad practice to build a system that generates this kind of URL. But your question is about to validate or not multiple question marks, so, thinking that those URLs can belong to other services that you don't have control, to me, there's no need to do the validation.


text:
Q: Detail view not updating when UITableView rows are re-ordered I have a UITableView that pushes to a Detail ViewController. In my tableview, my rows are draggable/re-arrangeable. However, when the rows are switched, the path stays the same when selecting the rows and the Detail View is presented. Example: TableView Re-order Pic
If I were to switch the "Milk" row with the "Gym" row, then select "Gym", the detail view would still return the details of the milk row.
How do I fix this so that the path of the rows switch appropriately as they do?
.m :
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self->newArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *theFood = [values objectAtIndex:indexPath.row];
    cell.textLabel.text = [theFood valueForKey:@"name"];
    cell.detailTextLabel.text = [theFood valueForKey:@"price"];

    return cell;
}

- (IBAction) EditTable:(id)sender
{
    if(self.editing)
    {
        [super setEditing:NO animated:NO];
        [_myTableView setEditing:NO animated:NO];
       // [_myTableView reloadData];
        [self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
        [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
    }
    else
    {
        [super setEditing:YES animated:YES];
        [_myTableView setEditing:YES animated:YES];
       // [_myTableView reloadData];
        [self.navigationItem.leftBarButtonItem setTitle:@"Done"];
        [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];

    }
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
        if( fromIndexPath == toIndexPath ) {
            return;
        }

    NSDictionary *moveFood = [self->newArray objectAtIndex:fromIndexPath.row];
    [self->newArray removeObjectAtIndex:fromIndexPath.row];
    [self->newArray insertObject:moveFood atIndex:toIndexPath.row];

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"detailSegue"]) {
        NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow];
        DetailViewController *detailVC = segue.destinationViewController;
        detailVC.detailFood = [values objectAtIndex:indexPath.row];

    }
}

A: When you switch the rows you should also update your data source. Otherwise when tableView's didSelect method is called it would access the wrong object in your data source array.
So in –tableView:moveRowAtIndexPath:toIndexPath: switch the location of the objects that were switched.

A: Special thanks to @HotLicks for helping me!
The problem was I didn't change my datasource for the detail view from values NSArray to my newArray NSMutableArray after the update in my tableView:moveRowAtIndexPath:toIndexPath: method!


text:
Q: Too much information I have this code running fine but then it shows too much information and I only want the last line in the code.
Code here:
import scala.io.Source

object CovidWorld {
  def main(args: Array[String]): Unit = {
    val filename = Source.fromFile("OOPAssignment3.txt")

    try{
        for (line <- filename.getLines.toList) {
            if (line.contains("Malaysia") && line.split(",").apply(7).nonEmpty) {
                val allDeathString: String = line.split(",").apply(7)
                print("\n\n Malaysia latest total amount of death: " + allDeathString)
            }
        }
    }
    finally{
        filename.close
        //print("\nThe file is now closed")
        }
    }
}

This is the result I obtain from it.result of the running code
I just want the last line of the information instead of the entire thing. Anyone can figure out how? Thanks in advance for the help :)

A: You can replace the inside of your try block with:
 filename
      .getLines
      .filter(line => line.contains("Malaysia") && line.split(",").apply(7).nonEmpty)
      .toList
      .takeRight(1)
      .foreach(line => {
        val allDeathString: String = line.split(",").apply(7)
        print("\n\n Malaysia latest total amount of death: " + allDeathString)
      })

The key part for your purposes is takeRight which selects n elements from the end of the list. When n == 1 you're taking only the last match which is what you want here.


text:
Q: How to chmod without /usr/bin/chmod? Today I was told a tale by a Unix trainer where the root password got leaked to the students, and one of the fellas removed the execute permission from /usr/bin/chmod itself. How do you recover chmod in this case and make it executable again? Let's say getting it from an external source or recompiling it is not a preferable option, is there some smart hack that can recover this chmod itself?
Note that this happened a long time ago and I'm not looking for a solution for some current problem, just curious about what ways Unix provides us around such an issue.

A: Some systems also have busybox installed in which case you may run:
busybox chmod +x /bin/chmod

Since you were asking for hacks, I just thought of another one:
mv /bin/chmod /bin/chmod.orig
cp -a /bin/chown /bin/chmod

Now you have a /bin/chmod that's executable but it's actually chown (i.e. some other binary). Now all we have to do is overwrite it with the original binary.
dd if=/bin/chmod.orig of=/bin/chmod

It keeps the +x flag so you just stole the +x of another file for this one.
Of course, if all those alternative binaries (including the loader, perl, python, gcc et cetera) were chmod -x, fixing it from a rescue system may be the only option.

A: rsync can also be used to change the file's permissions
# rsync /bin/chmod /tmp/chmod --chmod=ugo+x
# ls -al /tmp/chmod
  -rwxr-x--- 1 root root 52000 Sep  6 15:13 /tmp/chmod
#

A: Pipe the contents of chmod into an already executable file
cp /usr/bin/executable_file ~/executable_file
cat /usr/bin/chmod > ~/executable_file
~/executable_file +x file_to_be_executed.sh

A: Easy. What you can do is prepare some other executable file, and then cp chmod over it.
 $ cp /bin/ls chmod
 $ cp /bin/chmod .

The first cp creates a file called chmod with executable permissions, but which is really the ls executable. The second cp populates this file with the binary code of chmod, while preserving the execute permissions of the target file (because we did not specify any options to carry over permissions of the source file).

Another approach is to use the install utility which is a glorified copying program which can set permissions in one step. (See the -m argument.)
$ install -m a+x /bin/chmod .
$ ./chmod # executes

The install program isn't part of the Unix specification, but it is found in BSD, and in GNU Coreutils. Both support the -m option with chmod-like syntax, both symbolic and octal.

A: You can run the loader directly, and pass it the command you want to run:
/lib/ld-linux.so /bin/chmod +x /bin/chmod

Your path to the loader might vary. On a 64-bit system you need to choose the right one based on how chmod was compiled; the 64-bit version is named something like /lib64/ld-linux-x86-64.so.2

A: First things off the top of my head,

*

*Boot from any other source (network book, cd, etc.) and use the chmod on that source to set the permissions.

*Write a tiny C program to change the permissions.

*Write a perl script (ruby, php, python, etc.) to change the permissions

/usr/bin/chmod is just making a system call to change the permissions, you can make that system call yourself in any number of ways.

A: This is hackier than any of the other answers
(with the possible exception of the ld-linux.so answer,
which is a really clever hack),
but may be more adaptable to other problems
(especially if you fall into a time vortex
and travel back to a Land Before Perl™).

*

*For safety, copy /bin/chmod to a safe place:
cd
cp /bin/chmod .

*Do echo chmod | cpio -oc > chmod.cpio
This creates a cpio archive (not unlike a tar archive) containing chmod.
The -c option specifies that the file metadata is written in hex
(i.e., in ASCII).

*vi chmod.cpio
You'll see something like
0707010005DBFD000081A4000303E9000302010000000155C64D6E0000C01D000068E70000C361…chmod^@…
                   ↑↑↑

followed by a mixture of control characters, standard ASCII characters,
and extended ASCII characters.  Note that 0644 = 0x1A4 and 0755 = 0x1ED.
Find the 1A4 (starting at the 20th character position)
and change it to 1ED.  Save and exit.

*

*If you have a hex editor or something similar,
it might be better to use that to avoid the risk
that vi will contaminate the binary executable code in the file.
But I tried this with vi, and it seemed to work OK.

*cpio -i < chmod.cpio
You now have a copy of chmod in your directory, protected 755.

Other archive programs may have similar capabilities.
In particular, cpio is old and may be deprecated;
if you don't have it, look for pax.

A: The chmod utility relies on the chmod() system call (see man 2 chmod).  So you could do this with a few lines of C, or just about any other language that has a wrapper around it (which would be most of them).  Very few *nix systems are going to lack a C compiler and a perl interpreter; most linux distros require the later to work.
perl -e 'chmod 0755, "foobar.file"'

A: Or even easier - use setfacl which is often present on modern systems:

*

*Set executable permission for user:
# setfacl -m u::rx /bin/chmod

*Now use the now executable binary to set its own permissions back to the original ones (i.e. for all users)
# chmod +x /bin/chmod

*Drop extended ACL entries - optional, since there might have been a good reason why they were there in the first place.
# setfacl -b /bin/chmod

Note, that setfacl can be used on a filesystem that doesn't support ACLs as well.

A: Using setfacl:
setfacl -m u::rwx /bin/chmod

Easy/ Lazy Method ;)
rpm -qf /bin/chmod        # gets package name, coreutils
yum reinstall coreutils -y          # :D

Test Results:
[root@h1 ~]# ll /bin/chmod
-rwxr-xr-x. 1 root root 58656 Mar 15  2019 /bin/chmod
[root@h1 ~]# chmod 444 /bin/chmod
[root@h1 ~]# ll /bin/chmod
-r--r--r--. 1 root root 58656 Mar 15  2019 /bin/chmod
[root@h1 ~]# yum reinstall coreutils
Loaded plugins: product-id, search-disabled-repos, subscription-manager
Resolving Dependencies
--> Running transaction check
---> Package coreutils.x86_64 0:8.22-24.el7 will be reinstalled
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================================================================================
 Package                                      Arch                                      Version                                           Repository                                             Size
======================================================================================================================================================================================================
Reinstalling:
 coreutils                                    x86_64                                    8.22-24.el7                                       rhel-7-server-rpms                                    3.3 M

Transaction Summary
======================================================================================================================================================================================================
Reinstall  1 Package

Total download size: 3.3 M
Installed size: 14 M
Is this ok [y/d/N]: y
Downloading packages:
coreutils-8.22-24.el7.x86_64.rpm                                                                                | 3.3 MB  00:00:01
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : coreutils-8.22-24.el7.x86_64                                                                                1/1
  Verifying  : coreutils-8.22-24.el7.x86_64                                                                                1/1

Installed:
  coreutils.x86_64 0:8.22-24.el7

Complete!
[root@h1 ~]# ll /bin/chmod
-rwxr-xr-x. 1 root root 58656 Mar 15  2019 /bin/chmod
[root@h1 ~]#


text:
Q: How to deploy web application from local machine to iis azure vm using powershell? I have a asp.net web application, i need to deploy it from local machine on IIS on Azure-VM using powershell script.
I have an existing VM and IIS configured on it and i have installed web deploy.
Can you please provide a script which can solve my problem?

A: Stack Overflow is a community that is here to help when you run into issues with your own code, not to write the code for you. Paxz has in the comments provided a link on how to ask the perfect questions.
To try and get you started on an answer though, have a look at the below article:
https://blogs.msdn.microsoft.com/webdev/2017/11/01/publishing-a-web-app-to-an-azure-vm-from-visual-studio/


text:
Q: Display vector as rows instead of columns in Octave I'm new to octave and running into a formatting issue which I can't seem to fix. If I display a variable with multiple columns I get something along the lines of:
Columns 1 through 6:

        0.75883  0.93290  0.40064  0.43818  0.94958  0.16467

However what I would really like to have is:
0.75883
0.93290
0.40064
0.43818
0.94958
0.16467

I've read the format documentation here but haven't been able to make the change. I'm running Octave 3.6.4 on Windows however I've used Octave 3.2.x on Windows and seen it output to the desired output by default.
To be specific, in case it matters, I am using the fir1 command as part of the signal package and these are sample outputs that I might see.

A: It sounds like, as Dan suggested, you want to display the transpose of your vector, i.e. a row vector rather than a column vector:
>> A = rand(1,20)
A =

 Columns 1 through 7:

   0.681499   0.093300   0.490087   0.666367   0.212268   0.456260   0.532721

 Columns 8 through 14:

   0.850320   0.117698   0.567046   0.405096   0.333689   0.179495   0.942469

 Columns 15 through 20:

   0.431966   0.100049   0.650319   0.459100   0.613030   0.779297

>> A'
ans =

   0.681499
   0.093300
   0.490087
   0.666367
   0.212268
   0.456260
   0.532721
   0.850320
   0.117698
   0.567046
   0.405096
   0.333689
   0.179495
   0.942469
   0.431966
   0.100049
   0.650319
   0.459100
   0.613030
   0.779297


text:
Q: Spark: Dividing one array by elements in another I am new to Apache Spark and Scala. I am trying to understand something here: -
I have one array:
Companies= Array(
  (Microsoft,478953),
  (IBM,332042),
  (JP Morgan,226003),
  (Google,342033)
)

I wanted to divide this by another array, element by element:
Count = Array((Microsoft,4), (IBM,3), (JP Morgan,2), (Google,3))

I used this code :
val result: Array[(String, Double)] = wordMapCount
  .zip(letterMapCount)
  .map { case ((letter, wc), (_, lc)) => (letter, lc.toDouble / wc) }

From here: Divide Arrays
This works. However, I do not understand it. Why does zip require the second array and not the first one also the case matching how is that working here?

A:
Why does zip require the second array and not the first one?

Because that's how zip works. It takes two separate RDD instances and maps one over the other to create pair of the first and second element:
def zip[U](other: RDD[U])(implicit arg0: ClassTag[U]): RDD[(T, U)]

case matching how is that working here

You have two tuples:
(Microsoft, 478953), (Microsoft,4)

What this partial function does decomposition of the tuple type via a call to Tuple2.unapply. This:
case ((letter, wc), (_, lc))

Means "extract the first argument (_1) from the first tuple into a fresh value named letter, and the second argument (_2) to a fresh value named wc. Same goes for the second tuple. And then, it creates a new tuple with letter as the first value and the division of lc and wc as the second argument.


text:
Q: Checkbox que troca imagem em javascript Eu preciso, em um projeto, de uma interação que consiste em 5 checkboxes, que ao marcados, mudam a src de imagens na página.
Eu já achei um pronto, na verdade:
http://jsfiddle.net/y015gunx/1/
O que eu quero fazer é criar mais checkboxes para mudar a source de outras imagens, dentro do mesmo script.
Estou tentando fazer isso há um tempo, mas não consigo (por não conhecer nada de Javascript).
Esse script é a melhor solução para isso? Como eu faria para adicionar mais uma imagem e outro checkbox?

A: Se você for ter mais de uma opção pra mudar a mesma imagem então minha recomendação é utilizar radio ao invés de checkbox e separar ele em grupos. O problema do checkbox que eu penso seria quando você selecionar 2 checkboxs para alterar uma mesma imagem, qual prevalece e por que deixaria os 2 checados?
Exemplo:

function mudarBg(valor, idImg) {
    document.getElementById(idImg).src = valor;
}
window.onload = function() {
    document.getElementsByName('bgradio1')[0].click();
    document.getElementsByName('bgradio2')[0].click();
}
#sua_img {
    display: block;
    width: 150px;
    height: 150px;
}

#sua_img2 {
    display: block;
    width: 150px;
    height: 150px;
}
<input type="radio" name="bgradio1" onclick="mudarBg(this.value, 'sua_img')" value="http://igshalon.com/iswp/wp-content/uploads/2014/02/numero-1.jpg">Imagem 1.1

<input type="radio" name="bgradio1" onclick="mudarBg(this.value, 'sua_img')" value="https://s3-sa-east-1.amazonaws.com/leroy-production//uploads/img/products/numero_para_residencia_numero_2_14_5_cmx10_cm_cromado_bemfixa_87963715_0001.jpg_1800x1800.jpg">Imagem 1.2

<input type="radio" name="bgradio1" onclick="mudarBg(this.value, 'sua_img')" value="https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/N%C3%BAmero_3_(manuscrito).svg/305px-N%C3%BAmero_3_(manuscrito).svg.png">Imagem 1.3

<input type="radio" name="bgradio2" onclick="mudarBg(this.value, 'sua_img2')" value="http://cdn3.colorir.com/desenhos/pintar/numero-4_2.png">Imagem 2.1

<input type="radio" name="bgradio2" onclick="mudarBg(this.value, 'sua_img2')" value="http://vignette2.wikia.nocookie.net/runescape/images/c/c1/N%C3%BAmero_5.png/revision/latest?cb=20120802141805&path-prefix=pt">Imagem 2.2

Explicação:
A função mudarBg recebe 2 parâmetros:

*

*valor - é o value que está no input, no meu exemplo coloquei a URL da imagem.

*idImg - é o id da  que você quer mudar, exemplo os 3 primeiros radio alteram a primeira imagem enquanto os 2 últimos radio alteram a segunda imagem.

O atributo name do input agrupa os radio, então todos que possuem bgradio1 só pode ter um selecionado e a mesma coisa pro bgradio2.
-
Exemplo com checkbox:

function mudarBg(campo, idImg) {
    if (campo.checked) {
        document.getElementById(idImg).style.backgroundImage = 'url(' + campo.value + ')';
    } else {
        document.getElementById(idImg).style.backgroundImage = '';
    }
}
#sua_img {
    display: block;
    width: 250px;
    height: 150px;
    background-image: url('http://blog.trifork.com/wp-content/uploads/2014/09/Html5_canvas_logo.png')
}

#sua_img2 {
    display: block;
    width: 250px;
    height: 150px;
    background-image: url('http://mohitrickzz.heck.in/files/flags-dd-css.jpg')
}
<input type="checkbox" onclick="mudarBg(this, 'sua_img')" value="http://jstricks.com/wp-content/uploads/2014/07/javascript-redirect.png">Imagem 1

<input type="checkbox" onclick="mudarBg(this, 'sua_img2')" value="http://php.quicoto.com/wp-content/uploads/2013/06/css3.jpg">Imagem 2

A função mudarBg agora recebe o campo inteiro, através dele como saber se ele foi checked e qual seu valor.
O segredo está atribuindo CSS com um background-image padrão e quando eu seleciono o checkbox eu atributo um novo background-image direto no style. Dessa forma quando eu removo o checked ele só limpa o atributo style e mantém o CSS.


text:
Q: Ideas for extracting string when its place varies from row to row in Excel I am trying to extract a string(username) from a excel table.
username's place varies from row to row for example:

*

*D:\Users\james

*D:\Users\johnny2

*D:\Userdata\Users\mark\My Documents

*D:\Users\Jessica\My Private Files\Files

*D:\NewteamUsers\Molly2\Documents

What I need to extract is only usernames

*

*james

*johnny2

*mark

*Jessica

*Molly2

Because it varies from row to row I can't use a function to extract after nth character or specific character. Only common things are before usernames start always there is "sers\" and "\" character or blank space.
Could you please guide me how can I implement this using functions?

A: Try,
=TRIM(LEFT(SUBSTITUTE(REPLACE(A2, 1, FIND("sers\", A2)+4, TEXT(,))&"\", "\", REPT(" ", LEN(A2))), LEN(A2)))

If Users is not always proper case, swap SEARCH for FIND and you will get a non-case-sensitive location for the string search.

A: This one should work:
=IF(ISERROR(FIND("\",RIGHT(A1,LEN(A1)-FIND("Users\",A1)-5))),RIGHT(A1,LEN(A1)-FIND("Users\",A1)-5),LEFT(RIGHT(A1,LEN(A1)-FIND("Users\",A1)-5),FIND("\",RIGHT(A1,LEN(A1)-FIND("Users\",A1)-5))-1))

A: Here's one more approach.
=TRIM(MID(SUBSTITUTE(A2,"\",REPT(" ",99)),SEARCH("sers",SUBSTITUTE(A2,"\",REPT(" ",99)),1)+99,99))


text:
Q: Use RSACng to SignData that's compatible with RSACryptoServiceProvider I'm trying to convert some older CAPI code to use CNG, specifically with the goal of hydrating certificates with ephemeral private keys. (Not supported by CAPI, as I understand it.)
We use a certificate's private key (PK) to sign data. I expected the two implementations to produce compatible output, but to my surprise they don't.
// Hydrate a cert with PK. Make PK a file-based key so we can get the container and use CAPI.
// (Note, although .NET Framework 4.8, the LangVersion is 8.0 so I can use using.)
using var cert = new X509Certificate2(testCertData, "passwd", X509KeyStorageFlags.MachineKeySet);
// Some arbitrary data to sign.
byte[] data = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };

byte[] signatureCsp, signatureCng;
// Sign with CAPI. This is what we're doing today.
// The cert PK's crypto provider doesn't support SHA256, so we build a different one.
var csp = (RSACryptoServiceProvider)cert.PrivateKey;
var cp = new CspParameters{
    KeyContainerName = csp.CspKeyContainerInfo.KeyContainerName,
    KeyNumber = csp.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2,
};
using (var rsaCsp = new RSACryptoServiceProvider(cp)) {
    signatureCsp = rsaCsp.Sign(data);
}
// Sign with CNG. This is what I want to do.
using (var rsaCng = cert.GetRSAPrivateKey()) {
    signatureCng = rsaCng.Sign(data);
}
// The signatures are different. In fact they're different lengths, 128 and 256 bytes respectively.
Console.WriteLine(Convert.ToBase64String(signatureCsp));
Console.WriteLine(Convert.ToBase64String(signatureCng));

// But maybe they're compatible? Let's see if code which verifies the first can verify the second.
using (var provider = new RSACryptoServiceProvider(cp)) {
    var verifiedCsp = provider.Verify(data, signatureCsp);
    var verifiedCng = provider.Verify(data, signatureCng);
    Console.WriteLine("RSACryptoServiceProvider verified: {0}", verifiedCsp);
    Console.WriteLine("RSACng signature         verified: {0}", verifiedCng); // Nope. False.
}

The above uses the following extension methods, for uniformity, treating both cases as implementations of the abstract RSA base type and with the same crypto parameters.
public static byte[] Sign(this RSA rsa, byte[] buffer) {
    return rsa.SignData(buffer, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
public static bool Verify(this RSA rsa, byte[] buffer, byte[] signature) {
    return rsa.VerifyData(buffer, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

What do I need to do to sign data with the certificate's CNG key so that the output can be verified by current consumers of signatures produced by the CAPI key?

A: Your usage of the RSA classes is correct, and will produce compatible results for the appropriate keys.
The problem here is that you open the PFX into the machine key store:
using var cert = new X509Certificate2(testCertData, "passwd", X509KeyStorageFlags.MachineKeySet);

But when you reopened the RSACryptoServiceProvider version of the key, you didn't set the CspProviderFlags.UseMachineKeyStore flag.
var cp = new CspParameters{
    KeyContainerName = csp.CspKeyContainerInfo.KeyContainerName,
    KeyNumber = csp.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2,
};

Since you didn't set the machine key store flag, it used the user keystore, and "opening" the key created a new key (since one did not previously exist with that name).  After it was created once, successive runs would reopen the same key (assuming the PFX import got a consistent key name).
var cp = new CspParameters{
    KeyContainerName = csp.CspKeyContainerInfo.KeyContainerName,
    KeyNumber = csp.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2,
    Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey,
};


text:
Q: Retrieving input data into array, but giving every single element a length As the title shows I have a problem that I'm fighting and can't find a solution to it so here I am. Im writing a simple "decision maker" and need to gather the info from the input bar and put it to the empty array. BUT (as you know) typing in the input gives me only a solid string and I need a array of seperated elements (eg. ["pizza", "restaurant", "movies"]. I've tried it with .split() but it only works partways because all of the elements are assingned to the same length.
Is there a function/method to do what I need?

const array = [];
const helpBar = document.querySelector("input");
const answerBar = document.querySelector("h1");

const askHelp = (e) => {
  if (e.key === "Enter") {
    e.preventDefault();
    e.stopImmediatePropagation();
    const myArr = helpBar.value.split("");
    array.push(myArr);
    console.log(array);
    helpBar.value = "";
    const arrayRNG = Math.floor(Math.random() * array.length);
    document.querySelector("h1").textContent = array[arrayRNG];
  }
};

helpBar.addEventListener("keydown", askHelp);
<form>
  <input type="text" id="input" />`enter code here`

</form>

A: If I where you id do it similar too this:
This will add new input for every new item on click of button and on another click take all values and pick random one:

const helpBar = document.querySelector("input");
const answerBar = document.querySelector("h1");
const newItem = document.querySelector("#newitem");
const randomize = document.querySelector("#randomize");
const item = document.querySelector(".item");
const items = document.querySelector("#items");

const itemFun = (e) => {
  let itemClone = item.cloneNode(true)
  itemClone.value = ""
  items.appendChild(itemClone);
}

const askHelp = (e) => {
  let res = []
  document.querySelectorAll(".item").forEach(item => {
    res.push(item.value)
  });

  var randomItem = res[Math.floor(Math.random() * res.length)];
  answerBar.innerHTML = randomItem
};

newItem.addEventListener("click", itemFun);
randomize.addEventListener("click", askHelp);

  <input type="text" class="item" id="input" />

<button type="button" id="newitem">Add new item</button>

<button type="radom" id="randomize">Randomize</button>

Or if you really want to use input event and one input element, set the delimiter as , comma for example. And detected if one is present then  split at that mark:

const helpBar = document.querySelector("input");
const answerBar = document.querySelector("h1");

const askHelp = (e) => {

  if (e.target.value.includes(",")) {
    let res = e.target.value.split(",").map(Function.prototype.call, String.prototype.trim)
    // this will split at comma and also trim spaces if user has entered

    var randomItem = res[Math.floor(Math.random() * res.length)];
    answerBar.innerHTML = randomItem
  }
};

helpBar.addEventListener("input", askHelp);
<input type="text" class="item" id="input" />


text:
Q: vb.net arcobjects determine whether arcmap is in editing session I have a vb.net arcmap addin which provide a function to validate geodb topology. But there is a problem, when I am not in editing session and use the function, arcmap will crash. In this case I intend to check whether the map is in editing session.
Is there a way to check whether arcmap is in editing session?
I am using vb.net and arcmap 10.2.

A: You can check for the EditState on the editor extension.

A: After Jay's help, I have successfully check when arcmap is in editing session, the code is as floows:
    Dim editorUid As New UID()
    editorUid.Value = "esriEditor.Editor"
    m_editor = TryCast(My.ArcMap.Application.FindExtensionByCLSID(editorUid), IEditor3)
    m_editEvents = TryCast(m_editor, IEditEvents_Event)
    If m_editor.EditState = esriEditState.esriStateNotEditing Then
        MsgBox("You must in editing session to validate the topology")
    End If


text:
Q: Having issues with my long running task I have an asp.net web app but I am unable to navigate through it while my process in the background finishes what it's doing, which is getting data from a stored procedure (takes about ~20 secs). This action gives me a Json string in return. Once it's done I am able to navigate just fine. But, my question is: what do I need to do in order to keep my website responsive while my main operation finishes?
The way my main site is set up a form in in Index.cshtml and once the page load I do a "force submit" in order to call my action.
@model Foo.Models.HomeViewModel
@{
  ViewBag.Title = "Home";
}

    @using (Ajax.BeginForm("GetData", null,
new AjaxOptions
{
  HttpMethod = "post",
  InsertionMode = InsertionMode.Replace
}, new { id = "MyForm" })){

---


text:
Q: Implementing my own pow function in Java This is a popular interview question. Implementing my own pow function.
There are some popular recursive approaches available online but I'm trying to do it iteratively. The code works for n > 0, but I'm a little lost when it gets below 0. Here's my code.
 public double myPow(double x, int n) {

        if(x == 0) return 0;
        if(n == 0) return 1;

        double result = 1;
        if(n > 0 ){
            for(int i=1; i <= n; i++){
                result = result * x;
            }
        }else{
            for(int i=1; i<= n; i++){

               //calculate the nth root
            }
        }

        return result;
    }

Any help appreciated with calculating the nth root.

A: I guess you can do that: (because x^(-n) = 1/x^n)
double positive_pow(double x, int n) {

        if(x == 0) return 0;
        if(n == 0) return 1;

        double result = 1;
        if(n > 0 ){
            for(int i=1; i <= n; i++){
                result = result * x;
            }
        }else{
            for(int i=1; i<= n; i++){

               //calculate the nth root
            }
        }

        return result;
    }

public double pow(double x, int n) {
    if (n > 0) return positive_pow(x, n);
    else if (n == 0) return 1;
    else return 1 / positive_pow(x, 0-n);
}

This is not the shortest way to implement this, but it is based on your base function and it's more clear than recursively calculating it or messing around with Math functions.

A: This will work.

This code will be returning result for negative powers as well. For the explanation I have used the variable int p= x for my calculation of negative powers.....

public static double Pow(int x,int n){
    if(x == 0) return 0;
    if(n == 0) return 1;

    double result = 1;
    if(n > 0 ){
        for(int i=1; i <= n; i++){
            result = result * x;
        }
    }

    else{

        int p=x;

        for(int i=0; i>n; i--){
            if(result==1){
                result= 1/(result*x);
                result++;
            }

            else{
                p=p*x;
                result= (1.0)*1/p;
            }

        }
    }
    return result;
}

A: Try this, I wrote this one when I was practicing Java. The idea is 5^62=5^(32+16+8+4+2)=5^32*5^16*5^8*5^4*5^2, and in binary code, 62 is 00111110.
Here is the code:
double pow(double x, int n){
    int i;
    double result;
    result = 1;
    i = x;
    while(n != 0){
        if(n & 1 == 1){
            result *= i;
        }
        i *= i;
        n>>1;
    }
    return result;
}


text:
Q: Filter output of a process with `grep` while keeping the return value I think this is not a Python question but in order to provide the context I'll tell, what exactly I'm doing.
I run a command on a remote machine using ssh -t <host> <command> like this:
if os.system('ssh -t some_machine [ -d /some/directory ]') != 0:
    do_something()

(note: [ -d /some/directory ] is only an example. Could be replaced by any command which returns 0 in case everything went fine)
Unfortunately ssh prints "Connection to some_machine close." every time I run it.
Stupidly I tried to run ssh -t some_machine <command> | grep -v "Connection" but this returns the result of grep of course.
So in short: In Python I'd like to run a process via ssh and evaluate it's return value while filtering away some unwanted output.
Edit: this question suggests s.th. like
<command> | grep -v "bla"; return ${PIPESTATUS[0]}

Indeed this might be an approach but it seems to work with bash only. At least with zsh PIPESTATUS seems to be not defined.

A: Use subprocess, and connect the two commands in Python rather than a shell pipeline.
from subprocess import Popen, PIPE, call
p1 = Popen(["ssh", "-t", "some_machine", "test", "-d", "/some/directory"],
           stdout=PIPE)
if call(["grep", "-v", "Connection"], stdin=p1.stdout) != 0:
    # use p1.returncode for the exit status of ssh
    do_something()

Taking this a step further, try to avoid running external programs when unnecessary. You can examine the output of ssh directly in Python without using grep; for example, using the re library to examine the data read from p1.stdout yourself. You can also use a library like Paramiko to connect to the remote host instead of shelling out to run ssh.