text:
Q: How to transpose a 2 dimensional array on C via call by reference? As the title says, I am trying to transpose a 2 dimensional matrix by calling by reference.
I have attached my code below. When I run the code, the 2 dimensional array is unchanged.
#include <stdio.h>

#define SIZE 4

void transpose2D(int ar[][SIZE], int rowSize, int colSize);

int main()
{

    int testArr[4][4] = {
        {1, 2, 3, 4},
        {5, 1, 2, 2},
        {6, 3, 4, 4},
        {7, 5, 6, 7},
    };

    transpose2D(testArr, 4, 4);

    // print out new array
    for (int i = 0; i < 4; i++)
    {

        for (int j = 0; j < 4; j++)
        {
            printf("%d ", testArr[i][j]);
        }

        printf("\n");
    }

    return 0;
}

void transpose2D(int ar[][SIZE], int rowSize, int colSize)
{

    for (int i = 0; i < rowSize; i++)
    {
        for (int j = 0; j < colSize; j++)
        {
            int temp = *(*(ar + i) + j);
            *(*(ar + i) + j) = *(*(ar + j) + i);
            *(*(ar + j) + i) = temp;
        }
    }
}

Have been stuck for a couple of hours, any help is greatly appreciated, thank you!

A: To fix your function I suggest:

*

*switch element only once, the previous version swapped elements for i=a, j=b and i=b,j=a, so the matrix remained unchanged

*use a common a[i][j] syntax

*let the non-square matrix be embedded into a larger matrix whose inner dimensions is set to stride.

*using VLAs to make the interface a bit more generic

void transpose2D(size_t rows, size_t cols, size_t stride, int ar[][stride]) {
    assert(rows <= stride);
    assert(cols <= stride);
    for (size_t i = 0; i < rows; i++) {
        for (size_t j = i + 1; j < cols; j++) {
            int tmp = ar[j][i];
            ar[j][i] = ar[i][j];
            ar[i][j] = tmp;
        }
    }
}

Exemplary usage:
int testArr[4][4] = {
        {1, 2},
        {5, 1},
        {6, 3},
    };

transpose2D(3, 2, 4, testArr);

The algorithm is still very inefficient due to terrible cache miss rates on access to a[j][i]. It can be fixes by tiling and transposing smaller 8x8 blocks, but it is a topic for another day.


text:
Q: Create flip cart animation between two NSViews Hi I want to create flip card animation between two full screen NSViews
but my animation didn't work as expected like in iOS
here is example of iOS working code
UIView.transition(from:self.upperView, to:self.lowerView,duration:1,options:[.transitionFlipFromRight])

On mac OS app i am trying add two NSViews stack on top of each other.
private lazy var lowerView:NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.red.cgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private lazy var upperView:NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.green.cgColor
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

Thank I add 2 views to parent view of the viewcontroller with constraints.
private func addUpperView() {
        self.view.addSubview(upperView)
        NSLayoutConstraint.activate([
            upperView.topAnchor.constraint(equalTo: self.view.topAnchor),
            upperView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            upperView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            upperView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),

        ])
    }

    private func addLowerView () {
        self.view.addSubview(lowerView)
        NSLayoutConstraint.activate([
            lowerView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            lowerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            lowerView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
            lowerView.heightAnchor.constraint(equalTo: self.view.heightAnchor)        ])

    }

All of this i am executing in on viewDidAppear
override func viewDidAppear() {
addLowerView()
addUpperView()

 DispatchQueue.main.asyncAfter(deadline: .now()+2) {
            FlipTransition().flip(from: self.upperView, to: self.lowerView)
        }

}

And this is my helper class for executing the animation.
import Cocoa

public final class FlipTransition: NSObject {

    private var srcView, dstView: NSView?

    private var duration: TimeInterval = 2

    public func flip(
        from srcView: NSView,
        to dstView: NSView,
        duration: TimeInterval = 2
    ) {

        self.duration = duration
        self.srcView = srcView
        self.dstView = dstView
        srcView.isHidden = false
        dstView.isHidden = true

        guard let superLayer = srcView.layer else {
            return
        }

        var transform3D = CATransform3DIdentity
        transform3D.m34 = 1 / -1000

        let translation = CATransform3DMakeTranslation(
            superLayer.bounds.midX,
            superLayer.bounds.midY,
            .zero
        )

        superLayer.sublayerTransform = CATransform3DConcat(
            transform3D,
            translation
        )

        animate(
            srcView,
            from: CATransform3DIdentity,
            to: CATransform3DMakeRotation(CGFloat.pi / -2, 0, 1, 0)
        ) { f in
            self.startSecondStep()
        }
    }

    private func startSecondStep() {

        guard let srcView = srcView, let dstView = dstView else {
            return
        }

        srcView.isHidden = true
        dstView.isHidden = false
        animate(
            dstView,
            from: CATransform3DMakeRotation(CGFloat.pi / 2, 0, 1, 0),
            to: CATransform3DIdentity
        ) { f in
            self.finish()
        }
    }

    private func finish() {

        guard let srcView = srcView, let dstView = dstView else {
            return
        }

        srcView.layer?.removeAllAnimations()
        dstView.layer?.removeAllAnimations()

        [srcView, dstView]
            .compactMap(\.layer)
            .forEach { layer in
                layer.anchorPoint = .zero
            }

        srcView.superview?.layer?.sublayerTransform = CATransform3DIdentity
    }

    private class AnimationDelegate: NSObject, CAAnimationDelegate {

        private let completion: (Bool) -> Void

        init(completion: @escaping (Bool) -> Void) {
            self.completion = completion
        }

        func animationDidStart(_ anim: CAAnimation) { }

        func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
            completion(flag)
        }

    }

    private func animate(
        _ view: NSView,
        from: CATransform3D,
        to: CATransform3D,
        completion: @escaping (Bool) -> Void
    ) {

        let dstRotation = CABasicAnimation(keyPath: "transform")
        dstRotation.fromValue = from
        dstRotation.toValue = to
        dstRotation.duration = duration / 2
        dstRotation.fillMode = .forwards
        dstRotation.isRemovedOnCompletion = false
        dstRotation.delegate = AnimationDelegate(completion: completion)

        view.layer?.add(dstRotation, forKey: "flip")
    }

}

Can some one help me pls how to achieve the same animation like in iOS using UIView.transition

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solution of differential equation $(\frac{dy}{dx})^2 - x\frac{dy}{dx} + y = 0$ A Solution of differential equation $(\frac{dy}{dx})^2 - x\frac{dy}{dx} + y = 0$ is

A) $y = 0$ B) $y = 2x$ C) $y = 2x - 4$ D) $y = 2x^2 - 4$

The answer to the problem is given as $y = 2x - 4$ which makes sense since $\frac{dy}{dx} = 2$ hence the equation becomes $(4) - x(2) + (2x-4) = 0$ which is correct
However I do not understand why $y=0$ cannot be the solution to this equation since $\frac{dy}{dx} = 0$ in this case and so the differential equation should be true in this case aswell. Is there something I am missing or making some wrong consideration ? or is there any possible error in the answers ?

A: This is a Clairaut equation
$$
y=xy'-y'^2
$$
which has linear solutions
$$
y=Cx-C^2
$$
and a singular solution/envelope
$$
y=\frac{x^2}4.
$$


text:
Q: I have a chain of Rx.Subjects (A->B->C->A), but the final step is not working Live example.
I'm completely new to Rx*. I'm trying to create a reactive version of MVC using RxJS for my thesis. It's loosely based on https://github.com/staltz/mvi-example
I probably should've studied RxJS more before starting to code, but I've realised I usually learn the best by just jumping to the deep end of the pool. Now I'm completely stuck however.
The View has a text field with a numeric value and a button. Pressing the button changes the color of the text, clicking the text iterates the numeric value. The value is stored in the model, so that "chain" goes through all three objects (View->Controller->Model->View). Pressing the button does not require the model, so that chain is View->Controller->View.
Everything else works, but the final part of the chains (->View) is giving me trouble. Clicking on the text (in the View) propagates changes to the Controller and to the Model, but the View is not notified of the change in the Model. I don't understand why, since the way I understand this all these are implemented in the same way.
I've added comments to the code sample below to designate the functions that don't get called.
The code is available here. Note that, like I said, the code is for my thesis so some design decisions and the app itself may seem odd. Below I've also tried to include the parts I feel are most relevant. I know I should provide a complete example, but it's kind of impossible in this case.
The "obs" parameter that objects get is an internal data structure that I use to store observables. The relevant part is
var OBSERVABLES = {
    observe: function(source, observer, observer_name) {
      this.request(source, function(s) {
        console.log("\t[" + source + " is being observed by " + observer_name + " (" + s.constructor.name + " -> " + observer.constructor.name + ")]")

        return s.subscribe(
          function myOnNext(x) {
            console.log("\t(" + source + ") " + s.constructor.name + " -> OnNext -> (" + observer_name + ") " + observer.constructor.name)
            observer.onNext(x)
          },
          function myOnError(err) {
            console.log(error)
          })
      })
    },

View.js
var modelAmount = new Rx.Subject()
var textClicks = new Rx.Subject()
var buttonClicks = new Rx.Subject()
var changeColors = new Rx.Subject()

function View(obs, div) {
  console.log("View :: New View")
  obs = obs
  div = div
  var self = this

  obs.observe("clickAmount", modelAmount, "modelAmount")
  obs.observe("changeColor", changeColors, "changeColors")
  obs.add("textClicks", textClicks)
  obs.add("buttonClicks", buttonClicks)

  //Draw HTML elements
  render(div);
}
...
function onClick() {
  console.log("View :: onClick() emits 'textClicks'");
  textClicks.onNext()
}

function onButtonClick() {
  console.log("View :: onButtonClick() emits 'buttonClicks'");
  buttonClicks.onNext()
}

//Listen to controllers instruction to change the color
// DOES NOT WORK
var changeNumberColor = changeColors.map(function(c) {
  console.log("View :: Listened to 'changeColor'")
  if (c === undefined) {
    c = getColor()
  }

  CONTENT.css('color', c)
});

//Listen to model's instruction to change the value
// DOES NOT WORK
var setValue = modelAmount.last(function(latestValue) {
  console.log("View :: Listened to 'clickAmount'")
  console.log("View :: setValue(" + latestValue + ")")
  CONTENT.text(latestValue)
});

Controller.js
  var inputTextClicks = new Rx.Subject();
  var inputButtonClicks = new Rx.Subject();

  var obs = null;

  function Controller(obs){
    console.log("Controller :: New Controller")
    obs = obs

    obs.observe("textClicks", inputTextClicks, "inputTextClicks")
    obs.observe("buttonClicks", inputButtonClicks, "inputButtonClicks")

    obs.add("addAmount", addAmount);
    obs.add("changeColor", changeColor);
  }

  //Listen to input events and give instructions to model
  var addAmount = inputTextClicks.map(function(){
    console.log("Controller :: addAmount() listened to 'textClicks' and emits 'addAmount'")
    return 1;
  });

  //Listen to button presses and give instructions to the view
  var changeColor = inputButtonClicks.map(function(){
    console.log("Controller :: ChangeColor() listened to 'buttonClicks' and emits 'changeColor'")
    return 1;
  });

Model.js
  var controllerAddAmount = new Rx.Subject();

  var obs = null;

  //Stores the texts value. Starts at 0
  var VALUE = 0;

  function Model(obs){
    console.log("Model :: New Model")
    obs = obs

    obs.observe("addAmount", controllerAddAmount, "controllerAddAmount")
    obs.add("clickAmount", amountChanged)
  }

  //Listen to the controller about changing the value, notify the view about the new value
  var amountChanged = controllerAddAmount.map(function(val){
    console.log("Model :: amountChanged() listened to 'addAmount' and emits 'clickAmount'")
    VALUE += val
    console.log("Model :: Amount Changed to " + VALUE)
    return VALUE;
  })

So the problem is View.setValue() and View.setNumberColor().

A: You have a lot of code that essentially looks like this:
// Listen to x to ...
var a = x.map(function (val) { ... });

But then you never show what you do with a.  map takes an observable and produces a new observable that will run the supplied mapping operation.  However, the observable it returns is inert and does not actually do anything unless you eventually subscribe to a (or some derivative of a).
It looks like for your controller and model you eventually do subscribe to the observables they are producing (through the circuitous route of adding them to your obs and then subscribing to them in your view).
However, it isn't clear you ever subscribe to changeNumberColor or modelAmount.  Based upon the imperative code within those two map methods, I'm guessing you should be using subscribe instead of map in those 2 cases.
Also, for modelAmount you are using the last operator incorrectly.  Most likely you think last does something different than it does.


text:
Q: ssh no longer resolving for any hostnames Initially, I thought my SSH wasn't working on a university server due to a recent update to the VPN. I refreshed the connection, re-added the portal and restarted my device but no luck. Then, I tried my SSH on a few more hostnames (namely from OverTheWire.org) and it isn't resolving any of them.
I am using Ubuntu as a Windows Subsystem currently. Haven't updated it or installed anything recently, so I have no idea why SSH has stopped working in the normal fashion.
What actions should I take? I know the university network and my VPN are fine because my mapped drive is still accessible and I am able to access the university network via my browser. Just seems to be a problem specific to SSH right now.


text:
Q: prove $\frac{n e^{-n^2 x^2}}{\sqrt{\pi }}$ converges to $\delta(x)$ How can show as $n$ goes toward infinity the sequence converges to $\delta(x)$ my problem is I don't know how to show this.

A: Convergence in the sense of distributions is defined as follows: a sequence of distributions $\tau_n\in \mathscr D'(\mathbb R)$ is said to converge to a distribution $\tau\in\mathscr D'(\mathbb R)$ if, for every test function $\varphi\in C^{\infty}_0(\mathbb R)$, there holds
$$
\lim_{n\to\infty}\langle \tau_n, \varphi\rangle =\langle \tau, \varphi\rangle,
$$
in the usual topology of $\mathbb R$. The $\langle\cdot,\cdot\rangle$ denotes the action of the distribution on the test function:
$$
\tau:C^{\infty}_{0}(\mathbb R) \longrightarrow \mathbb R\\
\varphi \longmapsto \langle \tau, \varphi \rangle,
$$
which is linear and continuous in the appropriate sense. Of course, distributions which are in fact locally summable functions $\tau_f\simeq f$ act on test functions $\varphi$ by
$$
\langle \tau_f, \varphi \rangle = \int_{\mathbb R}f(x) \varphi(x) dx.
$$
Consider a test function $\varphi\in C^\infty_0(\mathbb R)$ (i.e. infinitely regular and of compact support). Then letting
$$
\rho_n(x)\equiv \frac{n}{\sqrt{\pi}}e^{-n^2x^2}
$$
we have
$$
\langle \rho_n, \varphi \rangle =
\int_{-\infty}^{+\infty} \frac{n}{\sqrt{\pi}}e^{-n^2x^2} \varphi(x) dx\\
=\int_{-\infty}^{+\infty} \frac{1}{\sqrt{\pi}}e^{-y^2} \varphi(y/n) dy
$$
where we have used the change of variables $y=nx$ in the last step. Since the integrand is dominated by the (summable) function
$$
e^{-y^2} \sup_{x\in\text{supp}\varphi}|\varphi(x)|
$$
we can apply Lebesgue's theorem and pull the limit $n\to\infty$ inside the integral getting
$$
\lim_{n\to\infty}\langle \rho_n, \varphi \rangle =
\int_{-\infty}^{+\infty} \frac{1}{\sqrt{\pi}}e^{-y^2} \varphi(0) dy = \varphi(0)
$$
since $\int_{\mathbb R}e^{-y^2}dy = \sqrt{\pi}$.
So we are ready to check the definition: since for every such $\varphi$
$$
\lim_{n\to\infty}\langle \rho_n, \varphi\rangle =\varphi(0)= \langle\delta, \varphi\rangle,
$$
then
$$
\lim_{n\to\infty}\rho_n = \delta
$$
in the sense of distributions over $C^{\infty}_0(\mathbb R)$.


text:
Q: Generating random noise for fun in /dev/snd/ Recently I have been exploring the enchanted /dev folder. I want to write some random data to an audio device in order to generate some noise.
I am using ALSA.
So I instruct cat to pipe some random data to the playback file in the /dev folder...
 cat file-of-random-data > /dev/snd/pcmC0D0p

then I recieve what seems to be an error from cat
 cat: write error: File descriptor in bad state

How can I fix this so I can hear some delicious static play from my sound card?

A: I think the reason this isn't working for you is because that interface has been deprecated. You normally can't write audio using /dev/dsp anymore, at least without being tricky.
There is a program that will accomplish this for you on your system: padsp.
This will map the /dev/audio or /dev/dsp file to the new Audio Server system.
Fire up the terminal and get into root mode with sudo su.
Then, I'm going to cat /dev/urandom and pipe the output into padsp and use the tee command to send the data to /dev/audio. You'll get a ton of garbage in your terminal, so you may want to redirect to /dev/null.
Once you're in superuser, try this command:
cat /dev/urandom | padsp tee /dev/audio > /dev/null

You may even want to try with other devices, like your mouse: Use: /dev/psaux, for instance or the usb driver. You can even run your memory through it:
/dev/mem
Hope this clarifies why it wasn't working before.
Personally, I found the mouse and memory to be way more interesting than playing random static!

A: Try /dev/audio or one of the other devices under /dev/snd. Not all of them are audio data sinks, you might have caught a mixer, microphone, or something

A: Is a sound daemon (e.g. pulseaudio) holding a lock on the device?  I think you can find out if anything else has a handle on it via lsof.

A: cat /dev/urandom | aplay
is the command that needs to be typed. If you aren't in "audio" group, you could prefix aplay with sudo. This also doesn't interfere with any daemons (I was running pulseaudio while this command was active and correctly heard the "noise".
EDIT (Aug 6, 2019): In an older version of the command I also had a padsp tee thing between the cat and aplay. Now that I'm actually working in the field I realise that it made absolutely no sense. Also, I know the updated command (the one visible now at the beginning of this answer) works because I use it several times a day at work.

A: update (2020-12-25): I created a shell script for forwarding data from stdin to stdout which set up stdout if it is a PCM file. Check out https://github.com/psqli/pcmsh.
TL;DR: The device's parameters must be set before reading or writing data to it.
Step by step:

*

*Open the PCM device. E.g.: fd = open("/dev/snd/pcmC0D0p", O_RDWR). After open, PCM is in OPEN state.

*Set parameters with ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, (struct snd_pcm_hw_params*) p). The hardware parameters structure has masks (each bit is a value) and intervals ([minimum, maximum] range). The parameters that are not being set must be passed filled (all bits/values set for masks; full range for intervals). After setting hardware parameters, PCM is in SETUP state. See pcm_set_config() of TinyALSA for code.
Setting ACCESS, FORMAT, RATE, CHANNELS, PERIOD_SIZE and PERIODS is sufficient. The other parameters are variants of these, except BUFFER_SIZE that in some devices may be set to a non multiple of PERIOD_SIZE.

*Call ioctl(fd, SNDRV_PCM_IOCTL_PREPARE) to prepare device and ALSA runtime variables. After this, the PCM is in PREPARED state.

*Start reading (capture) or writing (playback).
A minimal application for reading or writing to a PCM device will have most of its code around hardware parameters manipulation.


text:
Q: Displaying a chartjs chart within a bulma full height hero I am trying to display a chartjs chart within a bulma fullscreen hero section. The desired effect is that the section will take up the available browser space. I would also need for the chart to remain responsive.
It would also be good to be able to add a some text above the chart, a title and subtitle.
The code below works but chartjs become non-responsive.

        <canvas id="chart"></canvas>

If I try and add a title we overflow the full height:

        My title

      <canvas id="chart"></canvas>

A: For anyone looking to do the same thing

Title

        <canvas id="chart"></canvas>

A: Please try this. I think you do not need the container and add the title via the chart.js
Let me know if it helped.

<link href="https://cdn.jsdelivr.net/npm/bulma@0.8.1/css/bulma.min.css" rel="stylesheet"/>

    <canvas id="chart"></canvas>


text:
Q: Why does Scala use the '_' operator for package import instead of '*' as in Java? In my opinion, one of the greatest things about Scala is its interoperability with Java and its similar syntax. One thing that I found strange is the use of the _ operator for package wilcard imports instead of the * operator that is used in Java.
Is there a technical reason for using _ instead of *? If not, then why was this change done?

A: In Scala, the * is a valid identifier. One could write:
val * = "trollin'"
println(*)

With the result being:
trollin'

One could write a class named * as such:
class * {
  def test():String = {
    "trollin'"
  }
}

So with that being the case, when I have a class * in the package us.hexcoder and I write:
import us.hexcoder.*

You would be saying that you wish to import a class with the name *. Because of this, Scala needed to use another symbol to indicate a wildcard import. For whatever reason, they decided to use _ as the wildcard symbol.

A: In addition to Glenn's answer, import is a valid statement anywhere in Scala and you can import an object or an instance members into scope. As * is obviously a member of many classes, it can not be used as a wildcard for the import statement. So you end up with a string which must not be a valid identifier.
_ comes to mind. The fact that it is used in other places for a different meaning (existential type, function as an instance) is also due to the same issue.

A: In functional languages, the _ character is commonly used to say, "I don't care about this parameter" or "anything can go here". Extending that value to namespace imports only makes sense.

A: In Scala there are dozens of places where the underscore is used. Using it for wildcard imports is just a logical consequence.


text:
Q: Deserialize json Object using newtonsoft json I have a json like
{"NewMessage":[{"Id":-1,"Message":"Test","MessageName":"test1"}],"OldMessage":[]}

and  I need to deserialize this json in to my class object.
My Class
public class NewMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}

public class OldMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}

how can we achive this by using newtonsoft.json. can anyone help. thanks in advance

A: Your JSON actually contain an object which have properties of your defined classes - given the code posted, you don't have a class to deserialize into.
The first thing you can do is obvious - create a third class - MessagePair - which declares two properties - NewMessage[] and OldMessage[]. Then you can deserialize the JSON string like this:
var theMessages = JsonConvert.DeserializeObject<MessagePair>(jsonText);

If you don't like to create separate class, you can then deserialize into anonymous object like this:
var theMessages = new {
    NewMessage[] NewMessages = null,
    OldMessage[] OldMessages = null
};

theMessages = JsonConvert.DeserializeAnonymousType(jsonText, theMessages);


text:
Q: How do I clear previous WebView's content before loading the next WebView? My scenario is initially I am loading a WebView and later on I am loading the same WebView with a different URL.
My problem is whenever I am loading the next URL I can see the previously loaded URL contents and then my currently loaded URL contents gets displayed.
I want to clear the contents whenever I am loading the different URL.
Say,
if (pos == 0) {
    mweb.clearCache(true);
    mweb.clearHistory();
    mweb.loadUrl("http://stackoverflow.com/");
}
else if (pos == 1) {
    mweb.clearCache(true);
    mweb.clearHistory();
    mweb.loadUrl("http://android.stackexchange.com/");
}

Both clearCache() and clearHistory() does not work for me.

A: use mweb.clearView(); before loading the new URL.
Edit:
clearView() was deprecated in API level 18. Use WebView.loadUrl("about:blank") to reliably reset the view state and release page resources (including any running JavaScript).
to solve the issue raised by @Liang:
To have a consistent back navigation, you can override "onPageFinished", and inside it check whether the url contains "about:blank" or not. if yes, use "webview.goBack()"

A: I usually hide the webview before loading the new url, and then show it again when the loading progress has advanced a bit.
// url loading
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl(newUrl);

// show webview again
mWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView view, int progress) {
        if (progress >= 10) {
            mWebView.setVisibility(View.VISIBLE);
        }
    }
}

A: I guess you can use Webview.clearHistory(). But remember so impotent to call this after WebView is loaded. For example the code:
webView.loadData(someUrl);
webView.clearHistory();

won't work because webView is not loaded. We have to clear it like:
webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                clearHistory();
            }
}

A: Thnx to StefanK comment found Here, You need to use the clearHistory() method right when the page finishes loading in the WebViewClient onPageFinished(WebView view, String url) method also in the onLoadResource(WebView view, String url) method; as follows:
    myCoolWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url){
            view.loadUrl(url);
            return true;
        }
        @Override
        public void onLoadResource(WebView view, String url) {
            // Notice Here.
            view.clearHistory();
            super.onLoadResource(view, url);
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            // And Here.
            view.clearHistory();
            super.onPageFinished(view,url);
        }
    });

Also you can check the canGoBack() and copyBackForwardList() for manipulations.

A: It seems to set the layer type of webview as "software" can resolve the problem.
Perhaps the previous contents are caused by drawing cache.

A: Create a string with the HTML for a blank page and load that into the webview.  Or hide it until it is loaded.

A: use following statement before loadData     [Kuldip Bairagi]
view.loadUrl("javascript:document.open();document.close();");


text:
Q: how to proceed to checkout page after making order in bigcommerce? I have created orders using Bigcommerce API for a web based app.
Now after creating the order, how do I make the user to proceed to Bigcommerce checkout page to make the payment?
thanks

A: If you are capturing an order via the API, you won't be able to direct the user to a checkout page to just capture payments. The order creation is more for POS kind of flow, where you can capture the payment externally and create an order associated with that product in your bigcommerce store, thereby managing inventory details, syncing orders, etc.


text:
Q: Magento static block is not showing on my layout although I followed the instructions correctly I want to add a static block on my layout. Therefore from the backend I add a new static block and gave an identifier for that. Then I put my block code inside the page.xml file. This is my code,
 <block type="cms/block" name="templatename" template="page/html/templatename.phtml">
 <action method="setBlockId"><block_id>my_id</block_id></action>
 </block>

Then I put the php code inside my phtml (templatename.phtml) file to show the data. This is my code,
  <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_id')->toHtml();?>

Finally my phtml template file is loading in my layout.phtml file. This is that code,
   <?php echo $this->getChildHtml('templatename') ?>

But my static block isn't showing. Why is that? My Magento version is 1.8

A: if you want to call cms static block in your custom phtml file
just use below code to call with unique id define by you in admin cms static block section
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_id'')->toHtml()?>

that will sure display your static block in to you custom phtml files.
or you can use detail link
http://importantmagento.blogspot.in/2012/06/magento-how-to-call-static-block-on.html
i am not associate with above link for any how. it is just for knowledge purpose.
hope this will sure help you.

A: Thanks everyone....finally i could solve the issue.Only thing i was done,remove the block declaration from the xml file.I just write the php code on my template.Now it works fine.


text:
Q: C++ difference between 0 and 0.0 Is there a difference between 0 and 0.0 in C++? Which should you use for initializing a double?
Thanks

A: One appears to be an integer literal, the other a floating point literal.  It really doesn't matter to the compiler whether you initialize floats or doubles with integer literals.  In any event the literal will be compiled into some internal representation.
I would tend to suggest 0.0 in order to make your intention (to other programmers) explicitly clear.

A: Here is the Visual-C++ disassembly for:
int main() {
  double x = 0;
  //
  double y = 0.0;
  //
  double z = x * y;
  return 0;
}

Disassembly
int main() {
00007FF758A32230  push        rbp
00007FF758A32232  push        rdi
00007FF758A32233  sub         rsp,128h
00007FF758A3223A  mov         rbp,rsp
00007FF758A3223D  mov         rdi,rsp
00007FF758A32240  mov         ecx,4Ah
00007FF758A32245  mov         eax,0CCCCCCCCh
00007FF758A3224A  rep stos    dword ptr [rdi]
  double x = 0;
00007FF758A3224C  xorps       xmm0,xmm0
00007FF758A3224F  movsd       mmword ptr [x],xmm0
  //
  double y = 0.0;
00007FF758A32254  xorps       xmm0,xmm0
00007FF758A32257  movsd       mmword ptr [y],xmm0
  //
  double z = x * y;
00007FF758A3225C  movsd       xmm0,mmword ptr [x]
00007FF758A32261  mulsd       xmm0,mmword ptr [y]
00007FF758A32266  movsd       mmword ptr [z],xmm0
  return 0;
00007FF758A3226B  xor         eax,eax
}
00007FF758A3226D  lea         rsp,[rbp+128h]
00007FF758A32274  pop         rdi
00007FF758A32275  pop         rbp
00007FF758A32276  ret

They produced the same assembly. Visual-C++ uses the method of XOR-ing the XMM register with it'self. Had you first loaded the integer 0 then moved it into the XMM register it would have used an extra instruction. Given our hypothesis on how the 0.0 may be loaded as a literal, as well as the extra useless instruction load loading an integer 0 then moving it into a floating-point register, neither is optimal so it seems as though it really doesn't matter because the compiler writer we must assume this optimization has been know for a long time because it is kind of obvious. If 100% portability is required, then it is more portable to write an inline function that manually uses the XOR technique.

A: A literal 0 is considered to be an int literal; literal 0.0 is a double literal. When assigning to a double, either will work (since the int can be cast in a widening conversion); however, casting 0.0 to an int is a narrowing conversion, and must be done explicitly; i.e. (int)0.0.

A: I try to keep my constants type-consistent. 0 for ints. 0.0f or 0.f for float, and 0.0 for double.
To me, the most important reason to do this is so the compiler and the programmer see the same thing.
If I do this...
float t=0.5f;
float r;

r= 1 * t;

...should r be assigned 0 or .5? There's no hesitation if I do this instead...
float t=0.5f;
float r;

r= 1.0f * t;


text:
Q: absolutely continuous Suppose that $f$  is a continuous function on $[a,b]$ . And suppose that there exists an integrable function $g$  on $[a,b]$  such that  $\int_{[a,b]}fh'=-\int_{[a,b]}gh$ for any Lipschitz function $h$  on $[a,b]$ satisfying $h(a)=h(b)=0$. The conclusion is that $f$ is absolutely continuous.
But I just want to know is it possible to deduce that  $f(x)=\int_{[a,x]}g$  for any $x\in(a,b)$ by finding some specific function $h$ and plugging in the equation in the problem? Since we have the Lebesgue integral here, we are not able to apply the integration by parts. So what confuses me is that how can I get rid of the integral sign?

A: Given $x\in(a,b)$, you may choose a sequence of Lipschitz functions $\{h_n\}$ in the following way. For every $n\ge \max(\frac{1}{x-a},\frac{1}{b-x})$,
$$h_n(t)=\left\{\begin{array}{cc}
n(t-a)& t\in[a,a+\frac{1}{n}]\\
1&t\in[a+\frac{1}{n},x]\\
1-n(t-x)&t\in[x,x+\frac{1}{n}]\\
0&t\in[x+\frac{1}{n},b]
\end{array}\right.\ .$$
Then you will find $f(x)=f(a)+\int_a^xg(t)dt$.


text:
Q: Yii CGridView или свой Widget на bootstrap? Есть много модулей с таблицами, вопрос: использовать CGridView(но уж очень он мне не нравится) или же лучше написать своё (и изобрести велосипед)?
A: Что именно не нравится в CGridView?
Если оформление, так к нему можно подключить свой css и оформить так, как вам надо. В остальном он достаточно функциональный
A: Согласен полностью с @Barton и отчасти с @Ale_x.
Но, есть своё но.
Использую именно CGridView, функциональность его огромная. Как раз недавно использовал интересные вещи с его использованием. У него есть куча опций. Изменить поле, добавить поле, сделать свою выборку и прочее, css и многое другое, зачем изобретать велосипед в готовом фреймворке? Не, однозначно не стоит!
A: Смотря как быстро надо Вам сделать проект) Но я бы поступил следующим образом - на начальном этапе разработке пользовался бы встроенными виджетами, так сказать показывл бы заказчику  результаты именно работы логики приложения. А вот когда логика будет отточена можно взяться и за интерфейс приложения.


text:
Q: Complete a VBA Find Function to search for either one of two search varibles, then select the first one that comes up I currently have the following:
Set FindRow = ThisWorkbook.Sheets("Schedule").Range("n1:"& ActiveCell.Address).Find(What:="Assembly", SearchDirection:=xlPrevious, MatchCase:=False)

I would like to do the following
Set FindRow = ThisWorkbook.Sheets("Schedule").Range("n1:"& ActiveCell.Address).Find(What:="Assembly" or "Component", SearchDirection:=xlPrevious, MatchCase:=False)

I would like it to search for either Assembly or Component and stop the search on whatever one comes first.
Thanks

A: Thee may be ton's of variations.
If you are starting at N1, then you could use the entire column.
Evaluate("MIN(MATCH(""Assembly"",N:N,0),MATCH(""Component"",N:N,0))")
combined in a vba
    Sub Button1_Click()
    s = "N" & Evaluate("MIN(MATCH(""Assembly"",N:N,0),MATCH(""Component"",N:N,0))")
    MsgBox s
    Range(s).Select
    End Sub


text:
Q: Dark theme / with hooks Hello I have a custom hook to define my theme
code:
export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? 'dark' : 'light');
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button onClick={toggleTheme}>a</button>

    </ThemeProvider>
  );

and here is my hook:
import { darkTheme, lightTheme } from '../themes/index';

function usePersistedState(key) {
  const [state, setState] = useState(() => {
    switch (key) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });
  console.log(state);
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(state.type));
  }, [key, state]);

  return [state, setState];
}

export default usePersistedState;

basically every time my state changes I save it to local storage, but for some reason it only works the first time
when I try to change my theme the second time I do not enter my switch
edit:

as i show in the gif the first time i get an object because i enter my switch, but when i try to change the theme i get only a text cuz i dont enter my switch

A: The argument you provide to useState will apply only on the first render.
On the next renders, what you provide to setState function will be applied (you provide 'light' or 'dark', so state value will be 'light' or 'dark')
For your use case, in which you want the switch case to run every state change, useReducer is a better option than useState (in my opinion).
import { useReducer } from 'react';
import { darkTheme, lightTheme } from '../themes/index';

function usePersistedState(key) {
  const [state, dispatch] = useReducer(reducer, null, getTheme(key)); // first argument is the reducer function. second argument is the initial state. third argument is an init function (for complex initialization)

  const reducer = (state, action) => { // this will run on every state change (on every dispatch call)
    return getTheme(action.type)();
  }

  const getTheme = (themeType) => () => {
    switch (themeType) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  }

  console.log(state);
  useEffect(() => {
    localStorage.setItem('themeType', JSON.stringify(state));
  }, [state]);

  return [state, dispatch];
}

export default usePersistedState;

And from your component you call dispatch like so:
export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? {type: 'dark'} : {type: 'light'});
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button onClick={toggleTheme}>a</button>

    </ThemeProvider>
  );

A: I think you forgot to add the object wrapper on the toogle with { type: ... }
const toggleTheme = () => {
    setTheme({type: theme.type === 'light' ? 'dark' : 'light'});
};


text:
Q: show category id in list tree http://i.imgur.com/bEe8dD2.png
Is there an extension that will display the category id next to the name of categories? It would be handy to know the id without having to click on various categories first.
For instance, you may have some static blocks on your site rotating products of various categories. You may want to copy that block to a new location and display different products instead. Personally I don't have any of my category ids memorized so simply being able to know what they are without having to do much digging will be helpful.

A: This is a quick and dirty solution without a module, but should work fine even in  future updates

*

*Find the file
app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php'
and copy it to
app/code/local/Mage/Adminhtml/Block/Catalog/Category/Tree.php

*In this new file, around line 275 you will find a function named buildNodeName
Replace:
$result = $this->escapeHtml($node->getName());

With:
$result = '[' . $node->getId() . '] ';
$result .= $this->escapeHtml($node->getName());

You may need to clear the cache and recompile.


text:
Q: Oracle: search though all stored procs/triggers/other db code? Is it possible to search through all of the programmatic objects (functions, stored procedures, triggers, etc) across multiple schemas in Oracle?
There are a number of tables that appear to be unused in my code, but I don't want to break anything by removing them without checking first.

A: You can search the DBA_SOURCE view:
SELECT *
  FROM dba_source
 WHERE UPPER(text) LIKE '%YOUR_TABLE_NAME%';

A: Do this in Toad by selecting:
Search  =>  Object Search

A: It is possible to search through object code-- you'd generally use the DBMS_METADATA package to generate the DDL for the object and then search the CLOB.  However, it doesn't sound like that's actually what you want to do.
If you are just trying to figure out whether a table is referenced by any code in your system, you would generally want to use the DBA_DEPENDENCIES view (or ALL_DEPENDENCIES or USER_DEPENDENCIES depending on your privileges and the scope of what you're looking for).  Something like
SELECT *
  FROM dba_dependencies
 WHERE referenced_owner = 'SCOTT'
   AND referenced_name  = 'EMP'
   AND referenced_type  = 'TABLE'

will show you everything that depends on the EMP table in the SCOTT schema.
The only time you'd want to search code rather than looking at DBA_DEPENDENCIES would be when you had code that was doing dynamic SQL where the table name was hard-coded.  But that's relatively unlikely in practice.

A: If you had Toad you could do this built-in.  (I removed my schemas for privacy)


text:
Q: My /boot/efi is not pointing to the right ESP partition I have a computer with 2 storage devices.
I would like to have Windows on one and Linux on the other.
For a variety of reasons, I want them as separate as possible.
I'm using UEFI.
I installed Kubuntu on one device, during the setup, I specified it should be used for the bootloader installation.
But it turns out it has not been. Boot loader has been written to another device.
I've mounted the ESP partition from the other device, copied its content to the ESP partition of the device Kubuntu is installed on, rebooted, in the firmware boot manager, I chose to boot from it, it worked.
Now using mount, I see the /boot/efi is still pointing to the ESP partition on the other device.
I looked at /etc/fstab, it's got one line for /boot/efi, which indicates UUID=931B-CB7F . This UUID doesn't match any of the 2 ESP partition GUID, nor anything returned by blkid.
How can I have /boot/efi point to the ESP partition on the same device as KUbuntu is installed on?
fstab:
/dev/mapper/vg0-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/nvme1n1p1 during installation UUID=df5a10ea-a128-4c35-82f6-207493d101da /boot           ext4    defaults        0       2
# /boot/efi was on /dev/nvme0n1p2 during installation
#UUID=931B-CB7F  /boot/efi       vfat    umask=0077      0       1

/dev/mapper/vg0-home /home           ext4    defaults        0       2

/dev/mapper/vg0-swap none            swap    sw              0       0

lsblk -f | grep -v loop:
NAME                FSTYPE      FSVER    LABEL UUID                                   FSAVAIL FSUSE% MOUNTPOINTS
sda
nvme0n1
├─nvme0n1p1
└─nvme0n1p2         ntfs                       0E68C51168C4F88B                        877.3G     6% /media/xlp-admin/0E68C51168C4F88B
nvme1n1
├─nvme1n1p1         ext4        1.0            df5a10ea-a128-4c35-82f6-207493d101da      1.5G    13% /boot
├─nvme1n1p2         vfat        FAT32          423D-2695
└─nvme1n1p3         crypto_LUKS 2              1fc50d65-62f7-4513-bbf8-0002ae52b6b2
  └─nvme1n1p3_crypt LVM2_member LVM2 001       GNoW1G-nfU6-2yuG-MH2O-QGiC-0wmE-ONHQv8
    ├─vg0-swap      swap        1              6dfe2158-b779-47b6-83c3-cc2df4474ec0                  [SWAP]
    ├─vg0-root      ext4        1.0            b937a6a3-c62d-445a-9709-348a27a79b57     36.1G    21% /
    └─vg0-home      ext4        1.0            d86b3683-d330-4eaf-a278-d82c34a3685f    849.7G     0% /home

In the meantime, I have installed Windows on the other device. Windows decided to put its bootloader on the Linux device, and while at it, removed the Linux bootloader. I had made a copy before and restored it.
But in the process, Windows having failed to install on the other device ESP, I removed it hoping Windows would just create another on the same device.
That lead to Linux not booting anymore, so I commented it out in fstab.

A: Seems you have somehow destroyed the ESP on nvme0n1 (your Windows drive),I see only an unformatted empty partition nvme0n1p1. Now you have only the ESP on nvme1n1( your linux drive) which is nvme1n1p2.
Since you can still boot into your installation, you just need to change the UUID in /etc/fstab to the one of nvme1n1p2 in the lsblk-output. Then run sudo mount -a and sudo grub-install to make sure grub is completely installed in this partition.
When a system update delivers a new version of grub, you need the partition mounted, otherwise the upgrade will fail.
I cannot help you with the Windows part. Of course, you can use GParted to make this empty partition nvme0n1p1 a valid ESP, but then you still had to install Windows bootloader there, but that's a Windows thing and out of scope here. This link might be helpful.


text:
Q: How to send oauth2 tokens to client and store them? I have an app where I want to sign in with a 3rd party API (such as Google, Facebook, etc.). The client side front end is just a JavaScript SPA that will interact with my server. The server essentially is only needed to store the 3rd party ClientID and ClientSecret.
To login, the client will link the user to MyAPI/login. MyAPI will then redirect the user to the 3rd party login page, along with the ClientID. Upon authentication, the 3rd party will redirect the user back to MyAPI/callback with a code query parameter. MyAPI will send this code back to the 3rd party API along with ClientID and ClientSecret. The 3rd party API will finally return an access_token and refresh_token.
My question is how I should then send the tokens back to the client application? And, once the client has the tokens, how should I store them?

A: What you are describing is the Authorization Code Grant flow of OAuth.  In Auth Code flow, a code is provided to the client (in this case, MyAPI) so that the user never receives the access_token or refresh_token and thus doesn't have to be trusted with them.
By providing these tokens to the user and allowing them to store it in local storage, you are circumventing the security benefit of Auth Code flow.  It is definitely not recommended to do this unless security isn't as big of an issue for you (you trust the user).
As the comments suggest, you can use cookies to persist a session with MyAPI.  Still, the access_token and refresh_token should be kept in the session data and not shared directly with the user.  This enforces that access to the 3rd party API is only made by MyAPI on behalf of the user.
A better explanation of Auth Code flow is provided in the accepted answer to this question: What is the difference between the 2 workflows? When to use Authorization Code flow?
An incomplete Express.js example of MyAPI:
// imports
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const jwt = require('jsonwebtoken');

// setup passport (an authentication middleware) and use it with the session provided by express-session
passport.serializeUser((user, done) => {
  done(null, user);
});
passport.deserializeUser((obj, done) => {
  done(null, obj);
});
passport.use(new SomeStrategy(...strategyOptions));
const app = express();
app.use(passport.initialize());
app.use(passport.session());

// route handlers
app.get('/login', passport.authenticate('SOME_STRATEGY'), () => {});
app.get('/callback', passport.authenticate('SOME_STRATEGY'), { failureRedirect: '/badlogin' }, (req, res) => res.send(200));
app.get('/resource', (req, res) => {
  const accessToken = req.user.access_token; // req.user has the session information including the access token
  try {
    // verify the access token with the 3rd party auth's public key (NOT THE SAME AS DECODING IT!)
    const decodedAccessToken = jwt.verify(accessToken, thirdPartAuthPublicKey);
    return res.send(200).send(decodedAccessToken);
  } catch (err) {
    return res.send(401).send('unauthenticated');
  }
});

Here, the server keeps the access_token in the user's session data (req.user).  When the user makes a request for the resource, the server tries to verify the access_token and returns its decoded contents.


text:
Q: jquery div on top of another div I have a web page that contains a div element called #order_details that is hidden.  When a user clicks on a button, then the #order_details div element appears.  It appears that the div element has a z-index of 6500 which I have verified is the highest z-index in the entire site.  It is also using jQuery because I see code like:
$('#order_details').show();

which I know shows the #order_details div element.

    ...
    ...

Now I've added a new div element called #survey and when I click on a button in the #order_details div I want the survey to appear on the top.
I have set the z-index in the css #survey to be 6599.  Then I setup some jQuery to show the div.
$('#survey').show();

the #survey div appears, but it is not on top of the #order_details div.
My question is:
Isn't setting the z-index property of #survey to a higher value supposed to ensure that the #survey div will appear at the top?
Any help would be greatly appreciated...

A: Make sure you #survey has a positioning on relative, absolute or fixed. W3 spec


text:
Q: Find common sequence of elements in list of lists I have list of lists containing Id's as following-
[[45, 41, 20, 25, 78],
 [54, 12, 45, 36, 59],
 [45, 12, 45, 41, 88],
 [74, 85, 41, 20, 25],
 [54, 45, 36, 59],
 [74, 20, 25]]

Problem 1: I need all the  lists having same prefix(list starting with same number) in one list.
Desired output
[[45, 41, 20, 25, 78],
 [45, 12, 45, 41, 88]]
[[54, 12, 45, 36, 59],
 [54, 45, 36, 59]]
[[74, 85, 41, 20, 25],
 [74, 20, 25]]

Problem 2: Later find the common elements in respective sub-lists. For example:
   [[45, 41, 20, 25, 78],
   [45, 12, 45, 41, 88]]

In this list common elements are [45,41]
Final desired output:
[[45, 41],
 [54, 45, 36, 59],
 [74, 20, 25]]

A: You can use itertools.groupby For Problem 1:
from itertools import groupby

orig_list = [[45, 41, 20, 25, 78],
 [54, 12, 45, 36, 59],
 [45, 12, 45, 41, 88],
 [74, 85, 41, 20, 25],
 [54, 45, 36, 59],
 [74, 20, 25]]
sorted_list = sorted(orig_list, key=lambda l: l[0])
list1 = [list(g) for _, g in groupby(sorted_list, lambda l:l [0])]

Output:
[[[45, 41, 20, 25, 78], [45, 12, 45, 41, 88]],
 [[54, 12, 45, 36, 59], [54, 45, 36, 59]],
 [[74, 85, 41, 20, 25], [74, 20, 25]]]

For Problem 2, you could use set intersection; however, it won't preserve order:
[list(set.intersection(*[set(s) for s in sublists])) for sublists in list1]

Output:
[[41, 45], [59, 36, 45, 54], [25, 74, 20]]

If you want to preserve order and there are always 2 sublists, you could try this:
[[x for x in sublist[0] if x in sublist[1]] for sublist in list1]

Output:
[[45, 41], [54, 45, 36, 59], [74, 20, 25]]

If it's possible to have other number of sublists (more than 2 or only 1), you can tweak it like this:
[[x for x in sublist[0] if all([x in s for s in sublist[1:]])] for sublist in pre_list]

A: I think this is your solution
list1 = [[45, 41, 20, 25, 78],[54, 12, 45, 36, 59],[45, 12, 45, 41, 88],[74, 85, 41, 20, 25],[54, 45, 36, 59],[74, 20, 25]]
converted_list = []
i=0
while i <= (len(list1)/2)+1:
    a = list1.pop(0)
    print(a)
    for j in list1:
        if j[0]==a[0]:
            b = list1.pop(list1.index(j))
            converted_list.append([a,b])
            break
    i+=1
print(converted_list)

final_list = []
for i in converted_list:
    common_list = []
    for j in i[0]:
        if j in i[1]:
            common_list.append(j)
    final_list.append(common_list)
print(final_list)


text:
Q: C# stop on error line within try catch If I run the code below that calls Test1(), VS2012 will break nicely at that line and show me exactly what's going on. If I comment out Test1 and put in Test2, then the try catch does not stop on the line, it just logs it out to the console.
How can I get VS2012 to stop on the error line, even when it is surrounded by a try catch statement?
private void Button_Click(object sender, RoutedEventArgs e)
{
  //Test1(); // No try catch - stops on error line dividing by zero.
  Test2(); // Try catch - Just writes out to console.
}

private void MakeError()
{
  int i = -1;
  i += 1;
  int j = 1 / i;
  Console.WriteLine(j.ToString());
}

void Test1()
{
  Console.WriteLine("MakeError in Test1");

  MakeError();
}

void Test2()
{
  Console.WriteLine("MakeError in Test2");
  try
  {
    MakeError();
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.Message);
  }
}

A: While the other answers are correct, this is the intentional behavior by default, you can tell Visual Studio to alert you to those exceptions if you wish.
How to: Break When an Exception is Thrown:
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.
-or-
Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.

A: What you want is Visual Studio break execution when an exception is thrown:
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example (your case), Common Language Runtime Exceptions.
MSDN Reference.

A: Visual Studio will only intervene when there is an unhandled exception , in this case a division by 0. The try...catch handled the exception. Since there is no exception left unhandled, Visual Studio will not jump out.

A: try and catch statements are intended so that the flow of execution can still happen, even when an exception occurs. The debugger only stops when the exception is unhandled, which the try catch does.
This is intentional.


text:
Q: Custom react hook library. Webpack externals and peerDependencies doesn't work Each new try I getting 2 cases:
"Invalid hook call" - because of double React environment.
"Can't resolve "react"" - if I would remove it from devDependencies in hook library.
Goal is : to set up correct build environment of hook library.
webpack.config.js
const path = require("path")

module.exports = {
    mode: "production",
    entry: "./src/index.ts",
    output: {
        filename: "index.js",
        path: path.resolve(__dirname, 'dist'),
        clean: true,
        library: "custom-hook-lib",
        libraryTarget: "umd"
    },
    externals: {
        'react': 'react',
        'react-dom' : 'reactDOM'
    },

    resolve: {
        extensions: [".js", ".jsx", ".json", ".ts", ".tsx"]
    },

    module: {
        rules: [
            {
                test: /\.(j|t)sx?$/,
                exclude: /(node_modules)/,
                use: 'ts-loader'
            }
        ]
    }

}

package.json
{
  "name": "custom-hook-lib",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "module": "dist/index.js",
  "files": [
    "dist"
  ],
  "keywords": [],
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "@types/react": "^18.0.17",
    "typescript": "^4.8.2",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "ts-loader": "^9.3.1"
  }
}

A: After a few days of investigation I can answer:
There is wasn't building issue. I tried tsc, rollup, webpack. I tried to steal already working libs build configuration. Tried create-react-library. And after that I just get know from this Video, that for the testing you can't use npm/yarn link or just local path if there is hook in your project
You should build and publish your React library that's using hooks to test.

A: Do you really need a webpack to bundle your library? As your app will bundle it anyway.
I saw some hook libs use just 'tsc' command as npm build. In that case you app will supply only source code without bundeled deps. Also there will not be react in inner node_modules in hook folder as your react in devDeps and therefore you hook will supply react of your app node_modules.
Now (according the error) it seems that react is still in output bundle of hook lib.


text:
Q: NSIS conditional statement I am writing a script code which installs 3 drivers. Every time that a driver is installed I get a return code of '256' or '1' if the installation was successful, or a different return code if the installation failed. I need to check that all installations finished sucessfully, so I use the following code:

${If} "$2" == "1"
${OrIf} "$1" == "256"
${AndIf} "$2" == "256"
${OrIf} "$2" == "1"
${AndIf} "$3" == "256"
${OrIf} "$3" == "1"
    MessageBox MB_OK "Installation was successful!"
${Else}
    MessageBox MB_OK "Sorry, an error occurred during installation."
${EndIf}

Even if a driver installation fails I receive the message "Installation was successful!". Could someone help me  find the mistake in the above code?

A: In your example code the first ${If} is using $2 when it should probably check $1.
I don't think you should use OrIf and AndIf in the same if block like this, the results are probably undefined.
It is also possible to write your own custom LogicLib operators:
!include LogicLib.nsh
!macro _MyCheckExitcodeSuccess _a _b _t _f
    !if `${_f}` == ``
        !undef _f
        !define _f +2
    !endif
    IntCmp ${_b} 1 +2
    IntCmp ${_b} 256 `${_t}` `${_f}` `${_f}`
    !if `${_t}` != ``
        Goto `${_t}`
    !endif
!macroend
!define MyCheckExitcodeSuccess `"" MyCheckExitcodeSuccess`

StrCpy $1 1
StrCpy $2 256
${If} ${MyCheckExitcodeSuccess} $1
${AndIf} ${MyCheckExitcodeSuccess} $2
    MessageBox mb_ok "All OK"
${Else}
    MessageBox mb_ok "Something failed"
${EndIf}

A: A slightly slimpler way would be to do something like
; 1_256_1_256 is defined if we are good
!define $1_256_$2_256
!define $1_256_1_$2
!define 1_$1_1_$2
!define 1_$1_$2_256

!ifdef 1_256_1_256
   message mb_ok "All good"
!else
   message mb_ok "Failure detected"
!endif


text:
Q: JavaScript: Parse through odd string to get necessary information (RegEx) I am attempting to parse through an oddly formatted string which stores some data necessary for an audio player which I'm building.  An example would be:
"a:14:{s:10:"dataformat";s:3:"mp3";s:8:"channels";i:2;s:11:"sample_rate";i:44100;s:7:"bitrate";i:192000;s:11:"channelmode";s:12:"joint stereo";s:12:"bitrate_mode";s:3:"cbr";s:8:"lossless";b:0;s:15:"encoder_options";s:6:"CBR192";s:17:"compression_ratio";d:0.1360544217687074952660708504481590352952480316162109375;s:10:"fileformat";s:3:"mp3";s:8:"filesize";i:7249920;s:9:"mime_type";s:10:"audio/mpeg";s:6:"length";i:302;s:16:"length_formatted";s:4:"5:02";}"

It's super ugly.  For each song that I interface with it would include the type of information provided above.  Essentially all I want is the value of "length_formatted" which is "5:02".  I'm assuming I need to use regular expressions to accomplish this, but since don't have any experience with it I'm not sure where to start.

A: Try this code:

string = `"a:14:{s:10:"dataformat";s:3:"mp3";s:8:"channels";i:2;s:11:"sample_rate";i:44100;s:7:"bitrate";i:192000;s:11:"channelmode";s:12:"joint stereo";s:12:"bitrate_mode";s:3:"cbr";s:8:"lossless";b:0;s:15:"encoder_options";s:6:"CBR192";s:17:"compression_ratio";d:0.1360544217687074952660708504481590352952480316162109375;s:10:"fileformat";s:3:"mp3";s:8:"filesize";i:7249920;s:9:"mime_type";s:10:"audio/mpeg";s:6:"length";i:302;s:16:"length_formatted";s:4:"5:02";}"`

document.body.innerHTML = string.match(/length_formatted.*?(\d+:\d+)/)[1]

Explaining the regex:
/length_formatted.*?(\d+:\d+)/

length_formatted          // match the literal text
.*?                       // till the next ocurrence of
(                         // group in [1]
    \d+                       // at least one digit
    :                         // literal ':'
    \d+                       // at least one digit
)                         // end of captouring group

Hope it helps.

A:

var s = '"a:14:{s:10:"dataformat";s:3:"mp3";s:8:"channels";i:2;s:11:"sample_rate";i:44100;s:7:"bitrate";i:192000;s:11:"channelmode";s:12:"joint stereo";s:12:"bitrate_mode";s:3:"cbr";s:8:"lossless";b:0;s:15:"encoder_options";s:6:"CBR192";s:17:"compression_ratio";d:0.1360544217687074952660708504481590352952480316162109375;s:10:"fileformat";s:3:"mp3";s:8:"filesize";i:7249920;s:9:"mime_type";s:10:"audio/mpeg";s:6:"length";i:302;s:16:"length_formatted";s:4:"5:02";}"';

var x = s.split('length_formatted";s:')[1].split('"')[1];

alert(x);

Find 'length_formatted";s:' this string and split it now take the last part and split it by " and from the result take the middle part!

A: You could do something like this:
var lengthFormatted = string.match(/length_formatted"[^"]*"([^"]*)"/).pop(); // => 5:02

This assumes that this:
"length_formatted";s:4:"5:02"

could also be something like this:
"length_formatted";all_kinds_of_random_stuff_h3r3;;;;"5:02"

A: This works. This assumes that s:14 will always be the length. I split the junk on a ; then see if i had a match to s:4 and recorded the index. then extracted the text.
 $(document).ready(function () {

    //var cow =  'Check out this image  and one with a width ';
    var yourString = 'a:14:{s:10:"dataformat";s:3:"mp3";s:8:"channels";i:2;s:11:"sample_rate";i:44100;s:7:"bitrate";i:192000;s:11:"channelmode";s:12:"joint stereo";s:12:"bitrate_mode";s:3:"cbr";s:8:"lossless";b:0;s:15:"encoder_options";s:6:"CBR192";s:17:"compression_ratio";d:0.1360544217687074952660708504481590352952480316162109375;s:10:"fileformat";s:3:"mp3";s:8:"filesize";i:7249920;s:9:"mime_type";s:10:"audio/mpeg";s:6:"length";i:302;s:16:"length_formatted";s:4:"5:02";}"';

    var eachPart = yourString.split(";");

    var re = /s:4/i;
    var count = 0;
    for(var i = 0; i < eachPart.length; i++) {
        console.log(eachPart[i]);
        var found = eachPart[i].match(re);
        if(found)
            count = i;
    }

    re = /".*?"/;

    var yourLength = extractText(eachPart[count]);
    console.log(yourLength);

});

function extractText( str ){
    var ret = "";

    if ( /"/.test( str ) ){
        ret = str.match( /"(.*?)"/ )[1];
    } else {
        ret = str;
    }

    return ret;
}


text:
Q: Rails Console Complex queries I would like to post a subcategory using subsequent query like this:
Gender.where(gender: 'Masc').categories.where(name: 'clothes').subcategories.create([{ name: 't-shirt' }])

but  show  this error!

rake aborted! NoMethodError: undefined method `subcategories' for
  Category

I searched but could not find out how to create a data using a chained query.
Gender Model:

class Gender < ActiveRecord::Base
  extend FriendlyId
  friendly_id :gender, use: [:slugged, :history]

  has_many :categories
  has_many :subcategories, through: :categories
  has_many :products
  accepts_nested_attributes_for :categories
  accepts_nested_attributes_for :products
  accepts_nested_attributes_for :subcategories
  attr_accessible :gender, :categories_attributes, :subcategories_attributes,

end

A: where(name: 'clothes') returns a query, not a model instance. Presumably you have a has_many :subcategories in your categories and category names are unique so you'd use find_by to find the clothes category and then call subcategories on that. Similarly for looking up the gender:
Gender.find_by(gender: 'Masc')  # This gives you a single Gender instance
      .categories
      .find_by(name: 'clothes') # and then a single Category here
      .subcategories
      .create(name: 't-shirt')


text:
Q: Flutter/Dart: Button onPressed() called but screen not redrawing? I am trying to have a button change its text when it is pressed. I have done so by using setState() to change the value of the string that is passed to the Text child of the button. The button I am trying to change the text of is forgotLabel - found in the code below.
I have tried using different button types such as FlatButton and RaisedButton and all of them resulted in the same issue: The button gets pressed, setState gets called and changes the value of the string that represents the text in the button (called forgotText in the code) but the button does not appear to visually change. Here is the code:
import 'package:flutter/material.dart';
import 'package:mobileapp/home_page.dart';

class LoginPage extends StatefulWidget {
  static String tag = 'login-page';
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {
final bgGrey = Color(0xFF1c232c);

//Company logo at top
final logo = Hero(
  tag: 'hero',
  child: CircleAvatar(
    backgroundColor: Colors.transparent,
    radius:68.0,
    child: Image.asset('assets/logo_transparent.png'),
  ),
);

//Email field
final email = TextFormField(
  keyboardType: TextInputType.emailAddress,
  autofocus: false,
  initialValue: 'jonDoe@domain.com',  //remove later
  style: TextStyle(color: Colors.white70),
  decoration: InputDecoration(
    hintText: 'Email',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(32.0),
      borderSide: BorderSide(color: Colors.white)
      )
  ),
);

//Password field
final password = TextFormField(
  autofocus: false,
  initialValue: 'verysafePassword',   //remove later
  obscureText: true,
  style: TextStyle(color: Colors.white70),
  decoration: InputDecoration(
    hintText: 'Password',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(32.0),
      borderSide: BorderSide(color: Colors.white)
      )
  ),
);

// Login button
final loginButton = Padding(
  padding: EdgeInsets.symmetric(vertical: 20.0),
  child: Material(
    borderRadius: BorderRadius.circular(30.0),
    color: Colors.deepOrangeAccent,
    shadowColor: Colors.deepOrange[300],
    elevation: 5.0,
    child: MaterialButton(
      minWidth: 200.0,
      height: 30.0,
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => HomePage()),
        );
      },
      child: Text('Login', style: TextStyle(color: Colors.white70),),
    ),
  )
);

String forgotText = "Forgot Password";
void changeText() {
   setState(() =>forgotText = "Please use the web app to reset your password.");
}

// Forgot password button
final forgotLabel = MaterialButton(
  child: Text(
    forgotText,
    style: TextStyle(color: Colors.white70),
  ),
  onPressed: changeText,
);

//Layout settings for each widget made
//Contains: logo, email, password, loginButton and forgotLabel
return Scaffold(
  backgroundColor: bgGrey,    //defined under method declaration
  body: Center(
    child: ListView(
      shrinkWrap: true,
      padding: EdgeInsets.only(left: 24.0, right: 24.0),
      children: <Widget>[
        logo,
        SizedBox(height: 48.0),
        email,
        SizedBox(height: 8.0),
        password,
        SizedBox(height: 25.0),
        loginButton,
        forgotLabel
      ],
    ),
  ),
);
}
}

A: The problem is forgotText was changed when calling setState but because it's defined as a local variable inside build(), it gets initialised to Forgot Password again. Make it an instance variable of _LoginPageState.


text:
Q: Is there a way to fill an edge detected image with corresponding colors according to original image? I am trying to solve an image processing problem.
Here is the input image (figure_1) consists of 3 different colors. the original image has no red or blue which is appended to indicate areas that need to be processed later.

Applying edge detection on figure_1 gets an output image, on which there is only edges and no colors.
here is the code
cv2.namedWindow('Result')
img = cv2.imread('img.png')
v1 = 20
v2 = 20
edges = cv2.Canny(img,v1,v2)
edges = cv2.cvtColor(edges,cv2.COLOR_GRAY2BGR)
res = np.hstack((img,edges))
edges = cv2.Canny(img,v1,v2)
edges = cv2.cvtColor(edges,cv2.COLOR_GRAY2BGR)
res = np.hstack((img,edges))
cv2.imshow('Result',res)
cv2.waitKey()
cv2.destroyAllWindows()

Here is the output image (figure_2), without filling with red or blue, which is the problem needed.

is there a way to fill the figure_2 with corresponding colors (red and blue) according to original image (figure_1) in python?
this piece of code gets me the edge, how can I get the area_red and area_blue separately, so that I can plot different color respectively?
here is the final goal of this task, transfer original raster image (figure_1) to a vector image and filled with lines in corresponding color.

A: You can try paint the first image in blue and red, then you'll get a image 3 which you can mix with image 2


text:
Q: Maximize the difference of two linear expressions Given two $1\times N$ complex vectors h and g. I want to find a $N\times 1$ complex vector w(normalized to unit norm $ \Vert w \Vert^2=1$), which maximizes the following expression:
$$w_0=\arg\max_w \left| hw \right|^2-\left| gw \right|^2$$
Because that w can represent a direction, I have tried some geometric methods. But what is the geometric meaning of   $\left| hw \right|^2$?
Both of the algebraic and geometric methods are appreciated.

A: This method is called Lagrange Multipliers.  Start with $F(\vec{w})=|\vec{h}.\vec{w}|^2-|\vec{g}.\vec{w}|^2+\lambda(\vec{w}.\vec{w}-1)$ and differentiate with respect to $w_i$ and $\lambda$.
$$\frac{dF}{dw_i}=2h_i(h.w)-2g_i(g.w)+2\lambda w_i=0$$
That shows that $w$ is a linear combination of $g$ and $h$.  So start again with
$$w=xh+yg\\
h.h=A,h.g=B,g.g=C\\
\text{Maximize }(Ax+By)^2-(Bx+Cy)^2+\lambda(Ax^2+2Bxy+Cy^2-1)\\
A(Ax+By)-B(Bx+Cy)+\lambda(2Ax+2By)=0\\
B(Ax+By)-C(Bx+Cy)+\lambda(2Bx+2Cy)=0$$
The last two lines each give $x/y$ as a function of $A,B,C,\lambda$.  Then $\lambda$ must be the only value that gives the same $x/y$ each time.
That gives $x/y$.  Combine that with $Ax^2+2Bxy+Cy^2=1$ to get a quadratic in $x$.  One root of the quadratic gives a maximum, the other gives a minimum.

A: The problem: Maximize $|hw|^2 - |gw|^2$ subject to $|w|^2 = 1$
We have $|hw|^2 - |gw|^2 = w^T (h^Th - g^Tg) w$.
This is a standard setup, and is maximized when $w$ is an eigenvector of $h^Th-g^Tg$ with the largest eigenvalue.

Here it is as a lagrange multiplier problem for fun:
Let $f(w,\lambda) = |hw|^2 - |gw|^2 - \lambda (|w|^2 - 1)$ and set partial derivatives with respect to $w$ and $\lambda$ to zero:
$\left<w,w\right> = 1$
$2\left<h,w\right>h - 2\left<g,w\right>g - 2 \lambda w = 0$
The second equation is equivalent to:
$(h^T h - g^T g) w = \lambda w$
So $w$ is an eigenvector of $h^Th-g^Tg$.
(Now by the formula in the second line at the top, it's easy to see it must be the one with the largest eigenvalue.)


text:
Q: move time consuming operations out of page load I have a aspx page in which i create reports and charts on the fly. Creation of these charts and reports takes a lot of time because of which a blank screen is shown to the user until the creation completes.
Can you suggest ways by which i can unlink actual report and chart creation code from page load so that i can show a processing text and then show the generated chart or report once it is ready.
EDIT :-
I would want to do something like this -
on first request trigger the report or chart creation and register a call back for completion. the client can then poll the server every 2-3 seconds to check if the report creaetion is complete. I need help from you on how exactly i can implement this or if you can think of something better.
Please do let me know if the question is not clear enough.

A: It doesn't matter whether your code is in Page_Load or in any other event that fires during the page life cycle.  You probably want an Ajax type approach for your charting.  I don't know exactly what you're doing, but I've used SSRS ReportViewer control with great success.

A: A quick solution is to move the logic out of Page_Load and into it's own function.  Add an <asp:UpdatePanel> to where you want the chart to be displayed and add an <asp:Timer> control to your page.  For the timer's On_Tick event, call the code that generates and displays the chart, disable the timer (so it doesn't tick again) and call Update() on your UpdatePanel.
This will cause the page to load with the basic output, then the timer will kick off an AJAX call to generate and display your charts.  It's not the most elegant solutions, but it's probably the quickest to implement.


text:
Q: Showing that $7+\sqrt[3]{2}$ is an algebraic number How do I go about showing that $7+\sqrt[3]{2}$ is an algebraic number?
I need to show that it is the root of an integer valued formal polynomial?
How do I solve these problems in general? I haven't a clue where to start on this one, so it is hard to give context.
The problem is perhaps solved using methods of ring theory.

A: The other responses are great (+1), but what if you had been given a more complicated number like $\sqrt{3} + \sqrt[4]{5} + \sqrt[3]{17} + 1/\sqrt{2}$?  Indeed, it'd be nigh-impossible to find a polynomial with this number as a root!
Well, the set of all algebraic numbers is a field, and as such, with a more complicated number as above, it would suffice to show that $\sqrt{3}$, $\sqrt[4]{5}$, $\sqrt[3]{17}$, and $\sqrt{2}$ are all algebraic.  Then you can apply the field axioms to conclude that the number in question is algebraic.
You could apply this approach to your problem, since it is fairly obvious that $7$ and $\sqrt[3]{2}$ are algebraic.  But of course, as the other responses have shown, it is also fairly easy to prove it directly by constructing a polynomial for which $7+\sqrt[3]{2}$ is a root.

Footnotes:
You can prove that the algebraic numbers form a field in a few different ways.

*

*One way is to follow Ragib's approach in his answer here, where he is applying the fact that every element of an extension of a field $F$ of finite degree is algebraic over $F$.  This approach is perhaps most accessible to a beginner.

*In greater generality, Zorn's lemma can be used to show that every field $F$ has what is called an algebraic closure, which is an algebraically closed extension field of $F$ whose elements are all algebraic over $F$.  See here for a proof.

A: I'd like to strike a middle ground between these excellent answers. I shall use two results without proof. You might try to see if you can prove these, yourself.

*

*If $R$ is an extension ring of a field $F$, then $R$ is a vector space over $F$.

*If $u$ is algebraic over a field $F$, then $F[u]$ is a finite-dimensional vector space over $F$.
(Hint: suppose $p(x)\neq 0 \in F[x]$ is such that $p(u) = 0$. Show that if $m = \text{deg }p$, that $\{1,u,u^2,\dots,u^m\}$ is linearly dependent over $F$. Why is this enough?)
Now clearly $\Bbb Q$ is a field, and $\sqrt[3]{2}$ is algebraic over $\Bbb Q$ (it is a root of $p(x) = x^3 - 2 \in \Bbb Q[x]$), and we have $7 + \sqrt[3]{2} \in \Bbb Q[\sqrt[3]{2}]$. Hence if $\dim_{\Bbb Q}(\Bbb Q[\sqrt[3]{2}]) = k$, we have that:
$\{1, 7 + \sqrt[3]{2},(7 + \sqrt[3]{2})^2,\dots,(7 + \sqrt[3]{2})^k\}$ must be a $\Bbb Q$-linearly dependent set, that is, there exist:
$c_0,c_1,\dots,c_k \in \Bbb Q$ not all $0$ such that:
$c_0 + c_1(7 + \sqrt[3]{2}) + c_2(7 + \sqrt[3]{2})^2 + \cdots + c_k(7 + \sqrt[3]{2})^k = 0$.
So, if $q(x) = c_0 + c_1x + c_2x^2 + \cdots + c_kx^k$, evidently $q(7 + \sqrt[3]{2}) = 0$, so $7 + \sqrt[3]{2}$ is algebraic.
(Note that this "miraculously" produces our desired result, without actually finding the polynomial we want).

A: Well if you manage to find a polynomial with that as its root, then it is an algebraic number. The most obvious choice would be its minimal polynomial.
$x=7+\sqrt[3]{2}$
$(x-7)^3=2$
Expand that and move all terms to one side, and there's your polynomial.
I would also like to add that not all problems are this trivial. For example, showing that $\sqrt{2}+\sqrt{3}$ requires a little more work. Even worse is something like $\cos \left ( k \pi \right )$ where $k\in\mathbb{Q}$

A: So, first you write down the silliest thing: your number is a solution of
$$ x = 7 + \sqrt[3]{2} $$
(Always do the silliest thing first.)  Well, you say, that's not a polynomial with integer coefficients.  The constant term has that $\sqrt[3]{2}$ in it, not an integer at all.  So you want to get rid of that $\sqrt[3]{2}$.  I know, you think, I'll cube everything!  That'll get rid of that nasty $\sqrt[3]{2}$!
$$ x^3 = (7 + \sqrt[3]{2})^3 = 7^3 + 3\cdot49\sqrt[3]{2} + 3\cdot7\cdot\sqrt[3]{4} + 2 $$
Alas, now there are even more $\sqrt[3]{\cdot}$ than when we started.  What went wrong?  The 7 interfered, created all those cross terms.  We should cube the $\sqrt[3]{2}$ without interference.  So, move everything to the other side, where it won't get in the way.
$$ x - 7 = \sqrt[3]{2} $$
Then cube.
$$ (x-7)^3 = 2 $$
All integers now, hurrah.


text:
Q: How to improve ASP.NET MVC3 app data query performance? There is a book management system web application based on ASP.NET MVC3. When click the book index page, data query is very slow and user has to wait for several seconds for response. The code of Action Index in BookController below:
    public ViewResult Index(string sortOrder, int? page)
    {
        ViewBag.NameSortParam = string.IsNullOrEmpty(sortOrder) ? "desc" : "";
        ViewBag.CurrentSort = sortOrder;

        BookModel books = from b in db.Books select b; // db = new BookContext();
        switch (sortOrder) {
            case "desc":
                books = books.OrderByDescending(b => b.Name);
                break;
            default:
                books = books.OrderBy(b => b.Name);
                break;
        }
        int pageSize = 15;
        int pageNumber = (page ?? 1);

        return View(books.ToPagedList(pageNumber, pageSize));
    }

In my opinion, the main reason of slow is that server does not response to client until all data are ready. This process takes much time.
I do not know how to solve this problem, is there any method to improve data query performance in this case? Thank you!
update:
backend database is SQL Server Compact Edition 4.0
UPDATE
I update my logic code below, orderby is used before skip and take statements. Everything goes well. Thank you all for help.
books = (from b in db.Books
                       orderby b.Name descending
                       select b)
                       .Skip((page - 1) * pageSize)
                       .Take(pageSize)
                       .ToList();

A: You are loading in all your books before filtering the dataset to just the data you need (by using ToPagedList). Change your query and use the Skip and Take methods instead of ToPagedList.

A: Put index on the Books.Name column (with included columns: include those which are needed in your list), on the C# side query only the filed you are needed:
books.Select(x => new {
                       x.Name,
                       x.Author,
                       x.Description,
                       x.ID }).ToPagedList(/*....*/)./*...*/)

And i would look after the ToPagedList implementation.

A: Use OutputCaching on the method, varying by the two parameters. An overview of this is detailed here.
[OutputCache(Duration=60,VaryByParam="sortOrder;page;")]
public ViewResult Index(string sortOrder, int? page)


text:
Q: A malicious threat was detected in Media Player Classic exe file When I run HitmanPro, it says that mpchc64.exe is a trojan. A virustotal analysis seems to show malicious flags triggered by several vendors.

What is going on? Why does a file by Media Player Classic team contain a trojan?

A: That is not the version of Media Player Classic installed on your computer, and indeed is a virus.  Why?
Look at the folder the executable with a virus was found in - a folder which appears to be for temporary or cached files used by Adobe Flash Player.  In terms of the actual virus, it appears to be a variant of Win32/BitCoinMiner.G, which is indeed a real virus (using your computer power to mine bitcoins).
Lastly, you should be aware that the Product/Publisher/Descriptions contained in a .EXE file are set when the application is compiled.  They are in no way "official" and can easily be spoofed.

If you're wondering how that file got on your computer, it could possibly have been a drive-by download.  Make sure all of your antivirus software is up to date, and if you use any third-party addons in your web browser (especially Java or Flash), make sure they are always up to date (or preferably, disabled!).

A: *

*The real MPC-HC doesn't get installed to Flash's cache folder, unless you somehow decided to place it there.

*The real file is called mpc-hc64.exe

*The real file is not a mere 129 KB in size (which obviously means it has a completely different SHA-256 hash).

*Finally, the real version obviously is not launched on startup by a hidden batch file, as you yourself seem to have discovered.
So what makes you assert that this really is "a file by Media Player Classic team"?

A: Friend, you may have installed a fake version. I would suggest re-downloading it from an official site, and removing the current files.
(Also, if your Anti-V has a boot scan option, run it. Those nasty bitcoins sometimes place themselves in a bunch of other locations.)


text:
Q: Javascript- How to make window.location to open selected values in a new page? I have applied your solution like below but still not working. Any ideas? Thank you
code
open_links()
{
var options = document.querySelectorAll('#dwl option');
for( var i = 0 ; i < options.length ; i++ )
window.open(options[i].value, '_blank');
}

**HTML**

Download a HTML sample

<select id="dwl">
<option value="http://www.bbc.co.uk/">Sample 1</option>
<option value="http://www.bbc.co.uk/">Sample 2</option>
<option value="http://www.bbc.co.uk/">Sample 3</option>
<option value="http://www.bbc.co.uk/">Sample 4</option>
<option value="http://www.bbc.co.uk/">Sample 5</option>
</select>
<input type="button" onclick="open_links()" value="Download" />

A: Use window.open(url, '_blank');, to open all the link you should loop through all the options of select with id dwl using, you can use document.querySelectorAll for this :
HTML :
<input type="button" onclick="open_links()" value="Download" />

JS :
open_links()
{
    var options = document.querySelectorAll('#dwl option');
    for( var i = 0 ; i < options.length ; i++ )
        window.open(options[i].value, '_blank');
}

Hope this helps.


text:
Q: Has Apple officially not allowed access to camera for app in background? Can I build an iOS app that uses the camera (even if it doesn't take pictures/video) while the app is in the background?
If not, why? Where has Apple come out with this information? I have seen similar questions and answers, but none with direct proof from Apple.
For example, if I wanted to make an app that, while in background, can keep track of how many trees our phone encounters through the day through object recognition software.

A: The camera stops functioning when app moves to background and I have found this apple doc that supports the claim. Hope this will help you.
AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableInBackground

Camera usage is prohibited while in the background. If you attempt to
  start running a camera while in the background, the capture session
  sends an AVCaptureSessionWasInterruptedNotification with this
  interruption reason. If you don't explicitly call the stopRunning
  method, your startRunning request is preserved, and when your app
  comes back to foreground, you receive
  AVCaptureSessionInterruptionEndedNotification and your session starts
  running.

A: No, as soon as your app enters the background (even the built-in camera app), the camera stops recording.
This is done primarily because the camera consumes a great deal of power and generates a lot of heat. If you were to record a 15 minute video with an iPhone, you will notice both pretty quickly.
Combine running CV software, and you will drain the battery of any device in short order.

A: It's good that apple doesn't allow because it increases risk of apps capturing your moments from background without making you notice. Thus risk to privacy.


text:
Q: Change a part of a SVG color on hover loaded using image tag I have a SVG image which has a background circle and an arrow and I use it in my application like this:
<def>
    //few other svgs with image tag will be loaded here
    <image id="svg_asset" x="0" y="0" width="160" height="160"
         xlink:href="public/assets/svgassets/next_page.svg" />
</def>

and my svg content:

<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><defs><style>.a{fill:#4772c0;}.b,.d{fill:#fff;}.c,.d{stroke:none;}</style></defs><g transform="translate(-1043 -166)"><circle class="a" cx="30" cy="30" r="30" transform="translate(1043 166)"/><g class="b" transform="translate(1052.198 169.665)"><path class="c" d="M 23.94279861450195 36.81674957275391 C 23.52678871154785 36.81674957275391 23.12740898132324 36.64649200439453 22.8182487487793 36.33732986450195 C 22.17817878723145 35.69723129272461 22.17817878723145 34.69441986083984 22.8182487487793 34.05432891845703 L 28.51812171936035 28.35429000854492 L 9.353948593139648 28.35429000854492 C 8.469528198242188 28.35429000854492 7.749998092651367 27.63474082946777 7.749998092651367 26.75028991699219 C 7.749998092651367 25.8658504486084 8.469528198242188 25.14630126953125 9.353948593139648 25.14630126953125 L 28.51812171936035 25.14630126953125 L 22.78439903259277 19.41240119934082 C 22.14432907104492 18.77231025695801 22.14432907104492 17.76951026916504 22.78439903259277 17.12942123413086 C 23.09354782104492 16.82024955749512 23.49892807006836 16.64999008178711 23.92586898803711 16.64999008178711 C 24.35280799865723 16.64999008178711 24.75818824768066 16.82024955749512 25.06733894348145 17.12942123413086 L 33.49604797363281 25.59222984313965 C 33.80729675292969 25.90348052978516 33.98195648193359 26.33366012573242 33.97489929199219 26.7721004486084 C 33.96802139282227 27.19858551025391 33.79694747924805 27.59096908569336 33.49312210083008 27.8774471282959 L 25.06768798828125 36.33697128295898 C 24.75818824768066 36.64649200439453 24.35881805419922 36.81674957275391 23.94279861450195 36.81674957275391 Z"/><path class="d" d="M 23.94279861450195 36.56674957275391 C 24.28127861022949 36.56674957275391 24.6197681427002 36.43135070800781 24.89055824279785 36.16054916381836 L 33.31892013549805 27.69808959960938 C 33.86049652099609 27.19034004211426 33.86049652099609 26.31023979187012 33.31892013549805 25.76865005493164 L 24.89055824279785 17.30619049072266 C 24.6197681427002 17.03539085388184 24.27281761169434 16.89999008178711 23.92586898803711 16.89999008178711 C 23.57891845703125 16.89999008178711 23.23196792602539 17.03539085388184 22.96117782592773 17.30619049072266 C 22.41959762573242 17.8477897644043 22.41959762573242 18.69403076171875 22.96117782592773 19.23563003540039 L 29.12165832519531 25.39630126953125 L 9.353948593139648 25.39630126953125 C 8.609278678894043 25.39630126953125 7.999998092651367 26.00559997558594 7.999998092651367 26.75028991699219 C 7.999998092651367 27.49499130249023 8.609278678894043 28.10429000854492 9.353948593139648 28.10429000854492 L 29.12165832519531 28.10429000854492 L 22.99502754211426 34.23110961914063 C 22.45344734191895 34.77270126342773 22.45344734191895 35.61894989013672 22.99502754211426 36.16054916381836 C 23.26581764221191 36.43133926391602 23.60430908203125 36.56674957275391 23.94279861450195 36.56674957275391 M 23.94279861450195 37.06674957275391 C 23.46000862121582 37.06674957275391 22.99785804748535 36.87047958374023 22.64147758483887 36.51409912109375 C 21.90227890014648 35.77487182617188 21.90227890014648 34.61677169799805 22.6414680480957 33.87755966186523 L 27.91457557678223 28.60429000854492 L 9.353948593139648 28.60429000854492 C 8.33167839050293 28.60429000854492 7.499998092651367 27.77259063720703 7.499998092651367 26.75028991699219 C 7.499998092651367 25.72800064086914 8.33167839050293 24.89630126953125 9.353948593139648 24.89630126953125 L 27.91457366943359 24.89630126953125 L 22.60761833190918 19.58917999267578 C 21.86842918395996 18.84996032714844 21.86842918395996 17.69186019897461 22.60761833190918 16.95264053344727 C 22.96398735046387 16.59626007080078 23.43214797973633 16.39999008178711 23.92586898803711 16.39999008178711 C 24.41958808898926 16.39999008178711 24.88774871826172 16.59626007080078 25.24411773681641 16.95264053344727 L 33.67318725585938 25.41580963134766 C 34.03167724609375 25.77431106567383 34.23301696777344 26.2703800201416 34.22485733032227 26.77613067626953 C 34.21691131591797 27.26923942565918 34.01913833618164 27.72353172302246 33.66771697998047 28.05642318725586 L 25.24482917785645 36.51338958740234 C 24.88774871826172 36.87047958374023 24.42559814453125 37.06674957275391 23.94279861450195 37.06674957275391 Z"/></g></g></svg>

My requirement is to change the background blue circle color to magenta on hover and the arrow color should not be changed. I tried using filter in the below ways:
1)filter in css

#svg_asset:hover{
    filter:  invert(18%) sepia(99%) saturate(3021%) hue-rotate(303deg) brightness(77%) contrast(107%);
}

*filter using color matrix

#svg_asset:hover{
    filter: url(#colorFilter);
}
<filter id="colorFilter">
    <feColorMatrix color-interpolation filters="sRGB"
          type="matrix"
          values="0.73 0   0   0   0
                  0   0.04  0   0   0
                  0   0   0.53  0   0
                  0   0   0   1   0 "
         />
</filter>

But these methods change the whole svg color instead of changing only the blue circle to some other color. Thanks in advance for your answers.


text:
Q: How to use the values out of sendAsynchronousRequest? I am parsing some JSON data using Http POST request and NSURLRequest. But when I have got the values under sendAsynchronousRequest I cannot use those out side of that request. Please see the example bellow:
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         NSError *parseError = nil;
         dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }];

My query is how can I use the dictionary value where I need it? Thanks

A: You can do it in many ways. One way is to declare a property and use it inside the block.
As you are making an asynchrounous call, it is better to have your own custom blocks to respond to those calls.
Declare a completion block first:
 typedef void (^ ResponseBlock)(BOOL success, id response);

and declare a method that uses this block as a param:
 - (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion;

and include your async call in this method:
- (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion{

 [NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     NSError *parseError = nil;
     dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
     NSLog(@"Server Response (we want to see a 200 return code) %@",response);
     NSLog(@"dictionary %@",dictionary);
     completion(YES,response); //Once the async call is finished, send the response through the completion block
 }];

}

You can call this method anywhere you want.
 [classInWhichMethodDeclared processMyAsynRequestWithCompletion:^(BOOL success, id response) {
      //you will receive the async call response here once it is finished.
         NSDictionary *dic = (NSDictionary *)response;
       //you can also use the property declared here
           _dic = (NSDictionary *)response; //Here dic must be declared strong
 }];


text:
Q: Understanding distribution of sum of random variables I am trying to better understand the solution to this given problem:
Given X and Y as independent variables, where $X \in U(-1,1) \ and \ Y$ assumes values +1 and -1 with probability 1/2. Need to show $Z=X+Y \in U(-2,2) $
The solution goes as this : $F_Z = P(Z\leq z) = P(Z\leq z | Y=-1)\cdot P(Y=-1) + P(Z\leq z |Y=1)\cdot P(Y=1)$
I would like to clarify here : how can the probability of Z be the above without considering X?
Although the solution continues from above as this :
$= P(X \leq z+1)\cdot 1/2 + P(X \leq z-1)\cdot 1/2$
I understand that it is using the total law of probability but am a bit confused behind the reasons/rules of doing the above although Z is a sum of the above 2 random variables.
Thank you.

A: Rather than approach the question directly, let's consider a simpler question.  Suppose $X$ is either $0$ or $2$ with probability $1/2$ each, and $Y$ is either $0$ or $1$ with probability $1/2$ each, and we ask what the distribution of the sum $Z = X+Y$ is.
In that case, we could definitely write something like
$$
P(Z = z) = P(Z = z \mid Y = 0) \cdot P(Y = 0) + P(Z = z \mid Y = 1) \cdot P(Y = 1)
$$
which doesn't explicitly involve $X$.  This is simply the law of total probability, since there are only two possible cases for $Y$, and we exhaust them.  We could then go on to write
$$
P(Z = z) = P(X = z \mid Y = 0) \cdot P(Y = 0) + P(X = z-1 \mid Y = 1) \cdot P(Y = 1)
$$
which is the same as above, but now takes advantage of our knowledge that $Z = X+Y$.
The same sort of evaluation is taking place in your original problem.

A:
The solution goes as this : $F_Z(z) = P(Z\leq z) = P(Z\leq z \mid Y=-1)\cdot P(Y=-1) + P(Z\leq z \mid Y=1)\cdot P(Y=1)$
I would like to clarify here : how can the probability of Z be the above without considering X?

That's just the law of total probability:  $~\mathsf P(A) $ $=\mathsf P(A\cap B)+\mathsf P(A\cap B^\complement)\\=\mathsf P(A\mid B)\,\mathsf P(B)+\mathsf P(A\mid B^\complement)\,\mathsf P(B^\complement)$
The probability of a union of disjoint events is the sum of the probabilities of each event.
There is nothing much more to it than that.
The events here are when $\{Z\leq z, Y=-1\}$ and when $\{Z\leq z, Y=+1\}$.
Because $Z=X+Y$ then these events are also $\{X\leq z+1, Y=-1\}$ and $\{X\leq z-1, Y=+1\}$
Since, when $Y=-1$ then $Z$ being less than $z$ means $X$ is less than $z+1$

The reason for doing this is simple:   We know the distribution functions of $X,Y$, and wish to find the distribution function of $Z$ in terms of them.   Since $Y$ is discrete so partitioning on it is easier.   Thus we apply the LoTP.
$$F_Z(z)= F_{X\mid Y=-1}(z+1)\,P_Y(-1)+F_{X\mid Y=1}(z-1)\,P_Y(1)$$
Now since $X,Y$ are independent, that simplifies to:
$$F_Z(z)= F_{X}(z+1)\,P_Y(-1)+F_{X}(z-1)\,P_Y(1)$$
And because $P_Y(y) = \tfrac 12 \mathbf 1_{Y\in\{-1,1\}}$ we have:
$$F_Z(z)= \tfrac 12\big(F_{X}(z+1)+F_{X}(z-1)\big)$$
Finally, $X$ is uniformly distributed over $(-1;1)$, so:
$$\begin{align}F_Z(z) ~&=~ \tfrac 14(\mathbf 1_{z+1\in(-1;1)}+\mathbf 1_{z-1\in (-1;1)}) \\[1ex] &=~ \tfrac 14~\mathbf 1_{z\in(-2;0)\cup(0;2)}\end{align}$$
Which means $Z\sim\mathcal U (-2;2){\setminus}\{0\}$.   That is uniformly distributed almost everywhere on the interval $(-2;2)$.
That is all.


text:
Q: Resizing the height of the selection indicator in a UIPickerView in an App I have to maintain I had to set the rowHeight of a UIPickerView row to the value of 66. Now it can properly display three lines of text.
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
 return 66;
}

Now the selection indicator height is too small for a row.
Can anybody help me finding out how I can increase the height of that selection indicator?
Many thanks in advance.
Uwe

A: Unfortunately it's impossible.
But if you want a useful selection indicator, the solution is to draw a custom selection indicator with proper dimensions (The background must be transparent) and then adds to the UIPickerView as a subview (Don't forget to set the frame correctly).
So the result will be a UIPickerView with an UIImageView in the middle that represents the selection indicator.
I hope it helps,
Arildo


text:
Q: I am not able to create pipeline for SSR nextjs produciton here is my pipeline steps:-

    export buildName=$(Build.BuildNumber)
    echo $buildName
    export buildnumber=${buildName/{PROJECTNAME}/1.0.}
    echo $buildnumber
    echo '##vso[task.setvariable variable=tag;]'$buildnumber
    cd $(Build.SourcesDirectory)
    npm install
    npm run build
    rm -r node_modules
    npm install --production

please help me to speedup nextjs SSR


text:
Q: Branch created in bitbucket does not shown in my local git even after git fetch In our company we have a branch for every Sprint.
When sprint ends, I switch to master and merge branch back into master from Eclipse git.
Team -> merge -> Local -> Sprint-1 ...
Team -> push to upstream.
Then I go to BitBucket and create a new branch. Sprint-2
Branch is created and work collegue can see it and use it, but for some reason I cannot see branch.
Elcipse pull says everything is up to date.
From console:
$ git fetch && git checkout Sprint-2
error: pathspec 'Sprint-2' did not match any file(s) known to git

$ git pull origin
Already up to date.

If I export project as new in Eclipse, then branch suddenly appears.
But it is not very convenient.