text:
Q: Header was shaking when scrolling down Note: Please try to use mousewheel when scrolling down. Also please be nice to mousewheel. Move it slowly.
I have a little question about scrolling. I am trying to reduce the header height when page scrolled to the down as most creative websites do.
But in this case when I was tried to scroll down with mouse screen was shaking. Also sometimes its do with scrolling with mousewheel. All files added to the js fiddle. Please look at jsfiddle below. I hope I can express myself. Thanks in advance.

$(document).ready(function () {
 $(window).scroll(function () {
    if ($(window).scrollTop() >= 30) {
      $('.header-bottom').addClass('sticky');
      $('.header-bottom').css('line-height','80px');
    } else {
      $('.header-bottom').removeClass('sticky');
      $('.header-bottom').css('line-height','160px');
    }
  });
});
body {
  margin: 0;
}
.header-top {
  line-height:30px;
  background: blue;
}
.header-bottom {
  line-height:160px;
  background: red;
  -webkit-transition: .45s;
  -moz-transition: .45s;
  -ms-transition: .45s;
  -o-transition: .45s;
  transition: .45s;
}
.sticky {
  position: sticky;
  top:0;
  width: 100%;
}

.content {
  margin-top: 20px;
}

.content > div {
  margin-bottom: 100px;
}

Content

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora nobis, suscipit consequuntur! Neque modi libero praesentium rerum, pariatur, assumenda obcaecati laudantium officia iste excepturi, molestias quibusdam quae sed nihil laborum.

Necessitatibus, omnis odit ipsam, repudiandae beatae minima! Voluptates molestias vitae fuga officiis, aperiam earum quas laboriosam cupiditate hic vero reiciendis, numquam corporis, assumenda rem iure expedita animi magnam perferendis delectus.

Eum odit hic delectus vel facilis nisi cupiditate ad enim recusandae ex, commodi sunt ullam distinctio, architecto quam nulla cumque possimus nihil qui unde magni provident ratione obcaecati fuga. Beatae.

Iusto repellendus dolore atque architecto consequatur magni nulla animi possimus reiciendis, soluta similique recusandae voluptate reprehenderit, aspernatur repellat ab provident facere magnam sit unde, accusantium explicabo. Ducimus odit aliquid, minima!

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

A: do position: fixed; instead of position: sticky; in the sticky class

 $(window).scroll(function () {
    if ($(window).scrollTop() >= 30) {
      $('.header-bottom').addClass('sticky');
      $('.header-bottom').css('line-height','80px');
      $('.content').css('margin-top','120px');
    }else {
      $('.header-bottom').removeClass('sticky');
      $('.header-bottom').css('line-height','160px');
      $('.content').css('margin-top','20px');
    }
  });
body {
  margin: 0;
}
.header-top {
  line-height:30px;
  background: blue;
}
.header-bottom {
  line-height:160px;
  background: red;
  -webkit-transition: .45s;
  -moz-transition: .45s;
  -ms-transition: .45s;
  -o-transition: .45s;
  transition: .45s;
}
.sticky {
  position: fixed;
  top:0;
  width: 100%;
}

.content {
  margin-top: 20px;
  -webkit-transition: .45s;
  -moz-transition: .45s;
  -ms-transition: .45s;
  -o-transition: .45s;
  transition: .45s;
}

.content > div {
  margin-bottom: 100px;
}

Content

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora nobis, suscipit consequuntur! Neque modi libero praesentium rerum, pariatur, assumenda obcaecati laudantium officia iste excepturi, molestias quibusdam quae sed nihil laborum.

Necessitatibus, omnis odit ipsam, repudiandae beatae minima! Voluptates molestias vitae fuga officiis, aperiam earum quas laboriosam cupiditate hic vero reiciendis, numquam corporis, assumenda rem iure expedita animi magnam perferendis delectus.

Eum odit hic delectus vel facilis nisi cupiditate ad enim recusandae ex, commodi sunt ullam distinctio, architecto quam nulla cumque possimus nihil qui unde magni provident ratione obcaecati fuga. Beatae.

Iusto repellendus dolore atque architecto consequatur magni nulla animi possimus reiciendis, soluta similique recusandae voluptate reprehenderit, aspernatur repellat ab provident facere magnam sit unde, accusantium explicabo. Ducimus odit aliquid, minima!

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

A: You add
. After header-top and header-bottom move into

And add css;
.header { height:190px;}
If you using position:fixed insted position:sticky this could be useful.
The problem will be solved.

$(document).ready(function () {
 $(window).scroll(function () {
    if ($(window).scrollTop() > 30) {
      $('.header-bottom').addClass('sticky');
    } else {
      $('.header-bottom').removeClass('sticky');
    }
  });
});
body {
  margin: 0;
}
.header {
  height:190px;
}
.header-top {
  line-height:30px;
  background: blue;
}
.header-bottom {
  line-height:160px;
  background: red;
  -webkit-transition: .5s;
  -moz-transition: .5s;
  -ms-transition: .5s;
  -o-transition: .5s;
  transition: .5s;
}
.sticky {
  position: fixed;
  line-height:80px;
  top:0;
  width: 100%;
}

.content {
  margin-top: 20px;
}

.content > div {
  margin-bottom: 100px;
}

.margin {
  margin-top:190px;
}

Content

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora nobis, suscipit consequuntur! Neque modi libero praesentium rerum, pariatur, assumenda obcaecati laudantium officia iste excepturi, molestias quibusdam quae sed nihil laborum.

Necessitatibus, omnis odit ipsam, repudiandae beatae minima! Voluptates molestias vitae fuga officiis, aperiam earum quas laboriosam cupiditate hic vero reiciendis, numquam corporis, assumenda rem iure expedita animi magnam perferendis delectus.

Eum odit hic delectus vel facilis nisi cupiditate ad enim recusandae ex, commodi sunt ullam distinctio, architecto quam nulla cumque possimus nihil qui unde magni provident ratione obcaecati fuga. Beatae.

Iusto repellendus dolore atque architecto consequatur magni nulla animi possimus reiciendis, soluta similique recusandae voluptate reprehenderit, aspernatur repellat ab provident facere magnam sit unde, accusantium explicabo. Ducimus odit aliquid, minima!

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.


text:
Q: First time using javascript for a clicker game that doesn't work this is my first time using javascript.
I basically wanted to create a "clicker" game.
The target of the game is clicking an image to make points.
I've tryed fixing it by myself and looking on the internet but I found nothing.
What's is cauising the problem ?
Basically everytime I open the page the score is already set to 1 but when i click on the image it does not increases.

Score:

Time: 2

While this is the script that increases the score

A: Your score is initially one because you call your function when you use
document.write(scorecounter());
This will increase the value of score then return it, thus displaying the number 1.
The reason why your click doesn't increase the value of score is because you're not displaying the score again. At the moment you are simply just displaying the score when the page loads. Then when you click your image the value of score is increased but you're not displaying it to the DOM (ie the page) again. To display the value of score to the page you can use .innerHTML on the element where you want the score to appear.
See a working example below:

var score = 0;
function scorecounter() {
  score++;
  document.getElementById('score').innerHTML = score; // Set the element with the id 'score' to have the value 'score' inside of it. Also note that .innerHTML can be replaced with .textContent to help resolve XSS vulnrabilities.
}
/* css - ignore this */

.red {
  background-color: red;
  height: 50px;
  width: 100%;
  color: white;
  text-align: center;
  cursor: pointer;
}

Score: 0

  Click me (imagine this as your image)

Edit: As @BrandonBuck pointed out, .innerHTML is prone to cross-site scripting (XSS). To help avoid this using .textContent instead of .innerHTML can help avoid this.

A: Here is a JSFiddle of it working.
So there are quite a few things you're doing that you probably shouldn't be doing. And it's not necessarily your fault. JavaScript is old, and there are a lot of resources online and some of those resources are bound to be bad. Not to mention, I have no idea where you started from so you could have been given some really old example or what-have-you.
So where to begin, let's see... we don't use document.write anymore. As a matter of fact, when I started using JS about 17 years ago it was not really that common. The problem with document.write is that it's not doing what you think it's doing. When the page is initially parsed that will be executed, and it's going to write whatever you told it to, and that's it. It's done its job and it's over. It will never write again until you reload the page.
As @NickParsons pointed out in his comment, your score "starts" at 1 because you're calling scorecounter in your write statement, so you're incrementing the score and writing it's new value at the same time.
Next, you're using HTML attributes to associate JavaScript actions. This is generally frowned upon in modern web development as we tend to like to keep our JS and HTML pretty separate. I'll show you some examples of how to do that.
Okay, so another thing is global values. Of course in your example it's not necessarily avoidable but we can do some cleaning up for that. So let's take a go. First, let's clean up the HTML. Most of it (aside from the JS) is not bad at all.
this is my first time using javascript. I basically wanted to create a "clicker" game. The target of the game is clicking an image to make points. I've tried fixing it by myself and looking on the internet but I found nothing. What's is causing the problem?
Basically everytime I open the page the score is already set to 1 but when I click on the image it does not increase.

          Score:

          Time: 2

So the biggest thing I've done outside of formatting is remove all the JS code, and change the class on the value spans to <name>-value, so score is a perfectly fine class name, don't get me wrong -- but score-value is more clear about what we're going to put there.
Next thing we need to do is clean up the JavaScript. As a base, it's not bad. But it's not where we want to go. Let's do this in steps. I'm going to start from scratch here since we're going to change it quite a bit. First thing is we have a Game, and our game will have a score associated with it. So let's make a class (class syntax is new, but supported natively by the majority of major browsers in use).
class Game {
  constructor() {
    this.score = 0;
  }
}

Bam. Got our class. What else do we need? Well -- we need to increment our score. So let's do that.
class Game {
  constructor() {
    this.score = 0;
  }

  incrementScore() {
    this.score += 1;
  }
}

Easy enough. Next, we need to render our score, or add it to the DOM (the HTML after it's been processed by the browsers becomes the "DOM" or Document Object Model, which is an API that lets us interact with the page programmatically).
Now, rendering this score could be part of our game, but it's not really -- our game is supposed to be just the game itself. It really shouldn't contain a bunch of other logic. Otherwise we get a super class and we may as well have not tried to do this. But we can make a new class... let's call it UserInterface, since, y'know, it's our UserInterface. Most JavaScript libraries will refer to the HTML/DOM aspect of your app as a "view" or "component," I'm using "user interface" since we're talking about a "game" and the common term there is UI.
class UserInterface {}

Okay, so we need to render text. To do that, we need to fetch the DOM node we want to store the score, and then we need to set it's text to the current score. The UserInterface doesn't know that the score is, the Game does so we need to pass some data around.
class UserInterface {
  renderScore(score) {
    const el = document.querySelector('.score-value');
    el.textContent = score;
  }
}

You see I've used const. For the most part, you can imagine that const does that var does -- it declares a variable. Underneath they work quite differently. Without going in depth about JavaScript variable scoping let me just say that var is old school, and const is new school. const defines not only a variable like var but it also makes it so that it cannot be reassigned. Since we never reassign el in the body of renderScore I made it const. Now, var is old school as I said and its new school alternative is let, which does pretty much the same thing as const (as far as scope goes) but allows you to reassign the value. I encourage you to dive more into why let and const were added but that's beyond this answer.
There is an optimization here -- you see I'm searching for the .score-value element every time I render. This is bad. There are a few approaches I could take here but for the sake of simplicity, let's just do the easiest and get it up front.
class UserInterface {
  constructor() {
    this.scoreValueEl = document.querySelector('.score-value');
  }

  renderScore(score) {
    this.scoreValueEl.textContent = score;
  }
}

As an aside, you may not know what document.querySelector does, but you can think of it as searching the DOM (again, what the HTML page becomes after the browser processes it) for an element that matches the text you pass to it. The term selector comes from CSS, where you define your rules by "selecting" elements. You can select by tag, h3, div, etc.. or you can select by class name (just append a . in front of the class name, like .score-value for class="score-value" elements) or you can select by an ID (just append a # similar to . for class names). You can get more complex but for now, leave it at that. So document.querySelector('.score-value') says, "Hey DOM, can you find some element that has a class "score-value" on it and give it back to me?"
Okay, so now I have the Game to track the score (and other future game elements) and then I have the User Interface to render this stuff to the user. Next, we need to do some interaction. This part can be quite a topic of passing around lots of functions, etc.. so I'm going to keep it relatively simple. With our Game and UserInterface class ready we'll just bind the click to our image and increment the score and render it. So let's give all that a go. First, let's create our new values:
const game = new Game();
const ui = new UserInterface();

// we want to show the score on load, so let's do that
ui.renderScore(game.score);

Okay, so first part down. Now let's handle clicks. Using document.querySelector again to fetch the image:
// see here, we only have one img tag on the page, so I use the tag
// as the selector to find it
const img = document.querySelector('img');

img.addEventListener('click', () => {
  game.incrementScore();
  ui.renderScore(game.score);
});

Okay, so two new things here. addEventListener is the JS way to say "hey element, when the user does X do Y", in this case we say "when the user clicks this image, run this function." So the first value we pass to addEventListener is the name of the event we want to handle and the second value is the function we want to execute when the event is triggered. Now that function, I wrote it as an "arrow function" which is shorthand and means the same thing as function() {}. So () => {} is the same thing as function() {} (there are, again, some differences I'm glossing over because it's out of scope for this answer and you should definitely look those up). So don't be alarmed by the arrow function there, it's simple a JS function we're passing in to call. Notice inside this function we increment the score and then render it.
So the final JS should be something like this:
class Game {
  constructor() {
    this.score = 0;
  }

  incrementScore() {
    this.score += 1;
  }
}

class UserInterface {
  constructor() {
    this.scoreValueEl = document.querySelector('.score-value');
  }

  renderScore(score) {
    this.scoreValueEl.textContent = score;
  }
}

const game = new Game();
const ui = new UserInterface();

ui.renderScore(game.score);

const img = document.querySelector('img');
img.addEventListener('click', () => {
  game.incrementScore();
  ui.renderScore(game.score);
});

Here is a JSFiddle of it working.
Add On
(yes sadly I have more to say)
All that being said, learning JS is easy and accessible. If you'd like to brush up or learn new things, you can head over to CodeAcademy, or if you don't mind some out of pocket expense SkillShare, PluralSight, CodeSchool, and many more offer JavaScript courses.
In addition to learning more about JavaScript, most real-world JavaScript is written with some framework as a starting point. Vue was mentioned to you, so as you feel you're knowledge and comfort increase with JS you should look into Vue. It's great because it features minimum boilerplate (the amount of code necessary to "get started") and offers, essentially, feature parity to other popular solutions. Other solutions are React, Angular, maybe Ember still exists, Meteor (for full stack stuff) and many more. Also, despite it being "on the way out" as more people move away from it, jQuery is still around and still provides a huge set of conveniences instead of working directly with the DOM. So there is always that route as well.
The world of JavaScript is too big, and still growing. So you can really find whatever you want for whatever purpose it serves. There's hundreds of MVC frameworks, component frameworks, DOM wrappers, other basic utils, game engines, and on and on and on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disabling function inside textarea "onKeyUp" I'm trying to disable test() function inside a textarea tag.
onKeyUp="test()" // Not textarea

<textarea id="aaa" onKeyUp="test()"></textarea>

<input type="button" onclick="disable()" value="Disable" />
<input type="button" onclick="enable()" value="Enable" />

How can I disable and enable this test() function.

A: You can use .setAttribute to add and remove the value of any attribute of the selected element, including onKeyUp.
To disable:
// Instead of using:
document.getElementById('aaa').disabled=true;

// try:
document.getElementById('aaa').setAttribute("onKeyUp", "");

To enable:
// Instead of using:
document.getElementById('aaa').disabled=false;

// try:
document.getElementById('aaa').setAttribute("onKeyUp", "test()");

Check the snippet:

<textarea id="aaa" onKeyUp="test()"></textarea>

<input type="button" onclick="disable()" value="Disable" />
<input type="button" onclick="enable()" value="Enable" />


text:
Q: MySQL sort ordered grouped data I have two tables: ticket and ticketRules and i have a query like this:
SELECT * FROM (
    SELECT * FROM ticketRules
    ORDER BY
        date DESC,
        time DESC
) AS myTicketRules
GROUP BY ticketId
ORDER BY ticketId ASC

The first Order By (the one in the subquery) sorts data by date and time so the last ticketrule is always the first.
I group the results by ticketId so I only got the last ticketRule for each ticket.
Now I want to sort the results by ticket but if I do that the first result is also affected and tickets don't have the last ticketrule anymore but the one with the lowest id cause it's ordered by ticketId.
How can I sort only the visible records after I grouped them?

A: There are several issues with your query :

*

*there should be only one ORDER BY clause (that should be placed in the outer query)

*GROUP BY does not do what you think (ie it does not give access to the last ticket)

If you are trying to pull out the full latest record for each ticketId, ordered by ticketId, you can use a correlated subquery as follows :
SELECT
    t.*
FROM
    ticketrule t
WHERE
    t.date = (
        SELECT MAX(date)
        FROM ticketrule
        WHERE ticketId = t.ticketId
    )
ORDER BY t.ticketId

A: you should not use a  group by without aggregation function and for obtain the last value  could use use an aggregation function as max( )
select  ticketId, max(date)
from ticketRules
grouo by ticketId


text:
Q: Watch event for specific object We have an k8s operator (based on kubebuilder) which works as expected, now we need support for listening to secrets on the cluster.
The following code is working however I got event for all the secrets in the cluster which is not efficient,
I WANT to get the event only for specific secret, lets say secret with specific labels/annotation, how we can do it?
func (r *InvReconciler) SetupWithManager(mgr ctrl.Manager) error {
    manager := ctrl.NewControllerManagedBy(mgr).
        For(&corev1alpha1.Inv{}, builder.WithPredicates(predicate.Or(predicate.GenerationChangedPredicate{}, predicate.AnnotationChangedPredicate{}))).
        WithOptions(controller.Options{
        })

    manager = manager.Watches(&source.Kind{Type: &v1.Secret{}}, handler.EnqueueRequestsFromMapFunc(func(a client.Object) []reconcile.Request {
        return r.secretHandler.GetSecret(a.GetNamespace(), a.GetName())
    }))

    return manager.Complete(r)
}

this is the function
func (secretReq secretHandler) GetSecret(namespace string, name string) []reconcile.Request {

    fmt.Println("secret is: ", namespace, "--", name)
    return nil
}

lets say secret like the following and only for this secret (with labels foo: bar )i'll get the event when it was created or modified
apiVersion: v1
kind: Secret
metadata:
  labels:
    foo: bar
  name: mysecret
  namespace: dev
type: Opaque
data:
  USER_NAME: YWRtaW4=
  PASSWORD: dGVzdBo=

Im not talking about an if statement after I got the event as it already bring all the secrets event in the cluster.

A: According to this github source, you should be able to select specific objects (e.g. secrets) with EnqueueRequestForObject. However, it is not possible (yet) to watch only for specific secret CRUD changes.

EnqueueRequestForObject to watch for your CRD resource changes. In
your CRD reconciler, you'd fetch all of the TLS secrets using a label
selector based on the search definition and then run your merge logic
with the matched secrets.
EnqueueRequestFromMapFunc to watch for
secret changes and trigger a reconcile of one or more CRs. In your
mapper function, you'd fetch all of the CRs. For each CR that has a
search definition that matches the passed in secret, you'd create a
new reconcile.Request for the CR, and return the list of requests,
which would trigger your CRD reconciler for each CR that matched.

The cleanest way is using a label selector and then merge the results with your existing code. An example of using a label selector is given in this post:
func GetSecret(version string) (retVal interface{}, err error){
  clientset := GetClientOutOfCluster()
  labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

  listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    Limit:         100,
  }
  secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
  retVal = secretList.Items[0]
  return retVal, err
}

A: This is possible, in a roundabout way. You need to configure the selector into the controller Manager that you use to set up your reconciler.
You can use label or field selectors for this.
You can either set the same selector for all types of objects using DefaultSelector, or you can use SelectorsByObject to have different selectors for different types of objects.
import (
    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/labels"
    "k8s.io/apimachinery/pkg/selection"
    "k8s.io/client-go/rest"
    ctrl "sigs.k8s.io/controller-runtime"
    "sigs.k8s.io/controller-runtime/pkg/cache"
    "sigs.k8s.io/controller-runtime/pkg/manager"
)

func startReconciler(cnf *rest.Config) error {
    mgr, err := ctrl.NewManager(cnf, manager.Options{
        NewCache: func(conf *rest.Config, opts cache.Options) (cache.Cache, error) {
            // Use this selector for everything that is not mentioned in SelectorsByObject
            opts.DefaultSelector = cache.ObjectSelector{
                Label: labels.SelectorFromSet(labels.Set{"foo": "bar"}),
            }
            // Specific selectors per type of object
            opts.SelectorsByObject[&corev1.Secret{}] = cache.ObjectSelector{
                Label: labels.SelectorFromSet(labels.Set{"foo": "bar"}),
            }
            return cache.New(conf, opts)
        },
    })
    if err != nil {
        return err
    }
    r := &InvReconciler{}
    if err := r.SetupWithManager(mgr); err != nil {
        return err
    }


text:
Q: Sequential almost sure continuity implies almost sure continuity Let $(B_t)_{t\in\mathbb{R}}$ be a real stochastic process. $\forall\omega\in\Omega$, let $f_\omega(t) = B_t(\omega)$.
$\forall x\in\mathbb{R}$, $(B_t)_{t\in\mathbb{R}}$ is almost surely continuous at $x$ iff $f_\omega$ is continuous at $x$ for almost all $\forall\omega\in\Omega$.
Define sequential almost sure continuity at $x$ this way: $\forall (x_n)_n\subseteq\mathbb{R}\setminus\{x\}$, such that $x_n \rightarrow x$, it's almost sure that $B_{x_n} \rightarrow B_x$.
$\forall x\in\mathbb{R}$, is it true that sequential almost sure continuity at $x$ implies almost sure continuity at $x$?
If not, then also assume that, $(B_t)_{t\in\mathbb{R}}$ is almost surely continuous on $\mathbb{R}\setminus\{x\}$. That is, $f_\omega$ is continuous on $\mathbb{R}\setminus\{x\}$ for almost all $\forall\omega\in\Omega$. Would that be enough to show almost sure continuity at $x$?


text:
Q: Python zoom clone socket send video frame from client to another client with server as middle man I want to make an application like zoom so that later there will be a client and server. The client will send the opencv video frame to the server and then the server sends the video frame to another client again. But when i run the code a video from clint b is also displayed on client a so the result is like blinking, stop, and just loop old frame.

*

*Server Code

import socket
import sys
import cv2
import matplotlib.pyplot as plt
import pickle
import numpy as np
import struct  # new
import zlib
from PIL import Image, ImageOps
import threading
import concurrent.futures
import imutils
import select

# HOST = socket.gethostbyname(socket.gethostname())
HOST = 'My IP Addr'
PORT = 8080
FORMAT = 'utf-8'
SOCK_LIST = []

def send_frame(frame, conn):
    img_counter = 0
    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
    try:
        while True:

            frame = imutils.resize(frame, width=360)

            frame = cv2.flip(frame, 180)
            result, image = cv2.imencode('.jpg', frame, encode_param)
            data = pickle.dumps(image, 0)
            size = len(data)

            if img_counter % 10 == 0:
                conn.sendall(struct.pack(">L", size) + data)
                # cv2.imshow('client', frame)

            img_counter += 1
    except:
        conn.close()
        if conn in SOCK_LIST:
            SOCK_LIST.remove(conn)
        print(f"[INFO] Client ({addr}) disconnected from server")

def handle_client(conn, addr, lock):
    try:
        print(f"[INFO] Client ({addr}) is connected to the server\n")
        connected = True

        data = b""
        payload_size = struct.calcsize(">L")
        while connected:
            while len(data) < payload_size:
                data += conn.recv(4096)
                if not data:
                    break

            packed_msg_size = data[:payload_size]
            data = data[payload_size:]
            msg_size = struct.unpack(">L", packed_msg_size)[0]
            while len(data) < msg_size:
                data += conn.recv(4096)
            frame_data = data[:msg_size]
            data = data[msg_size:]

            # unpack image using pickle
            frame = pickle.loads(
                frame_data, fix_imports=True, encoding="bytes")
            frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)

            thread_list = []
            # thread_lock = threading.Lock()

            for sock in SOCK_LIST:
                if conn != sock and sock != server_sock:
                    thread_list.append(threading.Thread(target=send_frame,
                                                        args=(frame, sock)))

            for thread in thread_list:
                thread.start()

            # thread.join()
            # sock.sendall(frame)

            # cv2.imshow(f'From {addr}', frame)
            # cv2.waitKey(1)

        # conn.close()
    except:
        conn.close()
        if conn in SOCK_LIST:
            SOCK_LIST.remove(conn)
        print(f"[INFO] Client ({addr}) disconnected from server")

if __name__ == "__main__":
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind((HOST, PORT))
    print("[INFO] Server is starting ...")

    server_sock.listen(2)
    print(f"[INFO] Server is listening on {HOST} port {PORT}")

    while True:
        thread_lock = threading.Lock()
        conn, addr = server_sock.accept()
        SOCK_LIST.append(conn)
        thread = threading.Thread(
            target=handle_client, args=(conn, addr, thread_lock)).start()
        print(
            f"[INFO] Server active connections is {threading.activeCount() - 1}")

*

*Client Code

import cv2
import io
import socket
import struct
import time
import pickle
import numpy as np
import imutils
import threading
import random

# HOST = socket.gethostbyname(socket.gethostname())
HOST = 'Server IP Addr'
PORT = 8080
FORMAT = 'utf-8'
SOCK_LIST = []

def send():
    cam = cv2.VideoCapture(0)
    img_counter = 0

    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]

    while True:
        ret, frame = cam.read()

        frame = imutils.resize(frame, width=360)

        frame = cv2.flip(frame, 180)
        result, image = cv2.imencode('.jpg', frame, encode_param)
        data = pickle.dumps(image, 0)
        size = len(data)

        if img_counter % 10 == 0:
            client_socket.sendall(struct.pack(">L", size) + data)
            # cv2.imshow('client', frame)

        img_counter += 1

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cam.release()

def recv():
    data = b""
    payload_size = struct.calcsize(">L")
    print("payload_size: {}".format(payload_size))

    while True:
        while len(data) < payload_size:
            data += client_socket.recv(4096)
            if not data:
                break

        print(data)
        packed_msg_size = data[:payload_size]
        data = data[payload_size:]
        msg_size = struct.unpack(">L", packed_msg_size)[0]
        while len(data) < msg_size:
            data += client_socket.recv(4096)
        frame_data = data[:msg_size]
        data = data[msg_size:]

        # unpack image using pickle
        frame = pickle.loads(frame_data, fix_imports=True, encoding="bytes")
        frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)

        cv2.imshow('Another client', frame)
        cv2.waitKey(1)

if __name__ == "__main__":
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((HOST, PORT))

    cam = cv2.VideoCapture(0)

    thread_1 = threading.Thread(target=send).start()
    # thread_2 = threading.Thread(target=recv).start()

    data = b""
    payload_size = struct.calcsize(">L")

    while True:
        while len(data) < payload_size:
            data += client_socket.recv(4096)
            if not data:
                break

        print(data)
        packed_msg_size = data[:payload_size]
        data = data[payload_size:]
        msg_size = struct.unpack(">L", packed_msg_size)[0]
        while len(data) < msg_size:
            data += client_socket.recv(4096)
        frame_data = data[:msg_size]
        data = data[msg_size:]

        # unpack image using pickle
        frame = pickle.loads(frame_data, fix_imports=True, encoding="bytes")
        frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)

        cv2.imshow('Another client', frame)
        cv2.waitKey(1)
        #     data = client_socket.recv(4096)
        #     if not data:
        #         print(f"[INFO] Client ({(HOST, PORT)}) is left from the server")
        #     else:
        #         print(data)

The client A can see client B video capture and vice versa


text:
Q: When I create a new directory, create a markdown file with the same name in it I want to create a lot of directories (manually, using the GUI).
I will then want to have inside them a markdown document with the same name as the directory, so this sort of tree:
624466
└ 624466.md
626665
└ 626665.md

How can I automate the .md file creation?

A: I would use inotify API provided by the kernel to monitor filesystem events. There is no need for an indefinite while loop, you can use a tool that uses the interface provided by the kernel to check for any changes on any file.
One of the tools that uses inotify is inotifywait. From man inotifywait :
inotifywait efficiently waits for changes to files using Linux's inotify interface.

It is not installed by default, it is a part of inotify-tools package. You can install it by :
sudo apt-get install inotify-tools

The script i am taking about can take the form :
#!/bin/bash
while IFS= read -r line; do
    parent="${line%% *}"
    child="${line##* }"
    new="${parent}${child}"
    [[ -d $new ]] && touch "$new"/"$child".md
done < <(inotifywait --quiet --monitor --event CREATE,ISDIR /home/tim/test)

You can send it to the background :
./dir_event.sh &

Or perhaps use nohup or disown if you want :
nohup ./dir_event.sh &

*

*inotifywait --quiet --monitor --event CREATE,ISDIR /home/tim/test is the command to monitor the file system events on directory /home/tim/test, we are only interested in CREATE and ISDIR events. We are saving (as line) and then manipulating every new line indicating a relevant event as they happen. Please check man inotifywait to get more idea.

*parent will contain the directory we are monitoring /home/tim/test in this case and child will contain the newly created directory/file. Both are achieved by using bash parameter expansion.

*new is addition of the two to get the absolute path to the newly created entry. As CREATE event will result in creating a file too we need to make sure that new is a directory.

*[[ -d $new ]] checks if new is a directory, if so then we have created the required file inside it.

A: Try this:
#!/bin/bash

for d in */; do
    touch $d/$d.md
done

A: This is what I've ended up using.
while :
do
    for dir in *; do
        if [ "$dir" != "Untitled Folder" ];
        then

            if [ "$(ls "$dir")" = '' ];
            then

                touch "$dir/$dir.md"
            fi
        fi
    done
done

Thanks to @Grammageek, his original post really helped with the for loop concept..


text:
Q: How to show save file dialog in Safari? I need help. I have an angular app and by using DocRaptor want to generate PDF and save it as file. But I cant trigger the dialog to save file in Safari with any method what I have found on Stack Overflow. Those methods open file in current browser tab and replace site html or open file in new tab. No one cant shows the dialog. Here the examples what I have already tried to use. Environment MacOS - EL Capitan. Safari 9.0.3
Solution #1
var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );

Example jsfiddle. Shows file in current tab. Replaces site. But works in Chrome.
Solution #2

Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Solution #3
Export to JSON

and
$scope.saveJSON = function () {
            $scope.toJSON = '';
            $scope.toJSON = angular.toJson($scope.data);
            var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });
            var downloadLink = angular.element('');
                        downloadLink.attr('href',window.URL.createObjectURL(blob));
                        downloadLink.attr('download', 'fileName.json');
            downloadLink[0].click();
        };

Example Code Snippet. Shows the file content instead of document's html.
Solution #4
function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}

Example Code Snippet. Replace document with file content in Safari. Works in Chrome.
And similar Solution #5
function download(text, name, type) {
    var a = document.createElement("a");
    var file = new Blob([text], {type: type});
    a.href = URL.createObjectURL(file);
    a.download = name;
    a.click();
}

Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Also I have tried to use libraries like:
FileSaver - It opens file in Safari instead of document. So you should click Cmd+S. Example.
If we use type 'pplication/octet-stream' the name of file will be unknown or there was be an error 'Failed to load resource: Frame load interrupted'. Issue.
Second library Downloadify - doesnt work in Safari at all. Issue.
Angular library nw-fileDialog - instead of save as it shows choose file. Issue.
DocRaptor has own example with jQuery.
Example with angular in jsfiddle. It works in Chrome but in Safari example doesnt work be cause of error with SAMEORIGIN

Refused to display 'https://docraptor.com/docs' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

But if we reproduce it on server and change url on 'https://docraptor.com/docs.pdf' it works and open file in new tab and automatically download the file so you cant choose a folder and after download user see white empty screen tab in browser. If we specify form target="_self" it will work perfect, but console will have an error 'Failed to load resource:'.
I will appreciate any help with this problem.
Thanks.
Regards.

A: Try using Blob file for this:
// Buffer can be response from XMLHttpRequest/Ajax or your custom Int32 data
function download(buffer, filename) {
  var file = new Blob([buffer], {
    type: 'application/octet-stream' // Replace your mimeType if known
  });
  var fileReader = new FileReader();

  fileReader.onloadend = function(e) {
    var converted = e.target.result;
    converted.name = filename;
    converted.webkitRelativePath = filename;

    var iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    iframe.src = converted;
  };
  fileReader.onerror = function(e) {
    throw new Error('Something is wrong with buffer data');
  };
  fileReader.file = file;
  fileReader.readAsDataURL(file);
}

It basically uses filebuffer and download that as an iframe content. Make sure to hook correct mime type so that safari security system will recieved analyse filetype.

A: Ideally, Solution #2 would be the answer, but the download attribute does not yet have cross-browser support.
So you have to use a <form> to create the download. As you noted, DocRaptor's jQuery example uses this technique.
The SAMEORIGIN error is actually because JSFiddle is running the code in an iFrame with their origin settings. If you run this straight from your Angular application, you shouldn't have any problems.


text:
Q: Server does not accept public key for ssh login without password
Possible Duplicate:
Why am I still getting a password prompt with ssh with public key authentication?

I have ssh access to two sever. One old one and one new one. For the old one I use the tutorial SSH login without password to login without typing the password every time.
For the new machine I followed the tutorial again, but this time it is not working. I looked at the debug output from ssh (-v option) and it seems to me that the new server does not accept my public key. But I checked and bot authorized_keys are the same, I even used md5sum.
What could be the problem and how could I fix this?
Debug output for old server where it does work (snippet):
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/NICK/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277

Debug output for new server where it does not work (snippet):
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/NICK/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/NICK/.ssh/id_dsa

[UPDATE] Ownership of authorized_keys on remote
NICK@server-new:~/.ssh$ ls -l
total 4
-rwx------ 1 NICK NICK 404 2012-08-08 16:11 authorized_keys

Complete debug output for the not working server:
OpenSSH_5.9p1 Debian-5ubuntu1, OpenSSL 1.0.1 14 Mar 2012
debug1: Reading configuration data /home/NICK/.ssh/config
debug1: /home/NICK/.ssh/config line 1: Applying options for foo2
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to foo-serv2.cs.bar.it [XXX.XXX.XXX.XXX] port 22.
debug1: Connection established.
debug1: identity file /home/NICK/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/NICK/.ssh/id_rsa-cert type -1
debug1: identity file /home/NICK/.ssh/id_dsa type -1
debug1: identity file /home/NICK/.ssh/id_dsa-cert type -1
debug1: identity file /home/NICK/.ssh/id_ecdsa type -1
debug1: identity file /home/NICK/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.5p1 Debian-4ubuntu6
debug1: match: OpenSSH_5.5p1 Debian-4ubuntu6 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA XXX
debug1: Host 'foo-serv2.cs.bar.it' is known and matches the RSA host key.
debug1: Found key in /home/NICK/.ssh/known_hosts:34
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/NICK/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/NICK/.ssh/id_dsa
debug1: Trying private key: /home/NICK/.ssh/id_ecdsa
debug1: Next authentication method: password

A: Compare the sshd configuration files (mine's at /etc/ssh/sshd_config) on the old and new server - is something set up differently on the new one, for example does the AuthorizedKeysFile option on the new one point to some other file (I believe some SSH installations nowadays call the file authorized_keys2)?

A: Did you make sure that the ownership and mode of your ~/.ssh directory on the remote side is correct? It should be owned by you, and have 0700 permissions, i.e. chmod 700 ~/.ssh. Also chmod go-w ~ as this is checked also - because anyone with write permission on your home directory can change the permissions of the .ssh directory.


text:
Q: Is there a good way to scan a drive for bad blocks in the background? I just got a QNAP TS-251, an NAS that runs Linux plus the manufacturer's tools. One of the setup options is to run a bad block scan, but on a pair of 4 TB drives that might take a really long time to run, during which I can't start to use my new NAS.
So, is there a utility that I can run in the background once the device is fully functional? Obviously such a utility would take even longer than one that's running on new, empty drives, since it has to do its thing without destroying live data. But meanwhile the machine is functional and available.
Such a utility might also be useful as a periodic preventive maintenance tool, a few times a year, not just as a way to bring a new device into service sooner.

*

*Does such a utility exist for Linux in general?

*If so, does it run on a QNAP NAS?

*Or is there a QNAP specific utility for this purpose?

A: Since you tagged badblocks in your question, I assume you have some measure of familiarity with it. It can be run as a part of the e2fsck program used to check Ext2/3/4 filesystems if the underlying partitions on the NAS use that filesystem:
e2fsck -c /dev/blockDeviceHere


text:
Q: Scraping data dynamically generated by JavaScript in html document using C# How can I scrape data that are dynamically generated by JavaScript in html document using C#?
Using WebRequest and HttpWebResponse in the C# library, I'm able to get the whole html source code as a string, but the difficulty is that the data I want isn't contained in the source code; the data are generated dynamically by JavaScript.
On the other hand, if the data I want are already in the source code, then I'm able to get them easily using Regular Expressions.
I have downloaded HtmlAgilityPack, but I don't know if it would take care of the case where items are generated dynamically by JavaScript...
Thank you very much!

A: You could take a look at a tool like Selenium for scraping pages which has Javascript.
http://www.andykelk.net/tech/headless-browser-testing-with-phantomjs-selenium-webdriver-c-nunit-and-mono

A: When you make the WebRequest you're asking the server to give you the page file, this file's content hasn't yet been parsed/executed by a web browser and so the javascript on it hasn't yet done anything.
You need to use a tool to execute the JavaScript on the page if you want to see what the page looks like after being parsed by a browser. One option you have is using the built in .net web browser control: http://msdn.microsoft.com/en-au/library/aa752040(v=vs.85).aspx
The web browser control can navigate to and load the page and then you can query it's DOM which will have been altered by the JavaScript on the page.
EDIT (example):
Uri uri = new Uri("http://www.somewebsite.com/somepage.htm");

webBrowserControl.AllowNavigation = true;
// optional but I use this because it stops javascript errors breaking your scraper
webBrowserControl.ScriptErrorsSuppressed = true;
// you want to start scraping after the document is finished loading so do it in the function you pass to this handler
webBrowserControl.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserControl_DocumentCompleted);
webBrowserControl.Navigate(uri);

private void webBrowserControl_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    HtmlElementCollection divs = webBrowserControl.Document.GetElementsByTagName("div");

    foreach (HtmlElement div in divs)
    {
        //do something
    }
}


text:
Q: random error "cannot connect to itunes store" in app purchase I have implemented in app purchase in my iPhone application.
But first time while buying product during payment transaction phase I get an error:
cannot connect to iTunes store and it results in unsuccessful payment transaction.
Main thing is that it is occurring randomly means in subsequent attempts transaction gets completed successfully and again after 2 or 3 transactions it gives me the same error.
Weird behaviour?
I have tried all online available solutions like resetting, "Log out" from iTune account and creating new test user account but none is working.
I am trying to solve this problem since last three days(was waiting if problem is from iTune server) but no luck at all.
Before this I have successfully submitted no. of apps having in app purchase. Facing this issue first time.
Please do suggest some solution.
Thanks

A: In my case the error was because of "TimeOutInterval:".
In my In app purchase implementation workflow, in between there was a call to our local server to make entry of subscription in database.
Later I found, because of slow server I was getting late response from server resulting into "requestTimeout".
To solve this problem I increased the timeoutInterval while making request to server. And It worked for me.


text:
Q: incompatible fragment types i wanted to make an app with a navigation drawer.
The problem is, that once i start the emulator i get a warning:
"Error:(63, 77) error: incompatible types: FaecherFragment cannot be converted to Fragment".
The error in the MainActivity says:
"Wrong 2nd argument type. found: ´com.example.android.test6.FaecherFragment´, required ´android.support.v4.app.Fragment´"
I already found some similar problems, which could all be solved by changing the import statements either from ´android.app.support.v4.app.Fragment´ to ´android.app.Fragment´ or the other way round...sadly that does not work for me...i literally tried each and every combination of both of these in each and every Fragment or class i have made, but it would not work.
I also tried to change my fragment so it extends ´android.support.v4.app.Fragment´...that does not work either.
I am new to android, so maybe it is just a beginners mistake...anyway, i really hope someone can help me!!
MainActivity:
package com.example.android.test6;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;

public class MainActivity extends AppCompatActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks,        FaecherFragment.OnFragmentInteractionListener {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();

    switch (position) {
        case 0:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit();
            break;
        case 1:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit();
            break;
        case 2:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FaecherFragment.newInstance("a","b"))
                    .commit();
            break;
    }
}

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            break;
    }
}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onFragmentInteraction(String id) {

}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

}

FaecherFragment:
package com.example.android.test6;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
* A fragment representing a list of Items.
*

*

* Activities containing this fragment MUST implement the {@linkOnFragmentInteractionListener}
* interface.
*/
public class FaecherFragment extends ListFragment {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

// TODO: Rename and change types of parameters
public static FaecherFragment newInstance(String param1, String param2) {
    FaecherFragment fragment = new FaecherFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public FaecherFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    // TODO: replace hardcoded Faecher
    List<Faecher> faecherList = new ArrayList<Faecher>();
    faecherList.add(new Faecher("Mathe"));
    faecherList.add(new Faecher("Englisch"));
    faecherList.add(new Faecher("Sport"));
    setListAdapter(new ArrayAdapter<Faecher>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, faecherList));
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    //to start a new activity we have to declare an intent, this intent needs a context (the
    //activity in which we are) and the class that we want to pass the intent into
    Intent intent = new Intent(getActivity(), FaecherDetailsActivity.class);
    //now we take the clicked listitem from our listView l and store it inside a variable
    String title = l.getItemAtPosition(position).toString();
    //we give this variable to the intent (as an extra)
    intent.putExtra("value_title", title);
    //now we start the activity
    getActivity().startActivity(intent);

    if (null != mListener) {
        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        //mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
    }
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 *

 * See the Android Training lesson Communicating with Other Fragments for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(String id);
}

}

A: You have
 import android.app.ListFragment;
 public class FaecherFragment extends ListFragment

Change import to support list fragment

A: You import wrong class. You must import fragment from support library:
    import android.support.v4.app.ListFragment;

A: Your FaecherFragment extends ListFragment. And the ListFragment extends Fragment. This Fragment is incompatible with support.v4.app.FragmentManager.
So, you can make your FaecherFragment extend support.v4.app.ListFragment which extends support.v4.app.Fragment.


text:
Q: How to connect a voice stream websocket (goal is Google Voice API) to a Twimlets Conference In my existing app we use the https://www.twilio.com/labs/twimlets/conference feature :
var strURI = "http://twimlets.com/conference?Name=" + channelId.ToString() + "&Message=Welcome&Music=http://bter.com/radio/radio2.xml";
TwilioClient.Init(_twilioConfiguration.AccountSid, _twilioConfiguration.AuthToken);
var application = await ApplicationResource.CreateAsync(voiceUrl:new Uri(strURI), friendlyName: channelId.ToString());

My app then allows users in their browser to join in a special audio conference bridge to participate in training. It does not involve any phone number.
We have a need to route the stream to the Google Speech to Text API so we can use a custom dictionary.
In the examples I have found, and exercised
twilio phone-numbers:update 14805551212 --voice-url http://b74c35a792ff.ngrok.io

It seems like the phone number is configured in Twilio so that on connecting it opens a web socket stream to the endpoint (a ngrok endpoint proxy is common in the examples) .
In my situation, I wish to programmatically tell the dynamically created conference room to open a voice stream to a specific endpoint (for example http://b74c35a792ff.ngrok.io).
Is there an API call I can make to Twilio or additional settings I can add to the twimlets.com/conference to achieve this?

A: Twilio developer evangelist here.
When you set up a phone number with a voice URL in Twilio it doesn't connect via web sockets. Instead, when a phone call is made to the Twilio number it will make an HTTP request, a webhook, to the voice URL you provide. Similarly, when you create a new call via the REST API and provide a URL, Twilio will make an HTTP request to that URL when the call connects.
In both instances, Twilio is asking your application for instructions for what to do next. Those instructions are supplied by responding to the HTTP request with a subset of XML called TwiML. The XML elements and attributes describe what Twilio should do next with the call, like speaking a message, playing an audio file, gathering user input or dialling another number or into a conference.
When you use the Conference Twimlet, the URL you are providing returns TwiML to direct the call into a conference.
The Conference Twimlet does not provide any way to stream the audio from it. In fact, conferences in general do not make it easy to get the audio unless you literally dial into the conference itself. You could set up to stream the audio of each of the conference participants to your own websocket server by forking their audio before they join the conference using <Start><Stream> before redirecting to the conference Twimlet.
Sorry this isn't a full answer, but hope it helps.


text:
Q: How to understand the opcode mips pseudo instruction move? found an explanation of the pseudo instruction
Move (move)

The move pseudo instruction moves the contents of one register into another register.

move $1, $2
translates to

add $1, $2, $0

Here is the code.
25f0a003       move fp, sp

but add opcode is like this.
31-26 special   0x000000
25-21 rs       it should be  0x1d
20-16 rt       it should be  0x0
15-11 rd       it should be  0x1e
10-6  0        it should be  0x0
5-0   add      it should be  0x32

but the opcode is different.

A: I'm not sure where you got the explanation you quoted in your question, but it's up to the assembler to decide how to implement pseudo-instructions.
The word 25f0a003 doesn't make sense as a MIPS instruction, but if we swap the bytes around to 03a0f025 then we get:
0000 0011 1010 0000 1111 0000 0010 0101

=>

000000 11101 00000 11110 00000 100101

=>

or $30, $29, $0

=>

or $fp, $sp, $zero

So in this case, the assembler you used translated move $fp, $sp into or $fp, $sp, $zero.


text:
Q: Is a conditional distribution independent of the variable being conditioned on? This might seem like a bit of a silly question, but for some reason I'm having trouble convincing myself of it, so I thought I might solicit opinions on this site. Suppose random variables $(X,Y)$ have some joint distribution (bivariate normal if you'd like). Is the conditional distribution $(Y|X=x)$ independent of random variable $X$? I feel like it's vacuously true because $\text{P}(Y|X,X)=\text{P}(Y|X)$ but for some reason the intuition just isn't coming to me.

A: It depends what you mean by the "conditional distribution"
There are a number of ways this can be interpreted, and the answer depends on the interpretation.  To facilitate this analysis, suppose we define the conditional distribution function $F$ as the bivariate function:
$$F(y|x) = \mathbb{P}(Y \leqslant y | X = x)
\quad \quad \quad \text{for all } x \in \mathscr{X}.$$
If we consider the conditional distribution as the full bivariate function $F( \cdot | \cdot )$ then this object is fixed by the joint distribution of $X$ and $Y$, so it is a constant (and therefore trivially independent of $X$).  Similarly, if we substitute any constant arguments to reduce the function to a univariate function or scalar value, it is still a constant (and therefore trivially independent of $X$).  However, if we substitute one of the original random variables into its argument then it becomes a random variable, and it is now statistically dependent with the substituted random variable (and possibly also the other random variable).  This is summarised below.
$$\begin{matrix}
F( \cdot | \cdot ) & & & \text{Constant bivariate function} & & & \text{Independent of } X \text{ and } Y, \\[6pt]
F( \cdot | x ) & & & \text{Constant univariate function} & & & \text{Independent of } X \text{ and } Y, \\[6pt]
F( y | \cdot ) & & & \text{Constant univariate function} & & & \text{Independent of } X \text{ and } Y, \\[6pt]
F( y | x ) & & & \text{Constant scalar value} & & & \text{Independent of } X \text{ and } Y, \\[6pt]
F( \cdot | X ) & & & \text{Random univariate function} & & & \text{Not independent of } X, \\[6pt]
F( Y | \cdot ) & & & \text{Random univariate function} & & & \text{Not independent of } Y, \\[6pt]
F( y | X ) & & &\text{Random variable} & & & \text{Not independent of } X, \\[6pt]
F( Y | x ) & & &\text{Random variable} & & & \text{Not independent of } Y. \\[6pt]
F( Y | X ) & & &\text{Random variable} & & & \text{Not independent of } X \text{ or } Y. \\[6pt]
\end{matrix}$$
(Note that this is slightly simplified, insofar as I have not specified dependence on the other random variable; whether there is dependency with the other random variable depends on the original joint distribution and the conditional distribution.)
As you can see, the conditional distribution is independent of the random variable being conditioned on, so long as we take the conditional distribution to be a constant object.  If we condition on the random variable $X$ as a random variable then the conditional distribution becomes a random function (or random variable) that is not independent of $X$.

A: The immediate answer is that, if one considers the random variable $Z_k$ with cdf
$$F_k(z)=\mathbb P(Y\le z|X=k)$$
it is defined independently of $X$ and hence $Z$ is independent from $X$.
However, if the question is about the "random variable" $(Y|X=x)$, this object does not exist as such, i.e., separately from $Y$, marginal from the pair $(X,Y)$. That is, $Y$ enjoys both a marginal distribution and a conditional distribution, but remains the same random variable. The cdf $\mathbb P(Y\le z|X=k)$ is thus a characterisation of the conditional distribution of $Y$ when the realisation $X=k$ occurs. Since the conditioning event is $X=k$, the conditional distribution depends on it (or not when $X$ and $Y$ are independent), but it makes no sense to introduce independence once $X=k$ has happened.


text:
Q: vbscript get last line in text I'm trying to get the last line in a .HOL file.
It will get the last line but every time you run the script, it stacks the previous lines.
Dim lastLine
Dim objFile
Dim objFSO

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Desktop\OUTLOOK.HOL", ForReading)

Do Until objFile.AtEndOfStream

  lastLine = objFile.ReadLine

Loop

objFile.Close

Wscript.Echo lastLine

What I'm trying to make is a script that gets rid of any date that is older than the current date then add a new date at the bottom of the .HOL file. The reason I need the last line is so I can take that date and add 2 weeks to it.
What the Echo Looks like Run 1                      Run 2
Date1                                               Date1
                                                    Date2
Run 3
Date1
Date2
Date3

And so forth if you get it. (Id post picture but I cant yet)
=========== .HOL File =======
[Test Days] 5
Test Day, 5/3/2013
Test Day, 5/17/2013
Test Day, 5/31/2013
Test Day, 6/14/2013
Test Day, 6/28/2013

A: The easy fix:
    dim x

    Do Until objFile.AtEndOfStream
      x = objFile.ReadLine
      If objFile.atEndOfStream Then
         lastLine = x
      End If
    Loop

The following function will add 2 weeks to 31 jan 2010, you just need to compose that from your line:
    DateAdd("ww",2,"31-Jan-10")

couple of edits.. its been a while since vbscript!

A: If you want to replace the last date in the file you could try something like this:
Set fso = CreateObject("Scripting.FileSystemObject")

text = Split(fso.OpenTextFile("C:\Desktop\OUTLOOK.HOL").ReadAll, vbNewLine)

Set f = fso.OpenTextFile(filename, 2)
For i = 0 To UBound(text)-1
  f.WriteLine text(i)
Next

lastline = Split(text(UBound(text)), ",")
newdate = DateAdd("ww", 2, lastline(1))
lastline(1) = Year(newdate) & "/" & Right("0" & Month(newdate), 2) _
                & "/" & Right("0" & Day(newdate), 2)
f.WriteLine Join(lastline, ",")

f.Close


text:
Q: How to hide my JWT token On Javascript Ajax API Call from Frontend? My Question is that I was Implemented JWT Token When User is logged In. Also Done some test Through POSTMAN. Getting token when User is validating with username and password. Now My API is completed and whenever Front-end Guy needs API Calls, He have to pass JWT token. Now This token is visible on AJAX API call. Is there any way that I can Hide all token so that Attacker won't get this token?

A: jwt is not secured by default.
first if you want to work with jwt in your website,it must work on https.
second if you store it on a cookie use the cookie http only option to prevent javascript cookie hijack
also you can use jwt in OAuth for more features


text:
Q: Time-Series Analysis: Logarithmic returns Why is it that in many econometrics papers, especially the ones dealing with financial time-series data returns are modelled as logarithmic differences in prices
$r_t=\ln(p_t )-\ln(p_{t-1} )$, what is the advantage/disadvantage of using instead the traditional percentage change formula $r_t=p_t/p_{t-1}-1$?

A: The use of linear returns (percentage change) and log returns are both used in financial applications. Two arguments for using log returns for time series modelling are

*

*The distribution of log returns can unlike linear returns easily be project to any horizon

*Log returns typically have a symmetric distribution which makes modelling easier (stock prices are often assumed to be log normally distributed - log-returns follow a normal distribution)


text:
Q: Best approach to do auto versioning of an elixir application phoenix I am doing hot code upgrade using distillery for a phoenix application. I used this to create the version of the application.
  def project do
    {result, _exit_code} = System.cmd("git", ["rev-parse", "HEAD"])
    git_sha = String.slice(result, 0, 7)

    [app: :evercam_media,
     version: "1.0.1-a#{git_sha}",
     elixir: "~> 1.7",
     elixirc_paths: elixirc_paths(Mix.env),
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     compilers: [:phoenix] ++ Mix.compilers,
     aliases: aliases(),
     deps: deps()]
  end

this creates versions but that version doesn't work with hot code upgrades and messes up the relup file. When I do versioning like 1.0.1, 1.0.2 and 1.0.3. then hot code deploys works fine. but Is there any way to make this thing dynamic?
I am deploying using distillery to a remote server.
Update:
I am using distillery for deployment but the auto versions are not working unless they are 1.0.1 or 1.0.2 or 1.0.3. I have tried the answer below. as well as git describe --tags as well. but distillery only uses 2 versions then each time using the past version to create new release.

A: The issue with git_sha is that it's not ordered. The next version is assumed to have a number that is greater than the previous one by trivial alphanumeric sort. With sha that's not the case.
You might use date for that purpose. E. g.
git log -1 --date=raw --format=%cd
#⇒ 1535467693 +0200 # seconds since epoch

Now let's elixir it:
{epoch, _} = System.cmd("git", ~w|log -1 --date=raw --format=%cd|)
[sec, tz] =
  epoch
  |> String.split(~r/\s+/, trim: true)
  |> Enum.map(&String.to_integer/1)
#⇒ [1527769224, 200]
sec + tz * 36 # * 60 * 60 / 100
#⇒ 1527776424

The number above is always growing.

Sidenote: use inplace binary pattern match instead of String.slice/3 whenever possible:
{<<git_sha::binary-size(8), _rest::binary>>, _exit_code} =
  System.cmd("git", ["rev-parse", "HEAD"])
#⇒ {"556c53987eb55c82ffb6925f9f56eae5de01c119\n", 0}
git_sha
#⇒ "556c5398"

A: Here is the approach I use for an application that eventually get build as a versioned production RPM. When built against a clean tag, the version is the tab name. Otherwise, the version includes the short commit hash and the commit count since the last tag.
It also supports override the auto versioning by including a VERSION file in the project's root directory.
# mix.exs
defmodule MyApp.Mixfile do
  use Mix.Project
  @default_version "v1.0.0-default"

  def project do
    [
      app: :my_app,
      version: version(),
      elixir: "~> 1.6",
      # ...
    ]
  end

  # ...

  defp version do
    # Build the version number from Git.
    # It will be something like 1.0.0-beta1 when built against a tag, and
    # 1.0.0-beta1+18.ga9f2f1ee when built against something after a tag.
    with {:ok, string} <- get_version(),
         [_, version, commit] <- Regex.run(~r/(v[\d\.]+(?:\-[a-zA-Z]+\d*)?)(.*)/, String.trim(string)) do
      String.replace(version, ~r/^v/, "") <> (commit |> String.replace(~r/^-/, "+") |> String.replace("-", "."))
    else
      other ->
        IO.puts("Could not get version. error: #{other}")
        @default_version
    end
  end

  defp get_version do
    case File.read("VERSION") do
      {:error, _} ->
        case System.cmd("git", ["describe"]) do
          {string, 0} -> {:ok, string}
          {error, errno} -> {:error, "Could not get version. errno: #{inspect errno}, error: #{inspect error}"}
        end
      ok -> ok
    end
  end
end

A: Whether all you need is to make delivery happy, you might use delivery config for that purpose. Just put the following line in your .deliver/config:
AUTO_VERSION=commit-count+git-revision+branch-unless-master

A: The solution which we used was
defmodule EvercamMedia.Mixfile do
  use Mix.Project

  def project do
    [app: :evercam_media,
     version: "1.0.#{DateTime.to_unix(DateTime.utc_now())}",
     elixir: "~> 1.11.1",
     elixirc_paths: elixirc_paths(Mix.env),
     build_embedded: Mix.env == :prod,

this one and it works perfectly alright.
the solution, I had accepted that won't work with the hot upgrade when you deploy a branch and then master.
Also, the most important part while deploying with Ansible is to touch your mix.exs as well so it can compile and pick up a new version.
I have written an article about it Hot Code Upgrade


text:
Q: Android java XML junk after document element I'm using SAX to read/parse XML documents and I have it working fine except for this particular site where eclipse tells me "junk after document element" and I get no data returned
http://www.zachblume.com/apis/rhyme.php?format=xml&word=example
The site is not mine..just trying to get some data from it.

A: Yes, that's not an XML document. It's trying to include more than one root element:
<?xml version="1.0"?>
<word>ampal</word>
<word>ample</word>
<word>hampel</word>
<word>hample</word>
<word>lampl</word>
<word>pampel</word>
<word>sample</word>

The parser regards everything after <word>ampal</word> as by that time it's read a complete document... hence the complain about "junk after document element".
An XML document can only have one root, but several children within the root. For example:
<?xml version="1.0"?>
<words>
  <word>ampal</word>
  <word>ample</word>
  <word>hampel</word>
  <word>hample</word>
  <word>lampl</word>
  <word>pampel</word>
  <word>sample</word>
</words>

A: The page does not contain XML. It contains an XML snippet at best:
<?xml version="1.0"?>
<word>ampal</word>
<word>ample</word>
<word>hampel</word>
<word>hample</word>
<word>lampl</word>
<word>pampel</word>
<word>sample</word>

This is incorrect since there is no document element. SAX interprets the first <word> as the document element, and correctly reports "junk after document element" since for all it knows, the document element ends on line 1.
To get around the error, do not treat this document as XML. Download it as text, remove the XML declaration (<?xml version="1.0"?>) and then wrap it in a fake document element before you try to process it.


text:
Q: Frontend gets Error 401 from Backend in CORS request - apache/php insufficiently configured? I have a frontend, running on most recent vue on port 5000.
Then I have my backend, running on most recent lumen on port 8080.
Both are on my localmachine. Later in production, they will be separated on two virtual machines.
Right now, when sending an http request from the frontend to the backend, I get the following error to my devConsole (NOT the vue devtools, but the usual firefox/chrome devtools console!):
Error: Request failed with status code 401

The function returning the axios object executing the http request looks like this:
function fetchData(method, slug, payload) {
  return axios[method](`${API_ENDPOINT}${slug}`, payload);
}

The call looks like this:
fetchData(METHOD_POST, USER_LIST, "someToken").then((res)=>{
        return res
      })

METHOD_POST contains the string post and USER_LIST contains the string /user/show_data which is used to further specify the URL. In my Lumen backend, it accesses the following route:
$router->group(['prefix' => 'user', 'middleware' => 'auth'], function() use ($router){

    $router->post('/show_data', 'UserController@getData');

});

The route and the respective controller work, I've tested it with RESTClient https://addons.mozilla.org/de/firefox/addon/restclient/
I think that syntaxwise, everything is fine. Also, the token wasnt expired when I used it, I checked this multiple times.
So I think that it might be connected to the CORS-Policy of the apache and/or php.
Im running apache and php from the latest XAMPP dist.
Still, I'm not entirely sure if thats it, especially since this is the first time that I connect a backend using lumen and a frontend using vue.js.
EDIT: I managed to activate "withCredentials" for my axios object by changing the function body to:
  axios.defaults.headers.withCredentials = true;
  return axios[method](`${API_ENDPOINT}${slug}`, payload);

However, now the CORS problem turns up ^^
When sending the http request, I get these error messages to my console:
Access to XMLHttpRequest at 'http://localhost:8080/user/show_data' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And
xhr.js:178 POST http://localhost:8080/user/show_data net::ERR_FAILED

And
createError.js:16 Uncaught (in promise) Error: Network Error
    at t.exports (createError.js:16)
    at XMLHttpRequest.d.onerror (xhr.js:83)

What should I do?
EDIT2:
I now added the following lines to my httpd.conf and restarted apache and lumenproject:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Max-Age: 360
Header set Access-Control-Allow-Credentials: true
Header set Access-Control-Allow-Methods: *
Header set Access-Control-Allow-Headers: Origin
Header set Access-Control-Expose-Headers: Access-Control-Allow-Origin
</IfModule>

I also tried out explicitely specifying the origin to
http://localhost:8080

and
http://localhost:5000

But it didnt help. The errormessage remains the same.

A: Most browser will block you anyway if your backend allow any host.
Access-Control-Allow-Origin "*"

You are also missin a semi-colon
Access-Control-Allow-Origin: "*"

Try
Access-Control-Allow-Origin: "yourorigindomain.com"


text:
Q: AngularJS: tabs and controller passing data through I would like to create an AngularJS app in which I woud have a page containing multiple tabs. Since each tab would have a very specific business logic, I am wondering what would be the best way to achieve such a thing, knowing that I want to be able to pass through data from tab to tab. The user would have to follow a specific workflow, starting on the first tab, clicking on a button and landing on the second tab, able to see and use data he generated from the first tab, and so on.
I have come across this articles : Top 18 Most Common AngularJS Developer Mistakes which talks about controllerAs attribute. Would it be something I could use to have let's say:

*

*a route provider with a main controller

*a main view including each of my tabs' view

*a view per tab with an associated controller

*use controllerAs to be able to pass given shared data from a controller to another

UPDATE
Apparently it is clear that it cannot work if I do something like that:
Javascript:
angular.module('myApp').controller('FirstController', function(){
    this.myVar = "I am from FirstController";
});
angular.module('myApp').controller('SecondController', function(){
    this.myVar = "I am from SecondController";
});

HTML :

    {{FC.myVar}}
    {{SC.myVar}}

    {{FC.myVar}}
    {{SC.myVar}}

How could I make something like this nice and working? Or should I really have shared variables amongst the controllers provided from a MainController, wrapping these two?
Thank you for your helps.
Kind regards,


text:
Q: How to get two arrays from mongo aggregate with $project and $map insdite ti I have a nodejs app with Repository architecture. I am trying to get the data returned from an aggregation I made:
function foo(id) {
return await this.collection.aggregate([
      {
        "$match": {
          _id: "ObjectId('"+ id +"')"
        }
      },
      {
        "$addFields": {
          "self": "$$ROOT"
        }
      },
      {
        "$graphLookup": {
          "from": "categories",
          "startWith": "$_id",
          "connectFromField": "_id",
          "connectToField": "categoryId",
          "as": "categoryLookup"
        }
      },
      {
        "$addFields": {
          "categoryLookup": {
            "$concatArrays": [
              "$categoryLookup",
              [
                "$self"
              ]
            ]
          }
        }
      },
      {
        "$lookup": {
          "from": "locos",
          "localField": "categoryLookup._id",
          "foreignField": "categoryId",
          "as": "locosLookup"
        }
      },
      {
        "$project": {
            categories: {
              "$map": {
                "input": "$categoryLookup",
                "as": "c",
                "in": "$$c._id"
              }
            },
            locos: {
              "$map": {
                "input": "$locosLookup",
                "as": "l",
                "in": "$$l._id"
              }
            }
        }
      }
    ]);
}

I want to get the data from the returned cursor which can not be transformed into an array. The problem is that this code works fine on the playground but I think also that $filed won't get the field since we need to use $getField { "fieldName": "field"}. I am really stuck here and the answers given to me previously weren't helping ..
the next step please


text:
Q: How to get data received from embed in javascript <embed src=https://example.com></embed>
<script>
alert(embed data)
</script>

How to get data received from embed in javascript?

A: add id to eht element and then use javascript to get the data like that
<embed id="embed" src=https://example.com></embed>
<script>
alert(document.getElementById("embed").src)
</script>


text:
Q: Python - pd.to_datetime does not convert object string to datetime, keeps being object following problem:
I'm trying to convert a column of a DataFrame from a string to a datetime object with following code:
df = pd.read_csv('data.csv')
df['Time (CET)'] = pd.to_datetime(df['Time (CET)'])

Should be the standard pandas way to do so. But the dtype of the column doesn't change, keeps being an object while no error or exception is raised.
The entries look like 2018-12-31 17:47:14+01:00.
If I apply pd.to_datetime with utc=True, it works completely fine, dtype changes from object to datetime64[ns, UTC]. Unfortunately I don't want to convert the time to UTC, only converting the string to a datetime object without any time zone changes.
Thanks a lot!


text:
Q: How to exclude column while saving via jpa crud repository? I have a pretty huge entity with many fields and a several methods which interacts with that entity. And I have some problem with non-repeatable read when tho threads read data from db at the same time, one thread changed a field and saved entity, but other one at the same time read data with old value didn't change it and saved. First solution that I thought was to change transaction isolation level to repeatable read, but it may take a huge influence on perfomance of my app. All I need is to ignore a field in the second method, but change it in first one, so @Transient annotation is not suittable here. in both cases i have the same @Entity class and save data via defauld CrudRepository method save(entity) so i can't choose what fields i want to update and what are not. The second idea is to remove that problematic field from the entity, create a new one entity which extends first and place that field there. After that, use the extended entity in cases where I want to interact with that field and the base entity in cases where I don't. Is it a good idea?

A: Are both threads allowed to proceed, even if one doesn't see the changes made by the other one (in other words, is the data modified in one thread independent of the data modified in the other)?
If so, you could use @DynamicUpdate. This way, Hibernate will only update the fields that have in fact been modified, without overwriting any other fields. Please note that this comes with a performance penalty of its own, since it prevents Hibernate from using a single prepared statement for all updates to the entity.
If not, you can use locking to synchronize the threads.


text:
Q: Mouse configurations not staying when using RemoteApps I have some clients who need to use a larger mouse curser. However, when they use the RemoteApps we published for them, the configuration is not staying in place.
I thought maybe if I created a GPO to force the configuration that would work. It does not. It works when you RDP into a desktop but not when using a RemoteApp.
The GPO changes the users' registry to the desired mouse settings, yet it is not sticking in RemoteApps.
Also, this is for any published RemoteApp, we publish Windows File Explorer for them and that also reverts the mouse configuration back to Windows' default
Is there so configuration setting somewhere to control how a mouse looks in a RemoteApp specifically or something like that?


text:
Q: Get name and id of autocomplete suggestions into input field I have the code below, which I use to type and suggest a few relation names in an input field. The data variable right now returns only names like:
var data = ["name": "Relation 1", "name":"Relation 2"]

I modified it and now it has data like:
   var data = [
        {"id":1,"name":"Foo"},
        {"id":2,"name":"Bar"},
        {"id":3,"name":"Foo Bar"}
    ];

How do I append the id of the selected name in the id input?
$('input.relation').typeahead({
    source:  function (query, process) {
    return $.get('live_search.php?filter=relation', { query: query }, function (data) {
                console.log(data);
                data = $.parseJSON(data);
                return process(data);
        });
    }
});

 <div class="form-group">
                <label for="relation"> Relation </label>
                <input class="relation form-control" type="text">
                <input class="relation-id form-control" type="text" name="id">
 </div>


text:
Q: MVC5 and jQuery template I am trying to follow example shown in this session.  I have VS 2013 installed on my machine.  Below is code that deals with jQuery template.  But I am not able to see expected out put.

@section scripts{

}

Update: Please see below for Layout.cshtml file
<!DOCTYPE html>

    deleted...
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    Deleted...

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/koBootStrap")
    @RenderSection("scripts", required: false)

I was expecting to see list of friends i.e. F1,F2 and F3 but instead its outputing entier script ( see below )
{{each(index,friend) friends}}
${friend.name}
{{/each}}

Am I missing any jQuery library
I have included below libraries

*

*jQuery-1.10.2.js

*knockout-3.3.0.js
Do I have to include any other library for jQueryTemplate to work?
Update 2:

@section scripts{

}

Still I can't see  list of friends.  Its outputting entire 'text/html' block as it is.
Update 3: Posting bundle config
public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            var scriptBundleKoBootStrap = new ScriptBundle("~/bundles/koBootStrap");
            scriptBundleKoBootStrap.Include(new string[] { "~/Scripts/bootstrap.js","~/Scripts/respond.js","~/Scripts/knockout-{version}.js"});
            bundles.Add(scriptBundleKoBootStrap);

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }

A: There are a few ways to template bind in Knockout JS, some more verbose than others.  I would recommend reading through the template binding documentation. Here is one way of binding to a template.
Example

A: You need to reference the Knockout.JS at the top of your view page.
@{ ViewBag.Title = "Home Page"; }

A: Bellow is a solution that worked for me ( as suggested by Colin Bacon)

Still I don't know what was wrong with my initial code ( which was demonstrated in this video)


text:
Q: Change color of specific ytick matplotlib I have a dict with 200 keys and values that generates this graph.
Also i compute the average of these values and plot that too. I would like the avg value to be the same color as the line. The code that i use is this :
with open('path_to_json/values.json', 'r') as outfile:
    a = json.load(outfile)

sum = 0
for k, v in a.items():
    sum += v

avg = sum / len(a.values())

fig, ax = plt.subplots(1,1)
p=ax.plot(list(a.keys()),list(a.values()))
p=ax.plot([0, len(a.values())], [avg, avg], "--")
yt = ax.get_yticks()
yt = np.append(yt, avg)
xticks = np.arange(0, len(a.values()), 10)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
ax.set_xticks(xticks)
ax.set_yticks(yt)
plt.show()

A: Have a look at the overview for the Axes class, especially the "Ticks and tick labels" section: There's get_yticklabels and get_yticklines which return the objects which both have a set_color method.
Minimal example:
import matplotlib.pyplot as plt
import numpy as np

plt.plot([0, 1], [0, 1])
ax = plt.gca()
ax.set_yticks(np.append(ax.get_yticks(), 0.55))
ax.get_yticklabels()[-1].set_color("red")
ax.get_yticklines()[-2].set_color("red")
plt.show()


text:
Q: IPv6 interface not responding to neighbor solicitations, DHCP involved too ip addr shows:
2:  eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
     link/ether 02:6d:5e:86:29:49 brd ff:ff:ff:ff:ff:ff
     inet X.X.X.X/24 brd X.X.X.255 scope global eth0
        valid_lft forever preferred_lft forever
     inet6 2604:X:X:X::11/64 scope global deprecated
        valid_lft forever preferred_lft 0sec
     inet6 fe80::X:X:X:X/64 scope link
        valid_lft forever preferred_lft forever

In particular, I'm wondering about the deprecated and preferred_lft 0sec in there.
My syslog has this repeated over and over:
dhclient: PRC: Address 2604:X:X:X::11 depreferred.
dhclient: PRC: Address 2604:X:X:X::11 expired.
dhclient: PRC: Bound lease is devoice of active addresses. Re-initializing.
dhclient: XMT: Solicit on eth0, interval 1010ms.
dhclient: RCV: Advertise message on eth0 from ::.
dhclient: XMT: Request on eth0, interval 920ms.
dhclient: RCV: Reply message on eth0 from ::.

Then about four seconds later, it does it again. I can see the address appearing in and disappearing from the ip addr output.
I can ping the gateway while the address is present:
64 bytes from 2604:X:X:X::1: icmp_seq=1 ttl=255 time=0.318 ms
64 bytes from 2604:X:X:X::1: icmp_seq=2 ttl=255 time=0.277 ms
64 bytes from 2604:X:X:X::1: icmp_seq=3 ttl=255 time=0.336 ms
64 bytes from 2604:X:X:X::1: icmp_seq=4 ttl=255 time=0.324 ms
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
64 bytes from 2604:X:X:X::1: icmp_seq=7 ttl=255 time=0.316 ms
64 bytes from 2604:X:X:X::1: icmp_seq=8 ttl=255 time=0.321 ms
64 bytes from 2604:X:X:X::1: icmp_seq=9 ttl=255 time=0.331 ms
64 bytes from 2604:X:X:X::1: icmp_seq=10 ttl=255 time=0.327 ms

But if I try and ping this host from the Internet, it sees
IP6 :: > ff02:1:ff00:11: ICMP6, neighbor solicitation, who has 2604:X:X:X::11, length 24

multiple times, but never sends a response. ip maddr show does list inet6 ff02::1:ff00:11 on eth0.
At this point I've run out of things to look for. What might the problem be? In particular, what's going on with that immediately-expiring address from DHCP (it is the correct address, btw)?
Edit: I looked at the tcpdump in Wireshark, and I see that the leases are being given with a preferred lifetime of 4s and a valid lifetime of 8s, which is consistent with the timing in the syslog.

This is actually a VM running on an OpenContrail network, but I want to rule out it simply being a Linux issue first.