text:
Q: How to use Gamma distributions to estimate the number of failures? I need to calculate the expected number of failures of a product within 6 years.  The time until failure is said to be gamma distributed with $\alpha=2$ and $\beta=0.5$ for a mean time between failures of 1 year.
The product will be replaced after each failure, so I need to form a simulation to determine how many times I can expect to replace that product over the course of 6 years.  How can I calculate the expected number of failures in 6 years with this information? I will be implementing this in R.
I don't want to sound like I'm demanding an answer. There's much more to the problem in question. I'm only looking for a starting point as I have not used the Gamma distribution for this purpose before and after searching online I couldn't find much help.

A: Let's consider the problem generally so that we can delay the point at which details of Gamma distributions need to be known.  I will proceed in three stages: the first develops a general formula, the second exploits properties of Gamma functions (but without doing much calculation), and the third applies these results to the data in the question.

Relating service times to numbers of failures
At time $0,$ a product is put into service.  It lasts a random amount of time $T_1$ governed by some distribution law $F$ (which obviously must assign zero probability to negative times!).  At the moment $0+T_1,$ if the product is still needed, it is replaced by another.  It lasts a random amount of time $T_2$--independent of $T_1$--governed by the same law $F.$  At the moment $0+T_1+T_2,$ if the product is still needed this second product is replaced by a third.  This process continues until time $\tau \gt 0,$ representing how long some product needs to be in service.  Let $N(\tau)$ be the total number of products put into service between times $0$ and $\tau,$ so that
$$0 + T_1 + T_2 + \cdots + T_{N(\tau)} \lt \tau.\tag{1}$$
$N(\tau)$ is a random variable.  $N(\tau)-1$ is the number of product failures.  What is its expected value, $E[N(\tau)-1] = E[N(\tau)]-1$?
Writing $F_{N(\tau)}$ for the cumulative distribution of $N(\tau),$ a convenient way to find this expectation begins with the formula
$$E[N(\tau)]-1 = -1+\sum_{k=0}^\infty \Pr(N(\tau) \gt k) = \sum_{k=1}^\infty (1 - F_{N(\tau)}(k)).$$
Now, according to definition $(1)$ above, the event "$N(\tau)\le k$" -- which means $k$ or fewer products serially lasted at least for a duration $\tau$ -- can also be understood as meaning the total lifetime of $k$ products -- whether indeed $k$ were actually needed -- was $\tau$ or greater.  Thus
$$ F_{N(\tau)}(k) = \Pr(N(\tau)\le k) = \Pr(0+T_1+T_2+\cdots+T_k \ge\tau).\tag{2}$$
Writing $S_k = 0 + T_1 + T_2 + \cdots + T_k$ and $G_k$ for its cumulative distribution function,
$$G_k(\tau) = \Pr(0 + T_1 + T_2 + \cdots + T_k \le\tau) = \Pr(S_k \le \tau),$$
it is apparent that the right hand side of $(2)$ is closely related to the CDF of $S_k$ evaluated at $\tau,$
$$\Pr(0+T_1+T_2+\cdots+T_k \ge\tau) = \Pr(S_k \ge \tau) = 1 - \Pr(S_k \lt \tau) = 1 - (G_k(\tau) - \Pr(S_k=\tau)).$$
For a continuous time model--where a product could fail at any moment but has only infinitesimal chance of failing at any given moment--the last term $\Pr(S_k=\tau)$ is zero.  Together, the previous equations yield
$$E[N(\tau)-1] = \sum_{k=1}^\infty G_k(\tau).\tag{3}$$
This invites us to work out the CDFs $G_k(\tau)$ for $k = 1, 2, $ etc.

Using Gamma distributions of service times
That's about as far as the general analysis can go.  One reason why people hypothesize Gamma distributions for inter-arrival times is that they enjoy a very nice summation property:

The distribution of the sum of $k$ independent random variables with $\Gamma(\alpha,\beta)$ distributions has a $\Gamma(k\alpha,\beta)$ distribution.

In this notation, $\alpha$ is the "shape" parameter and $\beta$ merely establishes a scale--a unit of measurement--for the values.  (There are two conventions: in one, which I will use, $\beta$ is the unit of measurement; in the other, $1/\beta$ is the unit.  Obviously, switching between the two conventions is easy but when looking things up, be sure to check which convention is in use!)
Consequently, when $F$ is a $\Gamma(\alpha,\beta)$ distribution, then each $G_k$ is a $\Gamma(k\alpha,\beta)$ distribution.  Because these distributions have density functions, their CDFs can be expressed as integrals:
$$G_k(\tau) = \frac{1}{\Gamma(k\alpha)}\int_0^\tau x^{k\alpha} e^{-x} \frac{\mathrm{d}x}{x}.$$
In this formula I have dropped all references to $\beta$ because we can re-introduce it at the end, knowing it's just the unit of measurement of $\tau$ (namely, time).
In R, formula $(3)$ is readily evaluated by summing values of pgamma.  As an example:
#-- Specify the parameters of the problem
tau <- 6
alpha <- 2
beta <- 1/2

#-- Determine how far out to take the sum
u <- (rho + sqrt(6^2 + 4*tau/beta))/2
u <- pmax(1, round(u^2/alpha))

#-- Compute the sum
sum(pgamma(tau, alpha*seq_len(u), scale=beta))

In some cases, we can obtain simpler formulas.  The summation in $(3)$ can be interchanged with the integration, giving
$$E[N(\tau)-1] = \int_0^\tau \left(\sum_{k=1}^\infty \frac{x^{k\alpha}}{\Gamma(k\alpha)}\right)\ e^{-x} \frac{\mathrm{d}x}{x}.\tag{4}$$
The summation has nice properties (it converges absolutely for all $x$) and is relatively straightforward to evaluate numerically.

Calculations for the situation posed in the question
For small integral values of $\alpha,$ it's straightforward to obtain explicit formulas.  In the case of the question, with $\alpha=2,$ use the facts $0 = x^n-(-x)^n$ when $n$ is even and $2x^n=x^n-(-x)^n$ when $n$ is odd to re-express the inner sum of $(4)$ as
$$\sum_{k=1}^\infty \frac{x^{k\alpha}}{\Gamma(k\alpha)} = \sum_{k=1}^\infty \frac{x^{2k}}{(2k-1)!} = \frac{x}{2}\sum_{j=0}^\infty \frac{x^{j} - (-x)^{j}}{j!} = \frac{x}{2}\left(e^x - e^{-x}\right).$$
(See my account of decimation for the theory behind this technique.)
Thus, $(4)$ becomes

$$E[N(\tau)-1] = \int_0^\tau \left(\frac{x}{2}\left(e^x - e^{-x}\right)\right)\ e^{-x} \frac{\mathrm{d}x}{x} = \frac{1}{2}\left(\tau - \frac{1}{2}\left(1 - e^{-2\tau}\right)\right).$$

Also in the question, $\beta=1/2$ years and the duration is $6$ years, so using $\beta$ as the time units we must write $\tau = 6/\beta = 12$ time units.  Thus the answer is
$$E[N(12)-1] = \frac{1}{4}\left(23 + e^{-24}\right) \approx 5.750000000009438$$
(to double precision).  As far as any simulation is concerned, then, expect the average number of products failing during six years to be near $5.75.$


text:
Q: Displaying a button when a Listview is Swipe I am trying to create a listview on which if a row is swiped from rightside then a button appears. I went through various post on similar topics in Stackoverflow but was unable to comprehend those. It would be great if i have few instructions to go about as I am new to Android Development.
Thanks in Advance

A: Check out the Android SwipeListView  Also check Custom ListView with sliding view for each list

A: Try this way
1) Create This class
import android.content.Context;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;

public class SmartGestureListener extends SimpleOnGestureListener implements
        OnTouchListener {

    private Context context;
    GestureDetector gDetector;
    private ListView lstCustomListView;
    private boolean isFling = false;;
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private int swipeDeleteIjoomerButtonID;
    private OnSwipeDelete local;

    public SmartGestureListener() {
        super();
    }

    public SmartGestureListener(Context context, ListView lstCustomListView,
            int swipeDeleteIjoomerButtonID, OnSwipeDelete target) {
        this(context, lstCustomListView, null, swipeDeleteIjoomerButtonID, target);

    }

    public SmartGestureListener(Context context, ListView lstCustomListView,
            GestureDetector gDetector, final int swipeDeleteButttonID,
            final OnSwipeDelete target) {

        this.swipeDeleteIjoomerButtonID = swipeDeleteButttonID;
        this.local = target;

        if (gDetector == null)
            gDetector = new GestureDetector(context, this);

        this.context = context;
        this.gDetector = gDetector;
        this.lstCustomListView = lstCustomListView;

        this.lstCustomListView.setOnScrollListener(new OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

                if (!isFling) {

                    Log.e("tag", "onScroll");
                    int childern = SmartGestureListener.this.lstCustomListView
                            .getChildCount();
                    Log.e("tag", "count : " + childern);
                    for (int i = 0; i < childern; i++) {
                        View v = SmartGestureListener.this.lstCustomListView
                                .getChildAt(i);
                        Log.e("tag", "inside for loop");
                        if (v != null) {
                            Button btnDelete = (Button) v
                                    .findViewById(swipeDeleteButttonID);
                            if (btnDelete != null) {
                                Log.e("tag", "IjoomerButton found");
                                if (btnDelete.getVisibility() == View.VISIBLE) {
                                    btnDelete.setVisibility(View.INVISIBLE);
                                } else {
                                    btnDelete.setVisibility(View.INVISIBLE);
                                }

                            } else {
                                Log.e("tag", "IjoomerButton not found");
                            }
                        }
                        {
                            Log.e("tag", "view not found");
                        }
                    }
                } else {
                    isFling = false;
                }
            }
        });
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        super.onFling(e1, e2, velocityX, velocityY);

        try {
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                isFling = true;
                if (lstCustomListView != null) {
                    final int adapterIndex = lstCustomListView.pointToPosition(
                            (int) e1.getX(), (int) e1.getY());
                    int firstViewItemIndex = lstCustomListView
                            .getFirstVisiblePosition();
                    int viewIndex = adapterIndex - firstViewItemIndex;
                    Log.e("indexes", adapterIndex + " : " + firstViewItemIndex
                            + " : " + viewIndex);

                    View v = lstCustomListView.getChildAt(viewIndex);
                    Button btnDelete = (Button) v
                            .findViewById(this.swipeDeleteIjoomerButtonID);

                    // flip in animation applied to the IjoomerButton

                    if (btnDelete.getVisibility() == View.INVISIBLE) {

                        btnDelete.setVisibility(View.VISIBLE);
                        Animation a = AnimationUtils.loadAnimation(context,
                                R.anim.slide_left_in);
                        a.reset();
                        btnDelete.clearAnimation();
                        btnDelete.startAnimation(a);

                        btnDelete.setOnClickListener(new OnClickListener() {
                            public void onClick(View v) {

                                local.actionSwipeDelete(adapterIndex);
                            }
                        });
                    } else {
                        btnDelete.setVisibility(View.INVISIBLE);
                    }

                }
                return true;
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                isFling = true;

                if (lstCustomListView != null) {
                    final int adapterIndex = lstCustomListView.pointToPosition(
                            (int) e1.getX(), (int) e1.getY());
                    int firstViewItemIndex = lstCustomListView
                            .getFirstVisiblePosition();
                    final int viewIndex = adapterIndex - firstViewItemIndex;
                    Log.e("indexes", adapterIndex + " : " + firstViewItemIndex
                            + " : " + viewIndex);

                    View v = lstCustomListView.getChildAt(viewIndex);
                    Button btnDelete = (Button) v
                            .findViewById(swipeDeleteIjoomerButtonID);

                    if (btnDelete.getVisibility() == View.INVISIBLE) {

                        btnDelete.setVisibility(View.VISIBLE);

                        Animation a = AnimationUtils.loadAnimation(context,
                                R.anim.slide_left_in);
                        a.reset();
                        btnDelete.clearAnimation();
                        btnDelete.startAnimation(a);

                        btnDelete.setOnClickListener(new OnClickListener() {
                            public void onClick(View v) {

                                    local.actionSwipeDelete(adapterIndex);
                            }
                        });
                    } else {
                        btnDelete.setVisibility(View.INVISIBLE);
                    }

                }
                return true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return super.onSingleTapConfirmed(e);
    }

    public boolean onTouch(View v, MotionEvent event) {
        Log.e("gesture", "onTouch");
        return gDetector.onTouchEvent(event);
    }

    public GestureDetector getDetector() {
        return gDetector;
    }

}

2) Animation Xml file (Create "anim" folder in "res" folder and create below animation file)
slide_left_in.xml
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="800"/>
</set>

3) How to use?
SmartGestureListener swipeGestureListener = new  SmartGestureListener(this, myListview, R.id.btnDelete, new OnSwipeDelete() {

            @Override
            public void actionSwipeDelete(int rowID) {

            }
        });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to define a promise.all I am trying to understand how promises work by creating the Promise.all method from an exercise of this book:
https://eloquentjavascript.net/11_async.html#i_Ug+Dv9Mmsw
I tried looping through the whole array that's given as argument to the method itself, using .then for successful promises where the body of the handler pushes the result to a binding i defined previously outside of the loop, for rejected promises, i used .catch in a way that it takes the rejected value as a "reason" and rejects the main promise giving it an error
function Promise_all(promises) {
  return new Promise((resolve, reject) => {
    if(promises.length == 0) resolve(promises);
    let fullArray = [];

    for(let i=0; i<promises.length ; i++){
         promises[i]
        .then(x => fullArray.push(x))
        .catch(reason => reject(new Error(reason)));
    }
    resolve(fullArray);
  });
}

What i expected the function to do the following:
-Pick a promise from the "Promises" array.
-Solve the promise (if successful) by using the .then method on it with a handler function that just pushes the result to "fullArray".
-Solve the promise (if rejected) by using the .catch method on it with a handler function that simply calls the reject handler of the main promise that will be returned by "Promise_all".
-When the loop finishes, simply resolve the promise the "fullArray" of successful promises.
The code simply doesn't work the way i thought it would, using the test code of the book doesn't return the expected results:
Promise_all([]).then(array => {
  console.log("This should be []:", array);
});
function soon(val) {
  return new Promise(resolve => {
    setTimeout(() => resolve(val), Math.random() * 500);
  });
}
Promise_all([soon(1), soon(2), soon(3)]).then(array => {
  console.log("This should be [1, 2, 3]:", array);
});
Promise_all([soon(1), Promise.reject("X"), soon(3)])
  .then(array => {
    console.log("We should not get here");
  })
  .catch(error => {
    if (error != "X") {
      console.log("Unexpected failure:", error);
    }
  });

A: The issue with the code, as @Bergi said, was that the ".then" and ".catch" callbacks are called asynchronously and as a consequence of this, "fullArray" wasn't even filled when "resolve()" was called even when it was outside of the loop. To solve this, i simply added "resolve()" inside of the promise that finishes last, to do this, i simply added a "counter" binding that has the value of the length of the "promises" array, and is reduced by 1 every time ".then" was called on a promise and when this "counter" equals 0, it calls "resolve()".
But that only solves the problem of filling the "fullArray" with the promises, not the issue of those promises being ordered correctly by the order they were called, to solve this i simply enumerated them in the array with the "i" binding of the loop, the end result was this:
function Promise_all(promises) {
  return new Promise((resolve, reject) => {
    if(promises.length == 0) resolve(promises);
    let fullArray = [],
        counter = promises.length;

    for(let i=0; i< promises.length ; i++){
         promises[i]
        .then(x => {
           fullArray[i] = x;
           counter--;
           if(counter == 0) resolve(fullArray)})
        .catch(reason => reject(new Error(reason)));
    }
  });
}


text:
Q: show that $\tan \alpha_i = -t_i$ for each $i=1,2,3$
My question pertains to the question and solution below. In particular, can someone prove why $\tan \alpha_i = -t_i$ for each $i$? I think it would be worth clarifying what the angle each normal makes with the axis of the parabola (the x-axis) is. I think it's the smaller of the two angles formed by the normal lines and the axis.

A:
If you have already been able to understand how the normal equation at $(at^2, 2at)$ is derived, then you understand that $y=(–t)x + at^3 + 2at$ has slope "-t".
Also, by "angles which these three normals make with the axis", the reference is not to the smaller of the angles, but only the angle between the normal and the positive direction of the x-axis. That is why tanα = slope, otherwise we would have tan($\pi — α$) = slope for lines making obtuse angles with +X, because slope is defined as the tangent of the angle between the normal and the positive direction of the x-axis, measured anti-clockwise with the +X axis as the reference line.


text:
Q: 2 divs centered with multiple content I am consuming myself to find a way to solve this...
So, I have 2 content (CONTENT A and CONTENT B), floated side by side. I am searching for a way to center al of this content, but the problem is that CONTENT B has a dynamic width, so I am not figuring out how can I do this...
This is my LIVE EXAMPLE.
And here's my CSS and HTML.
CSS
.lean-slider-slide {
    display: none;
    position: relative;
    opacity: 0;
    -webkit-transition: all .7s;
    -moz-transition: all .7s;
    -ms-transition: all .7s;
    -o-transition: all .7s;
    transition: all .7s;
    float: left;
    text-align: left;
}
.lean-slider-slide.current {
    transition: all .9s;
    display: inline-block;
    opacity: 1;
    color: #00ACDE
}
.pglp span {
    float: left;
    font-size: 21px;
    font-family:"museo300";
    margin-right: 5px;
    text-align: right;
    color: #111;
}
div.pglp {
    width: 100%;
    margin-left: auto;
    margin-right: auto;
}

HTML

HELLO:

BANANA

MORANGO

Design Gráfico

NUTELA

PINEAPPLE

A: By use of display:inline_block;  and removing float: ... I got it to the point everything is in the center. BUT, because your 2nd block of information varies in with, the HELLO: will move along... so if this is not realy what you want, point it out, and I would surely try a second time.
Changed the SPAN into a DIV and added a class

HELLO:

and edited your css
.lean-slider-slide {
    display: none;
    position: relative;
    opacity: 0;
    -webkit-transition: all .7s;
    -moz-transition: all .7s;
    -ms-transition: all .7s;
    -o-transition: all .7s;
    transition: all .7s;
    text-align: left;
}
.lean-slider-slide.current {
    transition: all .9s;
    display: inline-block;
    opacity: 1;
    color: #00ACDE
}
.pglp2 {
    font-size: 21px;
    font-family:"museo300";
    margin-right: 5px;
    display: inline-block;
    color: #111;
}
div.pglp {
    width:100%;
    text-align: center;
}
#text_slider {
   display: inline-block;
}

see: http://jsfiddle.net/zuSke/


text:
Q: Parallel indexing in Keras or Theano The 2D problem
For each datapoint, I have an index matrix which I want to use to gather vectors from a 2D lookup matrix.
For a single datapoint, Theano and Keras allow easy indexing.

import keras.backend as K
result = K.gather(reference, indices)

E.g.:
result = K.gather(reference, indices)

#let:
indices.shape = (100, 5)
reference.shape = (101, 68)

#where:
max(indices) < reference.shape[0]

#then:
result.shape = (100, 5, 68)

The 3D problem
However, I need to repeat this process for each datapoint in a batch. E.g. I want to parallelise the lookup.
I have a 3D matrix that I want to convert into a 4D matrix.
E.g.

#let:
indices.shape = (batch_n, 100, 5)
reference.shape = (batch_n, 101, 68)

#desired result
result.shape = (batch_n, 100, 5, 68)

More formally, I am looking for an operation such that:
result[i,j,k,:] = lookup[i, indices[i,j,k], :]
or
result[i,j,k,l] = lookup[i, indices[i,j,k], l]
I implemented a Theano solution using scan. It is actually quite straightforward:
import theano
import theano.tensor as T

def parallel_gather(references, indices):
    result, _ = theano.scan(fn=lambda reference, indices:reference[indices], outputs_info=None, sequences=[references, indices])
    return result

Rewriting this to the Keras backend seems troublesome given that keras.rnn is the Keras alternative. It does not seem to support iteration of a list of tensors, and has some weird requirements.
I also wonder if this is the fastest option, perhaps some clever reshaping could also solve the problem.


text:
Q: Many problems with Swift3: cannot understand new syntax for completion handlers Yesterday I updated to new Mac OS X Sierra and XCode 8 which forced me to update to Swift 3.0 syntax. In my app I have many functions like the following:
fileprivate func requestFisheFieldWithHandler(_ url:String, completionHandler: @escaping (_ success: NSDictionary?, _ error: NSError?) -> Void) {

    let configuration = URLSessionConfiguration.default

    let url: URL = URL(string: url)!
    let urlRequest: URLRequest = URLRequest(url: url)

    let session = URLSession(configuration: configuration)

    let task = session.dataTask(with: urlRequest, completionHandler: { (data: Foundation.Data?, response: URLResponse?, error: NSError?) -> Void in

        if (error != nil) {
            //print(error?.code)
            //print(error)
            completionHandler(success: nil, error: error)
        }

        else {
            do {
                let responseJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [String: String]
                completionHandler(success: responseJSON, error:nil)
            }
            catch let error as NSError {
                completionHandler(success: nil, error:error)
            }
        }
    } as! (Data?, URLResponse?, Error?) -> Void)

    task.resume()
}

and I get this error:

"Cannot convert value of type '(Data?, URLResponse?, Error?) -> Void' to expected argument type '(Data?, URLResponse?, Error?) -> Void'"

Moreover, I also used many associative arrays to collect data from downloaded JSON file, like the following:
for comune in response! {
                        self.comuni.append(comune["nome"] as! String)
                        self.comuniWithID[comune["nome"] as! String] = Int(comune["idcomune"] as! String)
}
DispatchQueue.main.async {
    self.myPicker.reloadComponent(1)
}

and another error I get is:

"Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members"

Please, would someone help me to correct them? Because I cannot understand what they mean and my app will be published next 30th September...

A: The most significant change is that all parameter labels in closures have been removed in Swift 3.
This is your code Swift 3 compatible.
As always, do not cast a Swift collection type to a Foundation counterpart. You will throw away all type information.
And don't use the annotations in the completion block return values, the compiler can infer the types. If you need to look up the actual types ⌥-click on the symbol.
fileprivate func requestFisheFieldWithHandler(_ url:String, completionHandler: @escaping ([String: String]?, NSError?) -> Void) {

  let configuration = URLSessionConfiguration.default

  let url: URL = URL(string: url)!
  let urlRequest = URLRequest(url: url)

  let session = URLSession(configuration: configuration)

  let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
    if (error != nil) {
      completionHandler(nil, error as NSError?)
    }

    else {
      do {
        let responseJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [String: String]
        completionHandler(responseJSON, nil)
      }
      catch let error as NSError {
        completionHandler(nil, error)
      }
    }
  }
  task.resume()
}

Regarding the second error you have to cast response! to something more meaningful than Any, I guess ... in response as! [[String:Any]]

A: The completion handler of dataTask(with:completionHandler:) in Swift 3 is changed to completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void so use Error instead of NSError.
let task = session.dataTask(with: urlRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in

For more about completion Handler check Apple Documentation.
For your error

Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members"

You need to specify the type of your response to [[String:Any]] then all goes to normal.
if let array = response as? [[String: Any]] {
    for comune in array {
        self.comuni.append(comune["nome"] as! String)
        self.comuniWithID[comune["nome"] as! String] = Int(comune["idcomune"] as! String)
    }
}


text:
Q: How do I rename a class including test target in Xcode? I frequently use Xcode refactor/rename tool to rename classes, variables, protocols, etc. in my code. It fails to rename the references to these classes in my tests target. How can I get the refactor/rename tool to rename these classes in both my regular target and my test target?

A: In Xcode 13, renaming a function used in an application and test targets is only possible by renaming it from the test target.


text:
Q: How can I set y-intercept to zero in plotly with simple example of issue I've had a great time getting to learn R, but I have struggled with one thing in my Plotly graph..
Below is a simple example of the issue I am having. Basically the plot is setting the y-intercept at my second data point "3.5%". I want the intercept to cross at y = 0 so that both of my values show up on the bar plot side by side
library(plotly)

x <- c("Unlevered", "Levered")
y <- c("4.5%","3.5%")
summary_plot <-  data.frame(x, y)
plot_ly(data = summary_plot, x = ~x, y = ~y, type = "bar")

Here is what my plot currently looks like:
Example Plot

A: Try something like:
s <- seq(0, 4.5)
p <- plot_ly(x = ~x, y = ~s)

A: Try this by relevel-ing your factor values in y:
library(plotly)
x <- c("Unlevered", "Levered")
y <- c("4.5%","3.5%")
summary_plot <-  data.frame(x, y)
levels(summary_plot$y) <- c(levels(summary_plot$y), '0.0%')
summary_plot$y <- factor(summary_plot$y, levels = sort(levels(summary_plot$y)))
plot_ly(data = summary_plot, x = ~x, y = ~y, type = "bar")


text:
Q: Notifier calling earlier then expected I have following issue
0) Homepage having two button, Button A , Button B
1) TabbarviewC.h/TabbarviewC.m  //set in storyboard class its a subclass of UITabBarController

- (void)viewDidLoad
{
[self loadAPI];
}

    -(void)loadAPI
    {

     //load my api
     //on success load another api and insert data in sqlite database
     //on completion of insert database i add notifier

    [self databaseinsertComplete];
    }

-(void)databaseinsertComplete
{

  [[NSNotificationCenter defaultCenter]  postNotificationName:@"DataLoadedCompletely" object:nil];

}

2) I have load an API in TabbarviewC.m
    3) I have 4 tabs (tab1,tab2,tab3,tab4) to be link with TabbarviewC
Now, according to situation , i need to pass data in all 4 tabs
also
If user Press button A -> it load the API and then jump to tab 1

-(IBAction)ButtonA:(id)sender
{
UIStoryboard *storyboard  = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UITabBarController *tbc = [storyboard instantiateViewControllerWithIdentifier:@"TabBarController"];
            tbc.selectedIndex=0;
            self.window.rootViewController = tbc;
            [UIView transitionWithView:self.window duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:nil];
}

If user press button B -> it will open the tab2

-(IBAction)ButtonB:(id)sender
{
UIStoryboard *storyboard  = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UITabBarController *tbc = [storyboard instantiateViewControllerWithIdentifier:@"TabBarController"];
            tbc.selectedIndex=1;
            self.window.rootViewController = tbc;
            [UIView transitionWithView:self.window duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:nil];
}

In my tab1 or tab 2 i add the notifier addObserver to call a reload tableview function but its call to early before the data inserted in sqlite db
- (void)viewDidLoad
{
 [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadTableview)
                                                 name:@"DataLoadedCompletely" object:nil];
}

-(void) reloadTableview
{
//my table view reload
//it loads the data from database and then reload the tableview
}

in both case i need to load the API data at TabbarviewC and on success of it i have to show the data in tab 1 , or tab 2
In my case, the API response get later and my tab shows empty tableview results at first time.

A: NSNotificationCenter posts notifications synchronously. Not sure how you save data to your sqlite database but if you have a completion handler - you should use it to post a notification. Also, good thing here would be posting a notification asynchronously with NSNotificationQueue. Something like that:
NSNotification *notification = [NSNotification notificationWithName:@"DataLoadedCompletely"
                                                             object:nil];
[[NSNotificationQueue defaultQueue] enqueueNotification:notification
                                           postingStyle:NSPostASAP];

This way you will get your notification delivered right in time and you will have no race conditions.

A: Most likely, whatever you are doing to retrieve your data is running asynchronously... but you are sending the "complete" notification as soon as you start your data retrieval process.
-(void)loadAPI
{

 //load my api
 //on success load another api and insert data in sqlite database
 //on completion of insert database i add notifier

[self goGetData]; // probably returns immediately

[self databaseinsertComplete]; // method is called *while* data is still being retrieved
}

So, if your "fetch data" process is async, make sure you are waiting for it to fully complete before you send your "DataLoadedCompletely" notification.


text:
Q: Chi-square in ANOVA I am comparing models that I created with the lmer function from the lme4 package using ANOVA. Paricipants and verbs are my random factors, and RT are the Reaction Times that I measured. From the little statistics that I know, I would expect F-statictic values in the output, but instead I get chi-square.
Could you please help me understand why I get that, or whether I should (or could) change that?
Here is my code and output:
m0<-lmer((sqrt(RT))~(1|Participant)+(1|Verbs), data=data, REML=FALSE)
m1<-lmer((sqrt(RT))~(1|Participant)+(1|Verbs)+verbT, data=data, REML=FALSE)

anova(m0,m1)

Data: data
Models:
m0: (sqrt(RT)) ~ (1 | Participant) + (1 | Verbs)
m1: (sqrt(RT)) ~ (1 | Participant) + (1 | Verbs) + verbT
   Df     AIC     BIC logLik deviance  Chisq Chi Df Pr(>Chisq)
m0  4 -693.68 -672.44 350.84  -701.68
m1  5 -693.71 -667.16 351.85  -703.71 2.0238      1     0.1548


text:
Q: Py.Test hangs on timeout when running parallel tests with xdist I've recently started using pytest to run my automated test suite. Test runs that were completing successfully when run sequentially, are now failing randomly when I use xdist to run the suite in parallel. I have pytest configured as follows;
[pytest]
addopts = -nauto --rerun 3 -ra --timeout=180 --junit-xml=pyresult.xml
python_files=test*.py

At random a test will fail to launch the Chromedriver and a timeout will be eventually thrown. For all other instances of failed tests for flaky reasons, pytest will gladly rerun the test for me. However in this instance, when the timeout is thrown, pytest outputs the timeout and then just hangs. My test run never ends and hence Jenkins doesn't get the results its waiting for. The only way to get pytest to finish is to manually send a control break.
My driver is started as follows (NOTE I don't think my code is the problem here);
@classmethod
def open_browser(cls, browser_name, configuration, down_dir=""):
    """
    Returns the driver for the required browser
    """
    if browser_name == 'Chrome':
        chrome_options = webdriver.ChromeOptions()
        prefs = {"download.default_directory" : down_dir}
        chrome_options.add_experimental_option("prefs", prefs)
        driver = webdriver.Chrome(
            executable_path=configuration, chrome_options=chrome_options)

The timeout message is as follows;
~~~~~~~~~~~~~~~~~~~~~~~~~~ Stack of <unknown> (8460) ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 277, in _perform_spawn
    reply.run()
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 213, in run
    self._result = func(*args, **kwargs)
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 954, in _thread_receiver
    msg = Message.from_io(io)
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 418, in from_io
    header = io.read(9)  # type 1, channel 4, payload 4
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 386, in read
    data = self._read(numbytes-len(buf))

~~~~~~~~~~~~~~~~~~~~~~~~~ Stack of MainThread (12788) ~~~~~~~~~~~~~~~~~~~~~~~~~~
  File "<string>", line 1, in <module>
  File "<string>", line 7, in <module>
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 1534, in serve
    SlaveGateway(io=io, id=id, _startcount=2).serve()
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 1047, in serve
    self._execpool.integrate_as_primary_thread()
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 259, in integrate_as_primary_thread
    self._perform_spawn(reply)
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 277, in _perform_spawn
    reply.run()
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 213, in run
    self._result = func(*args, **kwargs)
  File "c:\python27\lib\site-packages\execnet\gateway_base.py", line 1072, in executetask
    do_exec(co, loc)  # noqa
  File "<string>", line 1, in do_exec
  File "<remote exec>", line 154, in <module>
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 724, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 338, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 333, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 596, in execute
    res = hook_impl.function(*args)
  File "c:\python27\lib\site-packages\_pytest\main.py", line 119, in pytest_cmdline_main
    return wrap_session(config, _main)
  File "c:\python27\lib\site-packages\_pytest\main.py", line 94, in wrap_session
    session.exitstatus = doit(config, session) or 0
  File "c:\python27\lib\site-packages\_pytest\main.py", line 125, in _main
    config.hook.pytest_runtestloop(session=session)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 724, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 338, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 333, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 596, in execute
    res = hook_impl.function(*args)
  File "<remote exec>", line 58, in pytest_runtestloop
  File "<remote exec>", line 74, in run_tests
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 724, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 338, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 333, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 595, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 247, in _wrapped_call
    call_outcome = _CallOutcome(func)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 264, in __init__
    self.result = func()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 595, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 247, in _wrapped_call
    call_outcome = _CallOutcome(func)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 264, in __init__
    self.result = func()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 596, in execute
    res = hook_impl.function(*args)
  File "c:\python27\lib\site-packages\pytest_rerunfailures.py", line 73, in pytest_runtest_protocol
    reports = runtestprotocol(item, nextitem=nextitem, log=False)
  File "c:\python27\lib\site-packages\_pytest\runner.py", line 76, in runtestprotocol
    reports.append(call_and_report(item, "call", log))
  File "c:\python27\lib\site-packages\_pytest\runner.py", line 120, in call_and_report
    call = call_runtest_hook(item, when, **kwds)
  File "c:\python27\lib\site-packages\_pytest\runner.py", line 138, in call_runtest_hook
    return CallInfo(lambda: ihook(item=item, **kwds), when=when)
  File "c:\python27\lib\site-packages\_pytest\runner.py", line 150, in __init__
    self.result = func()
  File "c:\python27\lib\site-packages\_pytest\runner.py", line 138, in <lambda>
    return CallInfo(lambda: ihook(item=item, **kwds), when=when)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 724, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 338, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 333, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 595, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 247, in _wrapped_call
    call_outcome = _CallOutcome(func)
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 264, in __init__
    self.result = func()
  File "c:\python27\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 596, in execute
    res = hook_impl.function(*args)
  File "c:\python27\lib\site-packages\_pytest\runner.py", line 91, in pytest_runtest_call
    item.runtest()
File "c:\python27\lib\site-packages\_pytest\unittest.py", line 151, in runtest
    self._testcase(result=self)
  File "c:\python27\lib\unittest\case.py", line 393, in __call__
    return self.run(*args, **kwds)
  File "c:\python27\lib\unittest\case.py", line 320, in run
    self.setUp()
  File "C:\Users\rhoward\Documents\GitHub\ui-selenium-tests\ui_selenium_tests\test010_provider_application_accordia
n.py", line 94, in setUp
    self.used_browser, self.browser_config)
  File "C:\Users\rhoward\Documents\GitHub\ui-selenium-tests\ui_selenium_tests\general_functions.py", line 198, in o
pen_browser
    executable_path=configuration, chrome_options=chrome_options)
  File "c:\python27\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 67, in __init__
    desired_capabilities=desired_capabilities)
  File "c:\python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 91, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "c:\python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 173, in start_session
    'desiredCapabilities': desired_capabilities,
  File "c:\python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 231, in execute
    response = self.command_executor.execute(driver_command, params)
  File "c:\python27\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 395, in execute
    return self._request(command_info[0], url, body=data)
  File "c:\python27\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 426, in _request
    resp = self._conn.getresponse()
  File "c:\python27\lib\httplib.py", line 1136, in getresponse
    response.begin()
  File "c:\python27\lib\httplib.py", line 453, in begin
    version, status, reason = self._read_status()
  File "c:\python27\lib\httplib.py", line 409, in _read_status
    line = self.fp.readline(_MAXLINE + 1)
  File "c:\python27\lib\socket.py", line 480, in readline
    data = self._sock.recv(self._rbufsize)

+++++++++++++++++++++++++++++++++++ Timeout ++++++++++++++++++++++++++++++++++++

Ideally I want pytest to note the timeout, but just rerun the test again and finish the test run as normal.


text:
Q: Sound as a conserved quantity From the first man to the present day men, all of them have made some sound. Sound is an energy, it can neither be created nor can it be destroyed. Therefore, every word spoken by each human that came into this world made some sound. Their voices might have converted into another form of energy. But, we have not lost that sound energy. Am I right?

A: (In fact, Michael has got most of the points. Er...)
First of all, Sound is a longitudinal wave which means it moves via compression / rarefaction. Whatever objects it interact (comparatively massive ones like a cloth, paper, stone, atoms), it affects them. Well, it can be easily noticed in a sub-woofer. Being a mechanical wave, it just tries to push, thereby disturbing objects. As Michael said, the sound energy is converted to heat energy and is lost as it propagates through the medium. The reason it can't be easily observed because, it is so negligible (similar to an elastic band or spring, after it is released from tension when elastic energy is converted to heat energy)
But, this can be observed in wood or plastic-like objects which are probably used for echo-prevention. For example, If you pass sound in a room completely covered with wood, no waves get reflected back. All are lost as heat-energy within wood itself. A great practical application would be Ultrasonic welding where high-frequency sound waves can be used to generate enough heat to weld plastics, etc.

A: Suppose you stand in the middle of a room and make a sound. When you make a sound you are causing air molecules to vibrate. The sound wave travels away from you and hits the walls, and it makes the molecules in the wall vibrate. These vibrations spread through the wall, then into the ground and in principle make the entire Earth vibrate, though of course the energy in the original sound gets spread more and more thinly and by the time the vibration has spread to the Earth it's energy is swamped by thermal noise.
So in principle the energy is still there, but in practice it's so widely spread that it would be impossible to reconstruct it. This is one of the many consequences of the second law of thermodynamics.
Actually the situation is worse than I described above because liquids don't have the vibrational modes of solids and if the sound hits a liquid the energy is rapidly dispersed as kinetic energy of the molecules in the liquid. This would be even harder to track backwards than the vibrations in the wall.


text:
Q: php call to oci_execute in try catch block Here is my code:
try
{
    oci_execute($command);
}
catch(Exception $e){
    $this->sendMailFunction($e);
}

where $command is a Oracle SQL Query. My Question is, if the query fails, the control is not going into the catch block. Why is it so?
I am using yii framework of php.

A: oci_execute doesn't throw Exceptions. If it fails, boolean false will be returned and a Warning will be generated. To get the error details you'll need to call the oci_error() function instead of try/catch:
if (false === oci_execute($command)) {
    $this->sendMailFunction(oci_error($command));
};

If you don't want the Warning in your error log you can prepend a @ sign to suppress it.


text:
Q: SSIS - Difference between merge and merge join I would like to know what the major difference between merge and merge join in ssis is.

A: You should google this first. Anyway to answer :
Merge Join is same as JOIN in t-sql, you can choose between different types of Inner join, left outer join  and outer join
the difference is that with Merge join transformation you can support two inputs from two different data source, for example one from flat file and another from oracle DB, but with join in t-sql you can only join from one data source.
Merge Transform is not actually like join, this will merge rows like UNION. this differ from UNION ALL Transform a bit, you can see difference between merge and union transforms here:
http://sqlserversolutions.blogspot.com/2009/01/difference-between-merge-and-union-all.html
source : microsoft technet


text:
Q: Failure in importing geojson data in Postgresql I am new to both PostgreSQL and GeoJson. While following some of the tutorials online and some answer over here I wrote this line to import my geojson file:
ogr2ogr -f "PostgreSQL" PG:"dbname=In user=postgres" "C:\Users\hp\Downloads\red\map.geojson" -nln locations -append

But this line produces a syntax errorERROR:  syntax error at or near "ogr2ogr"
I also followed the instructions on this answer Store GeoJson with Feature Collection
The data is shown but only on running the query given in the answer above. But how do I store this data. I am not able to find it by doing select * from table
_name.
Also the answer given on the above link shows data as expected but It is only shown the data and not storing it.
If anyone can help me insert the geojson file either by using the ogr2ogr or by helping me to insert data in table by using the link above.


text:
Q: Swagger-ui how is the name of api (resource) generated? When I create an API with swagger, normaly my API has the name of the resource:
Tasks
/tasks
/tasks/{id}
etc.

Sometimes I only get a default:
Default
GET /tasks
GET /tasks/{uuid}
etc.

What determines the header name of the API generated?
Screenshot of wished behaviour (tasks is sometimes default):

A: Do you mean these headers in Swagger UI?

They are generated based on the tags of your API operations. For example, to group operations under "Tasks", use:
{
  ...

  "paths": {
    "\/tasks:": {
       "tags": [
         "Tasks"
       ],
       ...

Each operation can have any number of tags. Operations with no tags will be listed under the "Default" group.
To provide description for the tags, use the top-level tags section:
{
  ...

  "tags": [
    {
      "name": "Tasks",
      "description": "Operations to manage tasks"
      }
    },
    {
      "name": "Notes",
      "description": "Operations to manage notes"
      }
    }
  ],
  ...

A: This depends on what you have passed on as an argument to swagger's Api annotation (io.swagger.annotations.Api) at the top of your RESTful service implementation -
@Path(value="/")
@Api(value="/")
public interface YourService {
    ....
}

@Api(value="/") will generate default
@Api(value="/Tasks") will generate Tasks


text:
Q: choose the newest file and use getline to read it Having problems with a small awk script, Im trying to choose the newest of some log files and then use getline to read it. The problem is that it dosent work if I dont send it any input first to the script.
This works
echo | myprog.awk

this do not
myprog.awk

myprog.awk
BEGIN{
#find the newest file
command="ls -alrt | tail -1 | cut -c59-100"
command | getline logfile
close(command)
}
{
while((getline<logfile)>0){
    #do the magic
    print $0
}
}

A: Your problem is that while your program selects OK the logfile the block {} is to be executed for every line of the input file and you have not input file so it defaults to standard input. I don't know awk very well myself so I don't know how to change the input (if possible) from within an awk script, so I would:
#! /bin/awk -f

BEGIN{
    # find the newest file
    command = "ls -1rt | tail -1 "
    command | getline logfile
    close(command)
    while((getline<logfile)>0){
    getline<logfile
        # do the magic
        print $0
    }
}

or maybe
alias myprog.awk="awk '{print $0}'  `ls -1rt | tail -1`"

Again, this maybe a little dirty. We'll wait for a better answer. :-)

A: Never parse ls. See this for the reason.
Why do you need to use getline? Let awk do the work for you.
#!/bin/bash
# get the newest file
files=(*) newest=${f[0]}
for f in "${files[@]}"; do
  if [[ $f -nt $newest ]]; then
    newest=$f
  fi
done

# process it with awk
awk '{
    # do the magic
    print $0
}' $newest


text:
Q: Sed to extract till first space after 2nd word How can we use sed to get the 4 characters between "Install ID:" and first space after XKCD, basically I want to extract "XKCD" string out of it
Install ID:          XKCD (8426200,8179503)

I tried using -
 echo "Install ID:          XKCD (8426200,8179503)" | sed -n 's/^.*ID:\(.*\)*$/\1/p'

but that gives me "XKCD (8426200,8179503)" instead of just XKCD. I am not able to figure out, how to hand the space part.

A: A couple of minor revisions to your attempt:
echo "Install ID:          XKCD (8426200,8179503)" | sed -n 's/^.*ID: *\([^ ]*\) .*$/\1/p'

or
echo "Install ID:          XKCD (8426200,8179503)" | awk '{print $3}'

A:  test="Install ID:          XKCD (8426200,8179503)"
 echo $test | sed -re 's/^.*\:\s+([A-z]{4}).*/\1/'

Or: ignore everything before the colon, ignore spaces after the colon, get the four chars after the spaces, then ignore everything afterwards. If your characters include numbers or other things it would currently fail, though (you'd need to add them to the list in the square brackets).


text:
Q: How do I call javascript function from codebehind with ClientScript
Possible Duplicate:
How to call javascript function from code-behind

I have an empty div that I want to be adding check boxes to if a code behind boolean is true.
Here is the div:
<div id="checkboxes" />

Here is my javascript function:
        <script type="text/javascript">
        function addCheckboxes() {
            alert("just an alert for now");
        }

And here is my code behind where I want to call the "addCheckboxes" function:
bool isMovingTask = Convert.ToBoolean(Request.QueryString["isMovingTask"].ToString());
        if (isMovingTask)
        {
            //call javascript function
        }

A: See related answer here: How to call javascript function from code-behind
Basically you want to make a call to register your client script, there are a few ways to do this in .NET.

A: javascript is called when server execution of code and finished and generated html/script response is sent to browser. You can access public property of code behind in javascript and use it.
Make a public property in code behind and assign value to it in code behind
Code Behind
public  bool isChecked = true;

Html
    function addCheckboxes() {

       if('<%= isChecked %>' == 'True')
       {
          //Your code here
          alert("just an alert for now");

       }
    }


text:
Q: creating graphs in wolfram alpha I am trying to plot the function $$\max(x-40,0)$$ in Wolfram|Alpha, but I can't figure out how.
What Wolfram|Alpha query URL should I use to produce this graph? Or, what similar online program could I use to produce this graph?

A: Try out Desmos.
Typing $y=\max \left(x-40,0\right)$ works perfectly.
Here's a link to this graph:

A: Wolfram|Alpha works for me if you specify the bounds for $x$:
» plot max(x - 40, 0) from x = -20 to 60


text:
Q: Rails Models Structure I'm developing a website with the following models:
- Restaurant
--> has_one :menu

- Menu
--> has_many :items
--> belongs_to :restaurant

- Item
--> belongs_to :menu

- Food

- Drink

Food and Drink are models that theoretically subclass from Item because each of them will have its own specific attributes. I tried the STI (Single Table Inheritance) approach but I realized that I cannot add custom fields to Food and Drink because the tables are not created.
I think this is a pretty common scenario but I'm stuck on how to implement it.

A: I would approach it like this:
class Item < ActiveRecord::Base
  self.abstract_class = true
  belongs_to :menu

  # ...any other code that Food and Drink share...
end

class Food < Item
  self.table_name = "foods"

  # ...code specific to Food...
end

class Drink < Item
  self.table_name = "drinks"

  # ...code specific to Drink...
end

As you can see, the special parts are the abstract_class and table_name class methods. The docs for the former include this information:

abstract_class
Set this to true if this is an abstract class (see abstract_class?).
  If you are using inheritance with ActiveRecord and don't want child
  classes to utilize the implied STI table name of the parent class,
  this will need to be true. For example, given the following:
class SuperClass < ActiveRecord::Base
  self.abstract_class = true
end
class Child < SuperClass
  self.table_name = 'the_table_i_really_want'
end

self.abstract_class = true is required to make Child<.find,.create, or any Arel method> use the_table_i_really_want instead of a table called super_classes

Of course, you will need to implement migrations for both the foods and drinks tables.

A: This is fairly common. Assuming that all Item's had a name, food has a vegetarian flag and drink has a an alcoholic flag. You might end up with the following fields in your items table:

*

*items

*

*id

*type # this field will have the value Food or Drink

*name

*vegetarian

*alcoholic

This is fine if there aren't too many fields that are different. Because of the implementation there is also nothing stopping you accessing the alcoholic value of a food item.
If there are lots of different attributes between Food and Drink a common implementation would be to have something like:
class Item < ActiveRecordBase
class Drink < Item
  has_one :detail, class_name: :drink_detail, dependent: :destroy
  delegates :alcoholic, to: :detail
class DrinkDetail < ActiveRecordBase
class Food < Item
  has_one :detail, class_name: :food_detail, dependent: :destroy
  delegates :food, to: :detail
class FoodDetail < ActiveRecordBase

You would then have 3 tables:

*

*items

*

*id

*type

*name

*drink_details

*

*id

*item_id

*alcoholic

*food_details

*

*id

*item_id

*vegetarian

A: You mean this?
- Restaurant
--> has_one :menu

- Menu
--> has_many :items
--> belongs_to :restaurant

- Item
--> belongs_to :menu
--> has_many :foods
--> has_many :drinks

- Food
--> belongs_to :item

- Drink
--> belongs_to :item

A: According to my comment, if you don't have the tables yet, maybe a solution would be something like this:
class Menu < AR
    has_many :items
end

class Item < AR
    belongs_to :menu
end

class Food < Item
    def name
       "French Fries"
    end
end

Then
menu.items << Food.new()
menu.items.first.name
# French Fries


text:
Q: Javascript: Split a long CSV string into array of strings without losing the values I am trying to find a solution for a SQL problem that i think i can solve via JavaScript but cant conceptualize the solution and need some help with it. I have a long string (118.0000000000,102.6666666666,110.6666666666,97.5000000000,82.5000000000,86.6666666666 .... 15000 characters long) that i need to break into a max string length of 4000 (SQL NVARCHAR(max) limitation) and iterate the strings to a stored proc for further processing.  Lets say using the string above i wanted to split the string at 35 character length but not lose data and terminate the new string at the last ',' before the 35th character and build the next string from that point on, so essentially strings would look like this:
118.0000000000,102.6666666666
110.6666666666,97.5000000000
82.5000000000,86.6666666666

I tried to look through all the solutions already presented related to splliting string but have not been able to extract the info that could result in solving my issue here. Appreciate all the help!

A: If your strings are going to be really long, it might be faster to just work with indexes manually rather than breaking everything into arrays — it's not much less readable. For this you just look ahead to the comma beyond 35 characters with each loop, take the part up to the last comma and reset the position to where the comma was plus 1. If you don't have 35 characters left, just add the last bit and stop.

function splitGroups(str, MAX) {
    let res = []
    let start = 0

    while (start < str.length) {
        if (str.length - start <= 35) {
            res.push(str.slice(start))
            break
        }
        let c = str.slice(start, str.indexOf(',', start + MAX + 1))
        let end = c.lastIndexOf(',')
        res.push(c.slice(0, end))
        start += end + 1
    }
    return res
}

let str = "118.0000000000,102.6666666666,110.6666666666,97.5000000000,82.5000000000,86.6666666666"

let groups  = splitGroups(str, 35)
console.log(groups)
console.log("lengths", groups.map(s => s.length) )

A: Use substr() to get the first 35 characters, split that into an array, then remove the last element of the array since it might not be a complete number.
var csv = "118.0000000000,102.6666666666,110.6666666666,97.5000000000,82.5000000000,86.6666666666";
var csv35 = substr(csv, 0, 35);
var nums = csv35.split(",");
nums.length--;

A: If I'm understanding your question correctly, you want to split a string at a separator in chunks of a predetermined maximum character length. Here's a functional approach that allows you to dynamically specify the length and separator:

const chunk = (maxLen, separator) => data => data.split(separator).reduce((chunks, v, i) => {
  const last = chunks.length - 1;

  if (chunks[last].length + separator.length + v.length <= maxLen) {
    chunks[last] += (i ? separator : '') + v;
  } else {
    chunks.push(v);
  }

  return chunks;
}, ['']);

let chunkAt35ByComma = chunk(35, ',')
let data = '118.0000000000,102.6666666666,110.6666666666,97.5000000000,82.5000000000,86.6666666666'
let chunks = chunkAt35ByComma(data)

console.log(chunks)


text:
Q: How to plot ROC for LOOCV by hand based on output probabilities returned by SVM? I want to plot ROC for Leave-one-out (LOO) cross-validation (CV).
I have the decision values as well as probability values for each class from SVM classifier.
I did see the answer to this post; however, the answer was not complete about plotting ROC according to probabilities.
As an example the output of my classifier for one sample is like this:
c1a
  1
attr(,"decision.values")
          1/0
c1a 0.1338180
attr(,"probabilities")
            1         0
c1a 0.6824716 0.3175284
Levels: 0 1


text:
Q: Get path of Java application that launched the executable I am trying to validate that only our Java application has launched an inside-included executable. To achieve this, I thought of having a list of valid known SHA2 hashes (of the Java application) on our server and the executable will first check if the application's hash it was launched from is on that list.
So far, everything is working. The hashing, client-server communication etc. Except I have stumbled at the last hurdle. I am unable to get the path of the Java application from the executable.
I thought I could simply do this:
pid_t jarpid = getppid();

// Got from online
int get_exe(pid_t pid, char* buf, size_t bufsize) {
    char path[64];
    sprintf(path, "/proc/%d/exe", pid);
    return readlink(path, buf, bufsize);
}

However this points to /usr/lib/jvm/java-8-oracle/jre/bin/java and not the running Java Application. I do use the ProcessBuilder in the application to launch the executable.
So my question is, how can I get the applications path that launched the executable. Is it even possible? I cannot provide the executable with arguments, as that would be too easy to reverse engineer.


text:
Q: Quotient of a Riemann Surface So i have been reading a little bit about riemann surfaces and at some point the author says that if a group $G$ acts on $X$, our riemann surface, by holomorphic automorphisms, such that :
1) Around each point $p \in X$ we can find an open neighborhood $N$ such that if $q_1,q_2 \in N$ and $g.q_1=q_2$ then $g=id$ and $q_1=q_2$.
2) Suppose $p,q \in X$ wich do not lie in the same orbit, then there are neighborhoods $N_1,N_2$ of $q_1,q_2$  such that $GN_1$ is disjoint from $N_2$.
Now i am trying to see that in fact $X/G$ is a Riemann surface. I think condition 2) will give us the fact that the space is hausdorff, and 1) says that for every element we can find a neighborhood where the projection is a bijection  and these are going to be the open sets to construct our riemann surface, but i cant seem to find the coordinate charts, i know i can find coordinate charts in $X$ and i can send $N$ to $X$ but this open set can be partitioned into the different open sets that give $X$ the structure of a riemann surface. So any tips would be appreciated , thanks.

A: Yes, the second statement implies that the quotient (with quotient topology) is Hausdorff.
You can relax the hypotesis requiring that $g(N_1) \cap N_2 \neq \emptyset$ for at most a finite set of $g \in G$ (this is useful when checking the condition for example on complex tori).
The proof of this is a game of intersecting open subsets. Start with the quotient, recall what open subsets are, see what you need on the preimages such that the intersection of the images is empty.
The first statement is properness (in the sense of covering maps) of the action. It implies that the quotient map
$$\pi \colon X \twoheadrightarrow X/G$$
is a covering map and in particular a local homeomorphism.
Let $y = [x] \in X/G$, choose a lift $x \in X$, statement (1) says that there is
a $x \in U \subseteq X$ such that $g(U) \cap U \neq \emptyset$ implies $g = id$.
This in particular gives that if $g_1 \neq g_2$ then
$$g_1(U) \cap g_2(U) = \emptyset.$$
Let $[U] = \pi(U)$ be the image, which is open. Then
$$\pi^{-1}([U]) = \bigsqcup_{g \in G} g(U)$$
which shows that $\pi$ is a covering map. In particular the restriction
$$\pi_{|} \colon U \to [U]$$
is a homeomorphism, and you use those to push charts.

I have been a bit sketchy,
but you can find all this in any book on covering maps.


text:
Q: IIS 7.0: Why does Require Client Certificates cause error 500 and "page cannot be displayed" I have two Windows 2008 x86 servers running IIS 7.0, one site on each server; both sites are SSL-enabled, using DoD-issued certificates.  Both sites are accessible via https over port 443, but fail the moment Client Certificates are set to Require or Accept. IIS log records error 500.0.64 but nothing else.
I have several Windows 2008 IIS 7 x64 servers that require client certificates and they are working as expected; it's just the two x86 servers that are being problematic.

A: The solution can be found here and is related to MS KB977377. The choices are

*

*Remove MS update KB977377

or

*

*Change the vlaue of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\DisableRenegoOnServer to 0


text:
Q: Split array of messages into conversations I'm building a comment/messaging system for a website, and I've ran into a problem regarding the messages.
When i go to an item i have for sale on my website, I received all the messages that is on the item. I'm allowed to see all messages, since people on the item can only message me.
The problem is splitting the messages up into conversations, as I don't want the messages mixed together.
Each message has a sender with an id referring to the user, and a receiver, also with an id.
I've tried splitting it up into subarrays with all the messages from one sender, but that doesn't include the messages I've messaged back.
var messages = data.reduce(function (buckets, item) {
    if (!buckets[item._sender._id]) {
        buckets[item._sender._id] = [];
    }
    buckets[item._sender._id].push(item);
    return buckets;
}, {});

$scope.messagesBucket = _.values(messages);

If i console log the messagesBucket it looks like this
[Array[x], Array[y]] // each array is a conversation
  >0: Array[z] // each conversation is array of messages, but they don't include the ones i sent, which is my problem
  >1: Array[q]
...

So my problem is I don't know how to split up all the messages into conversations.
Using lodash is a bonus!
Edit (Message data):
[
{
"_id": "5602858bb1f8f5ee05078ee0",
"_item": "5602858bb1f8f5ee05078ed9",
"content": "Det var billigt.",

"_sender": {
"_id": "56028589b1f8f5ee05078ec2",
"firstName": "Ole",
"lastName": "Wedel",
"image": "URL"
},

"_receiver": {
"_id": "56028589b1f8f5ee05078ec1",
"firstName": "Knud",
"lastName": "Larsen",
"image": "URL"
},
"__v": 0,
"timestamp": "2015-09-03T10:57:15.918Z"
},

{
"_id": "5602858bb1f8f5ee05078ee1",
"_item": "5602858bb1f8f5ee05078ed9",
"content": "Jeg vil lige tænke over det",

"_sender": {
"_id": "56028589b1f8f5ee05078ebe",
"firstName": "Oscar",
"lastName": "Andersen",
"image": "URL"
},

"_receiver": {
"_id": "56028589b1f8f5ee05078ec1",
"firstName": "Knud",
"lastName": "Larsen",
"image": "URL"
},
"__v": 0,
"timestamp": "2015-04-14T10:57:15.918Z"
},

{
"_id": "5602858bb1f8f5ee05078ee3",
"_item": "5602858bb1f8f5ee05078ed9",
"content": "Det går nok. Jeg har også andre jeg kan sælge til.",

"_sender": {
"_id": "56028589b1f8f5ee05078ec3",
"firstName": "Troels",
"lastName": "Sørensen",
"image": "URL"
},

"_receiver": {
"_id": "56028589b1f8f5ee05078ec1",
"firstName": "Knud",
"lastName": "Larsen",
"image": "URL"
},
"__v": 0,
"timestamp": "2014-11-12T11:57:15.918Z"
},

{
"_id": "5602858bb1f8f5ee05078eed",
"_item": "5602858bb1f8f5ee05078ed9",
"content": "Arh, jeg bliver nok nødt til at springe fra...",

"_sender": {
"_id": "56028589b1f8f5ee05078ec1",
"firstName": "Knud",
"lastName": "Larsen",
"image": "URL"
},

"_receiver": {
"_id": "56028589b1f8f5ee05078ec2",
"firstName": "Ole",
"lastName": "Wedel",
"image": "URL"
},
"__v": 0,
"timestamp": "2014-05-22T10:57:15.919Z"
}
]

A: So, in short, you need to group your messages by each unique sender-receiver pair. "Unique pair" means that A+B is the same as B+A; in my code I sort them so the pair is always in the same form.
This will do:
function groupConversations(messages) {
    return _.groupBy(messages, function(msg) {
        return _.sortBy([msg._sender._id, msg._receiver._id]).join(' ');
    })
}

A: Thanks for you response, i solved it my self after some time with the following code
function getItemMessages() {
            api.getItemMessages($scope.item._id)
                .success(function (data, status) {
                    if (status === 200) {
                        // push all messages into seperate conversations
                        var conversations = data.reduce(function (buckets, message) {
                            // if the message is from the creator, don't add it to it's own bucket
                            if (message._sender._id === $scope.user._id) return buckets;
                            if (!buckets[message._sender._id]) {
                                buckets[message._sender._id] = [];
                            }
                            buckets[message._sender._id].push(message);
                            return buckets;
                        }, {});

                        // find the messages by the owner, and push them into the conversation it belongs to
                        var keys = _.keys(conversations);
                        for (var i = 0; i < data.length; i++) {
                            if (data[i]._sender._id === $scope.user._id) {
                                var index = keys.indexOf(data[i]._receiver._id);
                                var key = keys[index];
                                var conversation = _.get(conversations, key);
                                conversation.push(data[i]);
                            }
                        }

                        $scope.messagesBucket = _.values(conversations);
                        if ($scope.messagesBucket.length > 0) {
                            $scope.changeCon($scope.messagesBucket[0]);
                        }
                    }
                });
        }


text:
Q: Exact match for all fields in table with excel in Talend I have a table and an excel wherein I have to compare values for all the fields. If there is a mismatch in the fields with the excel for that row in that column then it should highlight which column is a mismatch with the table field.I m getting all the columns in the rejected instead of only a column with differed value i.e. here only my row 2, column 4 is different from the table. Here is my excel and the table structure. Also I have attached the output needed. Excel Input :

Table Input :

Job Design :
TMAP Design :

Expected Output :

A: Your mapping seems correct, debug your work following these stemps:

*

*Make sure that data types are same for both inputs

*Visualize each input using a tLogRow, check out if there is some whitespaces around fields.

*There is a check box in the advanced settings of your input components to trim data and get rid of white spaces.

For the output, Talend cannot highlight cells or color it, think about something else, you can write in a new column the indeces of the unmached cells.

A: THIS IS RESOLVED. I put the data into other table and did a case query and joined the other table with the first table.


text:
Q: Cross platform library for mobile microphone in iOS or Android I'm developing an app in Android, that records a voice from a microphone and sends it over WIFI. For recording I use Audiorecord and Audiotrack. Because Android doesn't provide a low latency, I was looking for an audio library, which provide low latency and are cross platform capable for a later iOS implementation.
Right now I stopped by:

*

*libpd

*portaudio

*OpenAL Soft

My questions are:

*

*Which of those libs is most recommended or easier to implement in my case? maybe any implementation examples?

*When I broadcast a raw Audio data, which i recorded via Audiorecord, how can i filter own Audio-packets, which I produced? Should I send an ID with each Audio packet and filter by Auditrack?
thx
Vikkes

A: I've been looking into this question for a couple days now, and honestly I've found that everywhere I look into low latency android recording, there doesn't seem to be a consistent outcome for all android versions, nor even consistencies between physical devices.
This article was published as recently as Nov 2015 and details pretty well what I've been able to find as a whole with low latency recording with Android.
As far as what library to use, and what is considered to be easiest is opinion really, and not what SO normally handles. Personally I use OpenAL for my projects, but latency hasn't been an issue for me. If it were, I'd probably opt for portaudio because it would be easier to integrate Steinberg's ASIO drivers which would make Windows development easier. For OSX, core audio does not seem to require the same type of drivers for low latency that Windows does.
So to answer your question, I don't believe that any of the libraries listed would work low latency for every OS. No matter which one you use you'll probably have to support platform specific functionality.
The article I listed does suggest that there is a paid for library, however, which may work, but since I have not used it, I can't form an opinion on it.


text:
Q: Owl Carousel 2 with mousewheel.js and no loop I'm using Owl Carousel 2 with mousewheel.js and it's working just fine.
I also managed to make it work setting loop: false
My problem comes when I scroll to the last or the first slide: my mouse stops working and I can not scroll over the page unless my mouse is outside the carousel space. How can I make the mouse work scrolling over the page as usual when I go to either the first or the last slide?
Should I detach and re-attach mousewheel event listener everytime I go to the end or the begining of the carousel?
Here is my code so far:
           let owl = document.getElementsByClassName('owl-stage'),
                nestedChildren = $(this).find('.owl-item').length;

            owl[0].addEventListener('mousewheel', e => {
                var activeSlideIndex= $(this).find('.owl-item.active').index() + 1;

                if (e.deltaY > 0 && nestedChildren > activeSlideIndex) {
                    $('.owl-carousel').trigger('next.owl', [0, 300]);
                } else if (e.deltaY < 0 && nestedChildren > activeSlideIndex) {
                    $('.owl-carousel').trigger('prev.owl', [0, 300]);
                }
                e.preventDefault();
            }, false);

A: Before your if else statement, check if you're on the first/last slide and if the scroll direction is trying to scroll out of the carousel. If so, break out of the eventListener and have the scroll wheel behave as normal. Otherwise, continue into your existing if else statement.


text:
Q: Execute SET statement in EntityFramework context before call Query I have the following code script:
using (var context = new DatabaseContext())
{
    var records = context.GetData();
}

I need to adjust some SQL Server "SET STATEMENT ON|OFF" before call context.GetData()
using (var context = new DatabaseContext())
{
    // EXAMPLE =======> SET DATEFORMAT dmy
    context.?????? // How?

    var records = context.GetData();
}

Is it possible?

A: context.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");


text:
Q: Dune debugging - OCaml I know of the OCaml debugging tool (first compile with ocamlc -g <file>, then run ocamldebug <output>) and also the function call tracing feature in the toplevel (both covered here). However, I can't seem to find anything about debug builds with dune. Is this possible? Can someone point me in the right direction? Thank you!

A: The -g flag is present by default in all build profiles, so the short answer is that you don't need to do anything. As a pro tip, if you want to see what flags are set by default use
dune printenv .

or for the given building profile, e.g., for release,
dune printenv --profile release .

In a general case, flags are added using flags, ocamlc_flags, and ocamlopt_flags fields that are accepted by env, library, executable, and executables stanzas and have the corresponding scopes. If you want your flag to be applied globally you need to add the corresponding flag field to env stanza, e.g.,
(env
 (release
  (ocamlopt_flags (:standard -O3))))

Here :standard expands to the standard set of flags.
It is also worth to know that OCaml native executables (the executables compiled to machine code using ocamlopt) do not work with ocamldebug. You can use either gdb, which OCaml supports pretty well or use bytecode executables.


text:
Q: TKinter button avoid double click I have a script that enables a Power supply after the user click "ONLY ONE TIME" the "START TEST" button, right after, I disable the button to avoid the "double click, however, I have noticed that "some how" if user perform a "double click" my application launch a second operation.
def starttest():
    Button(main, text="START TEST", font=("Tahoma", 21), height=1, width=24,
    command=starttest, state=DISABLED).place(x=55,y=40)
    PS = serial.Serial('COM1', 9600, timeout=.1)
    ##my code here ...

Does anyone have an idea what should I do to prevent this happen?

A: Each time you call starttest() function by pressing the inherent button, a new button widget is created: that is why it looks like you are able to click indefinitely on the falsely "same" button.
You should create that button somewhere else in your program:
...
power_supply_btn = Button(... text="START TEST", command=starttest ...)
power_supply_btn.place(x=55,y=40)
...

Then configure the state of that button in your starttest() callback using the configure() function:
def starttest():
   global power_supply_btn
   power_supply_btn.configure(state=DISABLED)


text:
Q: Parallax effect for a footer in android Is there a way to implement footer parallax effect in Android? I know it's possible to implement header parallax with CoordinatorLayout + AppBarLayout. I wonder if it's possible to make a scroll animation of footer view like here https://codepen.io/hudsonmarinho/pen/FHGeK

A: I implemented that by adding a fake transparent element in the adapter of RecyclerView. The height of the fake element should be equal to the footer height. The footer view should be placed above RecyclerView in a FrameLayout


text:
Q: Is the "Doctor Who" spacetime affected by Hawking's chronology protection mechanism? Recently, there has been a paper1 (and an accompanying layman-ized white paper2) on "Traversable Achronal Retrograde Domains In Spacetime", TARDIS for short. It proposes a spacetime geometry that contains closed timelike curves.
Now, Hawking once proposed3 a mechanism that apparently causes all closed timelike curves to more or less destroy themselves. Basically, quantum fluctuations cycle through the curve and build upon themselves (in a sense, they overlay with their "past selves"), leading to a divergent expectation value for the energy-momentum tensor.
The media (which has dubbed it the "Doctor Who spacetime") seems to have caught on to this paper as the next time machine. Usually, the term "closed timelike curve" is associated with time machines because of the causality violations a CTC can cause.
Is this really possible? Or does Hawking's mechanism protect this system from a causality violation, destroying the CTCs in it?
1. arXiv:1310.7985 [gr-qc]; "Traversable Achronal Retrograde Domains In Spacetime", Benjamin K. Tippett, David Tsang
2. arXiv:1310.7983 [physics.pop-ph]
3. Hawking, S. W. (1992). Chronology protection conjecture. Physical Review D, 46(2), 603.

A: The Chronology Protection Conjecture is an entire bundle of rough theorems, counterexamples and conjectures. Hawking's original paper on the topic hinges on two main arguments :

*

*That compactly generated closed timelike curves (aka "a time machine", roughly) will violate the energy conditions.

*That a Cauchy horizon (the part of spacetime where the time travel starts being possible) will always collapse due to quantum effects

A few more arguments, more or less valid, exist that make time travel hard to solve (such as stability or non-uniqueness of the development of spacetime), but those are the two big ones. The first one is somewhat questionable, as the definition of "compactly generated" may not include all possible spacetimes (cf. Ori, Soen and Krasnikov on those topics), and the energy conditions lately have shown themselves to not necessarily be that important. If it holds up though, this spacetime would not violate that theorem, as it quite clearly states that the energy conditions are violated.
As for the second part, the conclusion lists it as an unsolved problem of this spacetime. As far as I know, quantum instability of the Cauchy horizon has not been applied to many spacetimes (roughly just Misner space and various wormhole spacetimes). It is hard to say if it would prevent this time machine, as there is no general theorem that you can readily apply.

A: Is this really possible?
No.
Or does Hawking's mechanism protect this system from a causality violation, destroying the CTCs in it?
No.
Hawking's chronology protection conjecture is redundant because time travel is science fiction, because there is no forward travel through time, and no backward travel through time, because there is no motion through spacetime. You move through space over time, and we depict this as your world line. But a world line isn't something you can point to in the clear night sky. It's an abstract thing. It doesn't actually exist. And you don't move up this world line, or along it. It's a line in a static "all times at once" depiction of space and things and their motion, and the map is not the territory. In similar vein you don't go round a closed timelike curve. See how the Wikipedia article says a CTC "is a world line in a Lorentzian manifold, of a material particle in spacetime that is 'closed', returning to its starting point. This possibility was first raised[citation needed] by Kurt Gödel in 1949". There's nothing much wrong with that. But check out A World Without Time: The Forgotten Legacy of Gödel and Einstein. See this page in it, where author Palle Yourgrau says Wheeler conflated a circle with a cycle:

IMHO he's correct. You don't move round that CTC. There is no way you can move such that everything else in this universe not only moved back to where it was, but never moved at all. Your 24-hour CTC doesn't describe some Groundhog day which you live over and over again. It describes some causeless Mayfly day, where your life is 24 hours long and you're born from your own egg. There is no opportunity for causality violation, and no need for any chronology protection conjecture.


text:
Q: How to prevent users filesharing on an openvpn network (all traffic redirected through tunnel set to on) I'm in the process of setting up an openvpn service for fellow friends (10 - 50) who live in remote countries and would like to get access to various websites. I've got it working great for me but before I let anyone on I want to prevent filesharing programmes from using my server for obvious reasons. Whilst I trust my friends to be law abiding citizens it's all too easy for them to forget that they have the tunnel switched on and start downloading something they shouldn't be.
How can I go about preventing this or limiting this? I've heard it can be tricky. I've heard of squid. Can that help? I could create a whitelist perhaps - it's only 20 or so sites people can't access so it's feasible (not ideal though).
Whilst I'll be offering this to friends, associates, etc., I'll be doing it as a limited company and will explain this to any users who sign up and clearly state it in the TOS. It's a very small gig, but i still have to be careful.

A: Have a look at:

*

*l7-filter - Application Layer Packet Classifier for Linux

*IPP2P - IPP2P is a netfilter extension to identify P2P filesharing traffic.

A: If it's just for websites you could block all non-port-80 traffic.
In fact, if it's just for websites, you could make it a secure proxy server.


text:
Q: How to PATCH an entity with a composite primary key? I have an entity with a composite primary key, and I can retrieve a single instance of it using:
GET https://example.com/service/Contacts(Foo=3,Bar=18)

How can I update an instance of it? I tried a PATCH using the same address:
PATCH https://example.com/service/Contacts(Foo=3,Bar=18)

But I get the next error:
{
    "error" : {
        "code" : "",
        "message" : "The request is invalid.",
        "innererror" : {
            "message" : "key : Expected literal type token but found token 'Foo'.\r\n",
            "type" : "",
            "stacktrace" : ""
        }
    }
}

What does this error mean?
I also tried without the property names, but I get another error:
PATCH https://example.com/service/Contacts(3,18)

Cannot create an abstract class. Description: An unhandled exception occurred during the execution of the current web request. Please review the stacktrace for more information about the error and where it originated in the code.

Any idea how can I do a PATCH in this case?
Thank you.

A: May be I am too late to the party but here it goes for PATCH
Note, that this is OData v6 (System.Web.OData) and Entity Framework with manual model setup. I think, previous version of OData didn't support this out of box.
In the controller, action Patch must have arguments that composed from 'key'+{ModelPropertyName}. Considering your model having properties Foo and Bar, the controller action should be as following.
public async Task<IHttpActionResult> Patch([FromODataUri] int keyFoo, [FromODataUri] int keyBar, Delta<FooBarModel> modelDelta)

Note that casing on the arguments don't matter. You can have them like KeyFoO if you want. But it is really matter on the URL

PATCH https://example.com/service/Contacts(Foo=3,Bar=18)

Here casing is matter. This wouldn't work

PATCH https://example.com/service/Contacts(foo=3,bar=18)

Order don't matter, this will work

PATCH https://example.com/service/Contacts(Bar=18, Foo=3)

This doesn't work
PATCH https://example.com/service/Contacts(3,18)


text:
Q: Safari cannot connect to local URL: http://127.0.0.1:5000 I try to run this simple flask hello word code:
app = Flask(__name__)
@app.route("/")
def hello_world():
    return "
Hello, World!
"

but safari doesn't want to connect to the url given by Flask (http://127.0.0.1:5000).
I'm using MAC OS M1

A: You should add at the bottom:
if name == "__main__":
      app.run(debug=true)


text:
Q: How to use List in Hibernate XML mapping? I have Department and Employee entities, I want to map them as one to many.
How can I use List in XML mapping instead of Set? I found this code from Internet, but when execute "from Department", the error is "Repeat property department_id in Employee.department", but if I remove the <index> in department, it's will
be "Unable to read XML".
Department.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 2, 2015 7:14:52 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="emp.entity.Department" table="department" schema="dbo" catalog="Emp" optimistic-lock="version">
        <id name="departmentId" type="long">
            <column name="department_id" />
            <generator class="assigned" />
        </id>
        <property name="deptName" type="string">
            <column name="dept_name" length="50" not-null="true" />
        </property>
        <list name="employees" table="Employee" inverse="true" cascade="all" >
            <key>
                <column name="department_id" />
            </key>
            <index column="department_id"></index>
            <one-to-many class="emp.entity.Employee" />
        </list>
    </class>
</hibernate-mapping>

Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 2, 2015 7:14:52 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="emp.entity.Employee" table="Employee" schema="dbo" catalog="Emp" optimistic-lock="version">
        <id name="employeeId" type="int">
            <column name="employee_id" />
            <generator class="assigned" />
        </id>
        <many-to-one name="department"  class="emp.entity.Department" fetch="select">
            <column name="department_id" />
        </many-to-one>
        <property name="firstname" type="serializable">
            <column name="firstname" />
        </property>
    </class>
</hibernate-mapping>

A: As it says, there has to be distinct two columns for child item identifier and index of the child in the list, so your list definition should be:
<list name="employees" inverse="true" cascade="all" >
        <key>
            <column name="department_id" />
        </key>
        <index column="other_column_to_keep_the_order_of_the_element_in_the_list"></index>
        <one-to-many class="emp.entity.Employee" />
</list>

If you just need the elements to be on a list and do not need to have their order kept in the database, you can declare a <bag> instead of a <list>.


text:
Q: In react bootstrap how do I show the contents of an array in an html table I have an array that I add to, each time a button is pressed.  That part appears to work.  When I output it to a console, I can see that each one is getting added.
  const addToPool = () => {
    diePool[poolCount] = (
      <die
        type={diceType}
        number={diceNumber}
        adjuster={diceAdjuster}
      />
    );
    poolCount++;
  };

How do I loop through and display that in my html table after my form?
return (

        <Form>
            <Button onClick={addToPool} aria-controls="diceRoll" aria-expanded={open} variant="secondary" size="sm">
              Add to Pool
            </Button>
          </ButtonToolbar>

        </Form>
        <Fade in={open}>

            The result is: {randNum}

        </Fade>

Dice Pool

          Type
          Number
          Adjuster

  );
}

export default App;

A: inside your body tag, you can iterate through an array using the map method (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map)

  {dice.map((item,index) => {
    return(

        {item.key1}
      etc...

   )})}

A: In order for React to update the user interface to reflect changes, it expects you to notify it that a change has been made. You do this my modifying the state of your component. In your addToPool method, you are modifying a local variable called diePool. That's just a member variable of the control object, not the state, and React won't know you've made a change.
Instead, modify the state with something like this:
const addToPool(diceType, diceNumber, diceAdjuster) {
  this.setState(prevstate => {
    return {
      diePool: prevstate.diePool.push(
        { type: diceType, number: diceNumber, adjuster: diceAdjuster }
      )
    }
  });
}

For this to work, your component will have to have an initial state to work with. You create this in the constructor:
constructor(props) {
  this.state = { diePool: [] };
}

Now, whenever your code calls addToPool, the state will be updated and through setState, React will know about it and call the render method as needed.
In your render method, you will need to consult the state to place the dice rolls in your table. You can do so by using map over your array of dice rolls:

  // ...snip...

    {this.state.diePool.map((roll, index) => {

        {roll.type}
        {roll.number}
        {roll.adjuster}

    })}

(Please note the use of index here to make sure that each table row has a unique index - this is a requirement for React to be able to update table rows individually when it can.)
What's important here is that the component state is a crucial concept in React. If you modify something and you expect React to react (ha!) to it, you'll have to modify the state through setState (not by modifying this.state directly). That's the only way React will know about it. React will then work its magic and call the render methods of your component and its children, as necessary.

A: I figured it out and posting it here in case others have trouble:
declared a counter:
const [poolCount, setPoolCount] = useState(0);

Created my addToPool:
  const addToPool = () => {
    setDiePool([
      ...diePool,
      {
        dp1 : poolCount,
        dp2 : diceType,
        dp3 : diceNumber,
        dp4 : diceAdjuster
      }
    ]);

    setPoolCount(poolCount+1);
  };

Call my addToPool when I click the button:
    <Button onClick={addToPool} aria-controls="diceRoll" aria-expanded={open} variant="secondary" size="sm">
    Add to Pool
    </Button>

Then create my table and loop:

Dice Pool

          #
          Type
          Number
          Adjuster

         {diePool.map(die => (
{die.dp1}	{die.dp2}	{die.dp3}	{die.dp4}
))}


text:
Q: Grabbing information from a JSON file w/ Java http://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key=C1C2692961278F5A77124973E0ACA799&steamid=76561198170248415&format=json
^^ That is the JSon URL, I just want it to output basic things for now I.E "playtime_2weeks": 5398,
"playtime_forever": 47551,
those ints '5398' and '47551'
This is my class thus far
package org.zach.csgo.record;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {
    public static String key = "C1C2692961278F5A77124973E0ACA799";
  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key="+key+"&steamid=76561198170248415&format=json");
    System.out.println(json.toString());
//What do I put here to just get info :P
  }
}

I believe this is enough information I apologize if it's not. I made this mistake the first time I asked a question on these forums!

A: Look at this working example but most important look at this site http://www.json.org/ and try to understand structure of JSON, it isn't complicated but it takes some time to 'feel' JSON.
public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key="+key+"&steamid=76561198170248415&format=json");
    System.out.println(json.toString());

    JSONObject response = json.getJSONObject("response"); //you get response, it's Json Object
    int totalCount = response.getInt("total_count");   //total_count, it's name/value pair total_count/5
    JSONArray games = response.getJSONArray("games");  //games, it's Json Array

    System.out.println("Games total: " + totalCount);

    for(int i = 0; i < games.length(); i++){  //we're iterating through the array of Json Objects
        JSONObject game = games.getJSONObject(i); //every game is Json Object

        int appId = game.getInt("appid");   //in every game we have 5 key/value pairs appid/730, etc...
        String name = game.getString("name");
        int playtime2weeks = game.getInt("playtime_2weeks");
        int playtimeForever = game.getInt("playtime_forever");
        String imgIconUrl = game.getString("img_icon_url");
        String imgLogoUrl = game.getString("img_logo_url");

        System.out.println("appid: " + appId + " name: " + name + " playtime2weeks: " + playtime2weeks + " playtime_forever: " + playtimeForever);
    }

A: http://www.json.org/javadoc/org/json/JSONObject.html
That is a link to the JSONObject API. It specifies several methods you could use to get data from your object. Look for the ones that start with get*


text:
Q: getting file name from for %%i variable I had a script that converts all mkvs in a folder to mp4s using ffmpeg. The downside is that it left the .mkv extension and just added .mp4 (eg: file.mkv.mkp4). I know %~n can be used to get a name without the extension, but I can't seem to figure it out.
Here's my original script:
for %%i IN (*.mkv) DO (ffmpeg -y -ss 00:00:00 -threads 6 -i "%%i" -vcodec copy -f mp4 -strict experimental -acodec aac -ab 128k -ac 2 "%%i.mp4")

Here's what I've tried:
for %%i IN (*.mkv) DO (ffmpeg -y -ss 00:00:00 -threads 6 -i "%~ni.mkv" -vcodec copy -f mp4 -strict experimental -acodec aac -ab 128k -ac 2 "%~ni.mp4")

A: Percent signs of loop variables must be doubled in batch scripts, so you have to use %%~ni instead of %~ni. See the Examples section in the documentation.