text:
Q: Is there a way to bypass the need to reference self in an argument (Python) The purpose of my code is to create and print a list of all the keyboard and mouse interactions that occur. The code was working, but then I decided to convert it into a class. From there, I was not able to reference the functions because it considered self to be the first argument.
Here is the code with the class that does not work.
import pyautogui
from pynput.mouse import Listener
MouseListener = Listener
from pynput.keyboard import Listener
KeyboardListener = Listener
from pynput import keyboard

######################
#
# m = move
# p = mouse press
# r = mouse release
# d = scroll down
# u = scroll up
# 1 = key down
# 2 = key up
#
######################

temp = []
class Recorder():
    #record mouse movement
    def on_move(self, x, y):
        temp.append('m{0}'.format(
            (x, y)))

    #record mouse click
    def on_click(self, x, y, button, pressed):
        temp.append('{0}{1}'.format(
            'p' if pressed else 'r',
            (x, y)))

    #record mouse scroll
    def on_scroll(self, x, y, dx, dy):
        temp.append('{0}{1}'.format(
            'd' if dy < 0 else 'u',
            (x, y)))

    #record keyboard press
    def on_press(self, key):
        try:
            temp.append('1({0})'.format(
                key.char))
        except AttributeError:
            temp.append('1({0})'.format(
                key))

    #record keyboard release and end if esc
    def on_release(self, key):
        temp.append('2({0})'.format(
            key))
        if key == keyboard.Key.esc:
            # Stop listener
            print(temp)
            keyboard_listener.stop()
            mouse_listener.stop()
            return False

mouse_listener = MouseListener(
    on_move=Recorder.on_move,
    on_click=Recorder.on_click,
    on_scroll=Recorder.on_scroll)

keyboard_listener = KeyboardListener(
    on_press=Recorder.on_press,
    on_release=Recorder.on_release)

keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()

And below is the code that performs properly.
import pyautogui
from pynput.mouse import Listener
MouseListener = Listener
from pynput.keyboard import Listener
KeyboardListener = Listener
from pynput import keyboard

##########
#
# m = move
# p = mouse press
# r = mouse release
# d = scroll down
# u = scroll up
# 1 = key down
# 2 = key up
#
##########

temp = []

#mouse recorder
def on_move(x, y):
    temp.append('m{0}'.format(
        (x, y)))

def on_click(x, y, button, pressed):
    temp.append('{0}{1}'.format(
        'p' if pressed else 'r',
        (x, y)))

def on_scroll(x, y, dx, dy):
    temp.append('{0}{1}'.format(
        'd' if dy < 0 else 'u',
        (x, y)))

#keyboard recorder
def on_press(key):
    try:
        temp.append('1({0})'.format(
            key.char))
    except AttributeError:
        temp.append('1({0})'.format(
            key))

def on_release(key):
    temp.append('2({0})'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        print(temp)
        keyboard_listener.stop()
        mouse_listener.stop()
        return False

#activation
mouse_listener = MouseListener(
    on_move=on_move,
    on_click=on_click,
    on_scroll=on_scroll)

keyboard_listener = KeyboardListener(
    on_press=on_press,
    on_release=on_release)

keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()

A: You can use the decorator @staticmethod for this. Add @staticmethod above the functions in question. For example:
class Recorder:
    #record mouse movement
    @staticmethod
    def on_move(x, y,temp):
        temp.append('m{0}'.format((x, y)))

You can now use the function without instantiating an object.
Call the function with:
Recorder.on_move(x,y,temp)

Documentation


text:
Q: Is add reference to a Class Library(Package) project in old Web project possible i have a running WebApi 2 project and i would like to investigate the upgrade path to Asp.NET 5. My upgrade path would be:

*

*Upgrade libraries one by one using the appropriate target framework

*Upgrade tests

*Upgrade WebApi project to new Asp.NET 5.

With my first library converted i was unable to add the reference to any project not using the new template!
Is this the tooling? Is this possible at all?

A: You cannot (at this time) reference a DNX project from a csproj.  You could however create nuget packages of the project using dnu pack and reference those in your csproj.
You can however reference a csproj from a DNX project via VS2015 or by using dnu wrap.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firestore: enablePersistence() and then using redux with offline database? So, essentially, I'm using Create-React-App and I want to allow users to add data to redux either offline or online. I also want to sync redux with Firestore.
In my main attempt, I initialize my firebase settings:
// ./firebase/firebase.js

var firestoreDatabase;

firebase.initializeApp(config.firebase.config);
firebase.firestore().enablePersistence().then(() => {
  firestoreDatabase = firebase.firestore();
});

export { firebase, firestoreDatabase };

Then, to make sure this has fired properly (this is definitely wrong, but I can't figure out the best place to catch the enablePersistence() return... ):
// src/index.js

import { firebase, firestoreDatabase } from "./firebase/firebase";

firebase.auth().onAuthStateChanged(user => {
  store.dispatch(setReduxData()).then(() => {
  if (firestoreDatabase) {
    ReactDOM.render(application, document.getElementById("root"));
  }
  });
});

ACTIONS FILE
import { firestoreDatabase } from "../firebase/firebase";

export const setReduxData = () => {
  return (dispatch, getState) => {
    const uid = getState().auth.uid;
    const data = { newData: '123' };

    return firestoreDatabase
      .collection("Users")
      .doc(uid)
      .collection("data")
      .add(data)
      .then(ref => {
        // so, this never gets fired
        dispatch(
          addData({
            id: ref.id,
            ...data
          })
        );
      })

So the dispatch never gets fired, however, when I refresh the application, the data I entered { newData: '123' } is added to the store.
I think my entire way of handling this is wrong. I don't like exporting firestoreDatabase as undefined and then updating it when enablePersistence() returns...
I would like to just enablePersistence() once and then use the cache or the server depending on if the user is online or not... Redux should operate the same regardless...
Any thoughts and feedback are welcome!

A: So, I figured out how to load Firestore properly in my application:
In my firebase.js file:
import * as firebase from "firebase";
import config from "../config";

// https://firebase.google.com/docs/reference/js/
firebase.initializeApp(config.firebase.config);

const database = firebase.database();
const auth = firebase.auth();
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

export { firebase, googleAuthProvider, auth, database };

Then, I added a firestore.js file:
import { firebase } from "./firebase";
import "firebase/firestore";
import { notification } from "antd";

firebase.firestore().settings({ timestampsInSnapshots: true });

const handleError = error => {
  if (error === "failed-precondition") {
    notification.open({
      message: "Error",
      description:
        "Multiple tabs open, offline data only works in one tab at a a time."
    });
  } else if (error === "unimplemented") {
    notification.open({
      message: "Error",
      description: "Cannot save offline on this browser."
    });
  }
};

export default firebase
  .firestore()
  .enablePersistence()
  .then(() => firebase.firestore())
  .catch(err => {
    handleError(err.code);
    return firebase.firestore();
  });

And then I call firestore in my actions file:
import firestore from "../firebase/firestore";

return firestore
  .then(db => {
    var newData = db
      .collection("Users")
      .doc(uid)
      .collection("userData")
      .doc();
    newData.set(data);
    var id = newData.id;
    dispatch(addData({ id, ...data }));
  })
  .catch(err => {
    // notification
  });

Essentially, I separated out my redux and Firestore, but ultimately they are connected through the Firestore id.


text:
Q: Does there exist a function such that $\int_{\mathbb{R}_+^{\star} } t^nf(t)dt=0$? Let $f\in C([a,b],\mathbb{R})$ such that $\displaystyle\int_{a}^{b} t^nf(t)dt=0$ for all integer n.
We know that $f\equiv 0$. It's "easy" to prove with Weierstrass theorem or with How to prove that $\,\,f\equiv 0,$ without using Weierstrass theorem?

*

*This theorem is wrong on $\mathbb{R^+}$, we can choose :
$$f(x)=\exp(-x^{\frac{1}{4}})\sin(x^\frac{1}{4})$$

Let
$$
I_n=\displaystyle\int_{0}^{+\infty}t^n\exp(-\omega t)dt=\frac{n!}{\omega^{n+1}},\quad n\in \mathbb{N}, \quad \omega=exp(\frac{i\pi}{4})
$$
Proof.
$$
|t^n\exp(-\omega t)|=t^n\exp \bigr(\frac{-t \sqrt{2}}{2}\bigl)\in L^1(\mathbb{R})
$$
by integration by parts we get
$$
I_n=\frac{n}{\omega}I_{n-1}
$$
Thus,
$$
I_n=\frac{n!}{\omega^{n+1}}
$$
Plus for $n\geq 1$, $\quad \omega^{4(n+1)}=-(1)^{n+1}$
Then,
$$
I_{4n+3}\in \mathbb{R}
$$
Therefore,
$$
0=\Im(I_{4n+3})=\displaystyle\int_{0}^{+\infty}x^nf(x)dx
$$

*

*Let $f:\mathbb{R}_+ \longrightarrow \mathbb{C}$,

I would like to prove the existence of a function $f$ such that $\int_{0}^{+\infty}t^n f(t)dt=0$,

In fact this example it's not mine (I have already read it in a book) and the question is to find $f:\mathbb{R}_+ \longrightarrow \mathbb{C}$. So I would like to know if we can proove the existence more generally or just how can I construct a such function.

Thank you in advance,

A: Start with your example, take the imaginary part, just user every fourth step with variable $t=s^{1/4}$.  We get:
$$
F(s) = \exp(-s^{1/4})\sin(s^{1/4}),
$$
for which
$$
\int_0^\infty s^n F(s)\;ds = 0
$$
for all nonnegative integers $n$.


text:
Q: Is there a way to create a plumber API in R with no parameters? I'm trying to return just a string or a data frame as soon as the API is pinged by the user. I'm using plumber to create this API. Unfortunately, I keep on getting a 404 error when I try to do this. Is this possible in plumber?
library(plumber)

#* Test plumber of API with no parameters
#* @response default array with corresponding responses
#* @serializer unboxedJSON
#* @post /Test

function(){

  return("Hello World!")
}

A: It works for me. Save your script as plumber_test.R, then open an R session and type
> library(plumber)
> reply_service <- pr('plumber_test.R')
> pr_run(reply_service, port=9494, host='127.0.0.1')

In another terminal try
$ curl -X POST http://127.0.0.1:9494/Test

And you should get back ["Hello World!"]


text:
Q: How to get the shortest time and longest time(or timespan) from a list using LINQ? I am trying to get the longest and shortest timespan in a list using LINQ.
My code looks something like this
List listofTimeSpans = new List();
adding the timespans to listofTimeSpans in a foreach loop.
Please help me with this.
Thank you.

A: I would create the list as
var listofTimeSpans = new List<TimeSpan>();

then
var min = listofTimeSpans.Min();
var max = listofTimeSpans.Max();

Regards.


text:
Q: How event handler inside JavaScript class/function got called? I'm quite new on JS and got stuck on this problem. So I have this constructor which I understand how its works EXCEPT for one thing. How does an event handler got called from inside of an object or function?
I thought event handler could only be placed on global scope directly, not inside a function/object or another block scopes.
class Counter {
    constructor(element, defaultValue) {
       this.element = element;
       this.value = defaultValue;

       this.valueDOM = element.querySelector('.value');
       this.valueDOM.textContent = this.value;

       this.increase = this.increase.bind(this);
       this.btnIncrease = element.querySelector('.increase');
       this.btnIncrease.addEventListener('click', this.increase);
    }
    increase() {
       this.value++;
       this.valueDOM.textContent = this.value;
    }
}

const counterOne = new Counter(document.querySelector('.counter-one'), 0);
const counterTwo = new Counter(document.querySelector('.counter-two'), 0);

The HTML is quite simple, just a plain old counter like this.

    0
    <button class="increase">+</button>

    0
    <button class="increase">+</button>

A: addEventListener in this case is pointing directly at the local object's this.increase method. It is not pointing at the object's prototype function, but an actual distinct copy of that function which is attached to the object instance. Does that help?


text:
Q: sections of the iOS app become black in some devices I have an app which is currently published, this one person reported a problem with an iPhone 7 iOS 13.5.1 where he could not use it, basically the background of a table view cell is completely black where on all other devices is white, because of that and since the text is black, this person can't read anything. Also in the search field he can't see what is being typed, there, the background is white and the text which is supposed to be black is white. We actually got a screenshot which is by the way not very clear but you can see a faded version of the text in both the search field and the table view.
We also have the same model and with the same OS version installed but are not seeing the issue, for now we have only gotten  report from this one person.
Has anyone experienced a similar issue that can point me to what the problem maybe?

A: You need to set your background color to white instead default.
"default" will set your background color in black if the device is in dark mode.

A: This looks to be an issue where your user has dark mode enabled, but your app appears to use a mixture of hardcoded and semantic colors.
As a quick workaround your can force your app to always use light mode by adding
<key>UIUserInterfaceStyle</key>
<string>Light</string>

to your Info.plist


text:
Q: (Apache + SVN) Group/IP-based Authentication/Authorization Assuming each user has a regular user-account "test" and an individual admin-account "test-adm" for a dedicated part on the server.
I want to grant access to an area on the server (SVN repository) when the user comes with an "admin-account" from a defined ip adress range. At the same time, this admin-account should have no write access to the rest of the server.
This admin-account should not work for the secured area from outside the ip adress range but there are other (LDAP) user groups that should be allowed to access the secured area with their regular user account.
Is there any approach to implement the concept of mutual exclusion in the scope of user access restriction within Apache?

Access Matrix to a "secured" repo

A:
I want to grant access to an area on the server (SVN repository) when
the user comes with an "admin-account" from a defined ip adress range

IP-based ACLs are out of scope for SVN's Path-Based Authorization - it knows only "user", "group", "path inside repo"entities

At the same time, this admin-account should have no write access to
the rest of the server.

This is also a responsibility of (Apache) backend, not SVN-part

This admin-account should not work for the secured area from outside
the ip adress range but there are other (LDAP) user groups,

You have even worse case - SVN can use usernames from another authorization layers in authz-file (even LDAP|AD), but haven't access to LDAP-groups, you have to transfer LDAP-groups to SVN (but some solutions already exist)
And when|if single user may have two roles (ro or rw), depending on conditions, it's job of authorization-subsystem outside of SVN to represent it as different users, you have to ask LDAP-guru about possibilities (this will be easier and faster, than include in another group and sync groups with SVN)


text:
Q: Add transparent color layer to b&w image using ImageMagick
I'm trying to take a black and white image and add a red transparent layer on top. Something similar to the image. Does anyone know how I can do this using ImageMagick in Node using gm?

A: I took @Bonzo suggestion and used blend. With Node gm you can call ImageMagick methods directly.
const gm = require('gm');
const im = gm.subClass({ imageMagick: true });

im()
.command('composite')
.in('-blend', '100x100')
.in('-gravity', 'center')
.in('/tmp/top.png')
.in('/tmp/bottom.png').toBuffer('PNG',function (err, buffer) { }


text:
Q: How do I keep track of requests issued/completed without the use of additional state variables? (Java/Grpc) I am using the StreamObserver class found in the grpc-java project to set up some bidirectional streaming.
When I run my program, I make an undetermined number of requests to the server, and I only want to call onCompleted() on the requestObserver once I have finished making all of the requests.
Currently, to solve this, I am using a variable "inFlight" to keep track of the requests that have been issued, and when a response comes back, I decrement "inFlight". So, something like this.
// issuing requests
while (haveRequests) {
    MessageRequest request = mkRequest();
    this.requestObserver.onNext(request);
    this.inFlight++;
}

// response observer
StreamObserver<Message> responseObserver = new StreamObserver<Message> {

    @Override
    public void onNext(Message response) {
        if (--this.onFlight == 0) {
            this.requestObserver.onCompleted();
        }

        // work on message
    }

    // other methods

}

A bit pseudo-codey, but this logic works. However, I would like to get rid of the "inFlight" variable if possible. Is there anything within the StreamObserver class that allows this sort of functionality, without the need of an additional variable to track state? Something that would tell the number of requests issued and when they completed.
I've tried inspecting the object within the intellij IDE debugger, but nothing is popping out to me.

A: To answer your direct question, you can simply call onComplete from the while loop.  All the messages passed to onNext.  Under the hood, gRPC will send what is called a "half close", indicating that it won't send any more messages, but it is willing to receive them.  Specifically:
// issuing requests
while (haveRequests) {
    MessageRequest request = mkRequest();
    this.requestObserver.onNext(request);
    this.inFlight++;
}
requestObserver.onCompleted();

This ensures that all responses are sent, and in the order that you sent them.  On the server side, when it sees the corresponding onCompleted callback, it can half-close its side of the connection by calling onComplete on its observer.  (There are two observers on the server side one for receiving info from the client, one for sending info).
Back on the client side, you just need to wait for the server to half close to know that all messages were received and processed.  Note that if there were any errors, you would get an onError callback instead.
If you don't know how many requests you are going to make on the client side, you might consider using an AtomicInteger, and call decrementAndGet when you get back a response.  If the return value is 0, you'll know all the requests have completed.


text:
Q: "Unable to find expected entry 'main/binary-i386/Packages' in Release file" I added a third party repository and now I'm seeing this warning while updating my packages list:
W: Failed to fetch http://codezen.org/debian/dists/sid/Release  Unable to find expected entry 'main/binary-i386/Packages' in Release file (Wrong sources.list entry or malformed file)

Why is that?

A: There are two causes but in your case is that you have configured multiarch to ask for i386 packages while that repository is amd64 exclusive. The same would be happened if you set arm64 or any other architecture as foreign architecture with dpkg.
There are three ways to go:

*

*If the repository should have amd64 packages, contact the maintainer and let them know.

*If you actually don't want/need foreigns architectures installed on your system you can disable them with dpkg --remove-architecture.

*You can set your sources.list to only ask for the architecture the repository is supposed to provide, so apt doesn't try to ask for them. Something like this:
deb [ arch=amd64 ] http://codezen.org/debian sid main

Other causes
This can also happen if components (main, contrib, security, etc.) or type of packages (sources vs binaries) aren't available in the repository. This can be identified by the string main/binary-i386/Packages. Here, main is the component, and binary the type of package, i386 the architecture.


text:
Q: How to persist value in select on automatic page reload I have JS code that stores a value in a select on page reload. This code works well, but it is attached to the submit button.
My code:

document.addEventListener('DOMContentLoaded', function() {
  var item = localStorage.getItem('test');
  var select = document.getElementById("test");
  select.value = item;
});

function submitForm() {
  var select = document.getElementById("test");
  var value = select.options[select.selectedIndex].value;
  localStorage.setItem('test', value);
}
<form method="POST" onsubmit="submitForm()">
  <select class="form-select" name="test" id="test">
    <option>Select value</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <input type="submit">
</form>

How do I change this code so that it also persists the value across reload when it happens automatically when the value changes by pasting this code into the form:
onchange="this.form.submit()"

I would like the page to reload automatically and still keep the value in the select.

A: Try using the beforeunload event listener instead of your submit function https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
document.addEventListener('beforeunload', function() {
    var select = document.getElementById("test");
  var value = select.options[select.selectedIndex].value;
  localStorage.setItem('test', value);
});


text:
Q: Why slice() is showing error but code run perfectly? I have written this code in js (developer.js) file.
app.filter('reverse', function() {
  return function(items) {
  return items.slice().reverse();
  };
});

now, this code i put because i needed to reverse the ng-repeat result, so I created manual filter.
But this code is working perfectly but its showing error in console.
And i don't want to see my console with all errors.
Error:
TypeError: Cannot call method 'slice' of undefined
    at Object.<anonymous> (http://192.168.0.14/test/js/developer.js:35:24)
    at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:69:187)
    at Ia.| (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:129:335)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:68:341
    at Ia.| (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:129:340)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:68:341
    at Object.e.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:88:347)
    at Object.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:147:244)
    at Object.e.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:86:286)
    at Object.e.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:88:506)

P.S.
This error will be shown first 4 times when i have total 6 values inside items.
items is having object array.
when I try to console items in filter, its for first 4 times, showing 'undefined' and then for last two times, its showing,
[Object, Object, Object, Object, Object, Object]

inside that objects, the values are defined
items hold this array of objects [data is coming in json form].
{
id: "51c2824088358f0d39000000",
name: "clientdemo",
key: ***,
secret: ***,
description: "It is good.",
icon_url: "/oauth2/static/media/images/icon/default.png"
},
{
id: "51c2cca588358f35aa000003",
name: "grantallllla",
key: ***,
secret: ***,
description: "This asdf",
icon_url: "/oauth2/static/media/images/icon/default.png"
},
{
id: "51d14e8c88358f6e96000024",
name: "12341234",
key: ***,
secret: ***,
description: "Enter descript12341234ion here",
icon_url: "/oauth2/static/media/images/icon/default.png"
},
{
id: "51d14e9888358f6e96000026",
name: "sdfgds345",
key: ***,
secret: ***,
description: "dsfasdfasdfasdf",
icon_url: "/oauth2/static/media/images/icon/default.png"
},
{
id: "51d1758888358f5171000002",
name: "1321",
key: ***,
secret: ***,
description: "zxcvzxcvcxvbxcvb",
icon_url: "/oauth2/static/media/images/icon/51c2819e88358f0d2a000000_1372701408_RhLW.jpg"
},
{
id: "51d3d8c588358f461a000002",
name: "sdafasdf",
key: ***,
secret: ***,
description: "asdfasdf",
icon_url: "/oauth2/static/media/images/icon/51c2819e88358f0d2a000000_1372857885_PSzB.jpg"
}

A: Have you tried handling the actual error?
Maybe just try this?
app.filter('reverse', function() {
  return function(items) {
    if( !items ){ return; } // This will take care of the error
    return items.slice().reverse();
  };
});

You may also want to know why some of your data is undefined, there may be an issue you may have to deal with.


text:
Q: Changing Nginx config for RabbitMQ to Kubernetes Ingress rules returns 404 queues or exchanges not found This is my nginx config for rabbitmq:
location ~* /rabbitmq-logger/api/(.*?)/(.*) {
    proxy_pass $rabbitmqlogger/api/$1/%2F/$2?$query_string;
    proxy_buffering                    off;
    proxy_set_header Host              $http_host;
    proxy_set_header X-Real-IP         $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

location ~* /rabbitmq-logger/(.*) {
    rewrite ^/rabbitmq-logger/(.*)$ /$1 break;
    proxy_pass $rabbitmqlogger;
    proxy_buffering                    off;
    proxy_set_header Host              $http_host;
    proxy_set_header X-Real-IP         $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

And these are my ingress rules:
 annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/proxy-buffering: "off"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "Host: $http_host";
      more_set_headers "X-Real-IP: $remote_addr";
      more_set_headers "X-Forwarded-Proto: $scheme";
      more_set_headers "X-Forwarded-For: $proxy_add_x_forwarded_for";

With the hosts:
  hosts:
    - host: somewebdomain
      paths: ["/rabbitmq-logger/(.*)"]
    - host: somewebdomain
      paths: ["/rabbitmq-logger/api/(.*?)/(.*)"]
    - host: localhost
      paths: ["/rabbitmq-logger/(.*)"]
    - host: localhost
      paths: ["/rabbitmq-logger/api/(.*?)/(.*)"]

I can successfully access and log in to RabbitMQ, but when I try to see for example exchanges I get:

Not found. The object you clicked on was not found; it may have been
deleted on the server.

Any help or advice will be highly appreciated. Thanks


text:
Q: Tensorflow returns error when trying to predict a simple two dimensional input I am running following code, trying to create a model to predict [a,b] --> [x,y]
model = tf.keras.Sequential([keras.layers.Dense(units=2, input_shape=[2])])
model.compile(optimizer='sgd', loss='mean_squared_error')
xs = np.array([[-1.0,1],[2,2]], dtype=float)
ys = np.array([[-2.0,2],[5,6]], dtype=float)
model.fit(xs, ys, epochs=1000)
res = model.predict([[2,2]])

And I am getting the following error:
Traceback (most recent call last):
  File "app.py", line 9, in <module>
    res = model.predict([[2,2]])
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py", line 1096, in predict
    x, check_steps=True, steps_name='steps', steps=steps)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py", line 2382, in _standardize_user_data
    exception_prefix='input')
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_utils.py", line 362, in standardize_input_data
    ' but got array with shape ' + str(data_shape))
ValueError: Error when checking input: expected dense_input to have shape (2,) but got array with shape (1,)

Not sure what am I doing wrong here, as the input for the predict() is a perfectly good 2D array.


text:
Q: Using Javascript object to set background-image with jQuery's .css() I am writing a front-end web app that provides weather conditions for the user's location. While the basic functionality is working, at the moment I'm trying to write the logic that allows the app to change the background of the body based upon the current weather conditions. To do this, I'm making use of the OpenWeatherMap API. A call to this API returns a JSON response, and among the many things returned, are two fields - id and icon. id returns a numerical code which determines the weather condition, like clear skies or broken clouds, and icon returns a string which determines if it's day or night.
To write the logic, I created a JS object which would have the id condition codes as the keys and the corresponding images as the values. Inside the .ajax() function, I have a switch block,  where I switch based on the id returned, and then use .css("background-image", "url(link)"); to set the background-image of the body.
The issue with the code is that - this way the browser doesn't seem to recognise the URL to the background-image. I see a GET - ...  404 not found error in the console. However, if instead of trying to access the URL to the image through the JS object, if I directly place the url to the image in .css(), it works. But of course that's not what I want.
Here's the JS object -
//object for images
var weatherConditions = {

    //Group 2xx: Thunderstorm
    '2xx' : 'http://www.weathersnapshot.com/wp-content/uploads/2014/04/414.jpg',

    //Group 3xx: Drizzle
    '3xx' : 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSsE4vZDsOCCsuE9X2WljNm0VewUdFj7onj438c9mD3_I6AfT71sA',

    //Group 5xx: Rain
    '5xx' : 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSsAlLmRls8CtL994qiwssqvQwdMNEI7yJcUUPWqNhMdtjGHExK',

    //Group 6xx: Snow
    '6xx': 'https://dl.dropbox.com/s/sywq7fk1u65lycf/6810006-snow-background.jpg?dl=0',

    //Group 800: Clear - day and night
    '800': ['https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTnYxZWx1uOc83uWxrTFfW7IiVj0XXMKM6fSdqS9U5kjh7Op_71WA', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQnSe0ASBAUAcsvEAkQqO28WFGCjLWAgODq9eosh2SBr9f4-_NI4Q'],

    //Group 80x: Clouds - day and night
    '8xx' : ['https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ_Fl9xNhT3AVwafZ2GeciqaqdLXosI-nPfhrVGvM7QFO0z0KQa', 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTgvOYSdZ7tHUybUfF5ydC2G97i78pv3hZ8jlX632lCu26VABGs3Q']

};

Note - I've tried hosting the images on dropbox too, as I thought the errors might be due to the image links themselves. But it had no effect.
This is a part of the switch block -
//---------get background-----------------
      var weatherID = data.weather[0].id;
      console.log("Weather ID = " + weatherID);

      switch(weatherID) {
        case 600: console.log(weatherConditions['6xx']);
                  $("body").css("background-image", "url(weatherConditions['6xx']");
                  break;
        case 800: console.log("inside clear sky weather");
                    $("body").css("background-image", "url(weatherConditions.8xx[0])");
                  break;
        case 803: //check for day or night
                  if(data.weather[0].icon.endsWith("d")) {
                    console.log("inside day weather");
                    $("body").css("background-image", "url(weatherConditions['8xx'][0])");
                  }
                  break;
        case 804: $("body").css("background-image", "url(http://www.weathersnapshot.com/wp-content/uploads/2014/04/414.jpg)");
      }

And here's the Pen with the full code.

A: "url(weatherConditions['6xx']" is exactly what it looks like. There is no substitution happening there, you're telling the browser to use weatherConditions['6xx'], literally, as the URL. (You're also missing the ) on that.)
You probably wanted to substitute:
$("body").css("background-image", "url(" + weatherConditions['6xx'] + ")");

In ES2015 (which you can use today with transpiling, and in months/a year/something without tranpiling) you could use a template string (quoted with backticks, using ${...} for placeholders):
$("body").css("background-image", `url(${weatherConditions['6xx']})`);

Here's an example using our Gravatars:

var gravatars = {
  "Manish": "https://www.gravatar.com/avatar/4657faf6aa5c4b2c01ce4fb6c63300ed?s=164&d=identicon&r=PG",
  "T.J.": "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=164&d=identicon&r=PG"
};
$("input[type=button]").on("click", function() {
  $(".holder").css("background-image", "url(" + gravatars[this.value] + ")");
});
.holder {
  display: inline-block;
  width: 164px;
  height: 163px;
}
<input type="button" value="Manish">
<input type="button" value="T.J.">


text:
Q: Reducing difference between two graphs by optimizing more than one variable in MATLAB/Python? Suppose 'h' is a function of x,y,z and t and it gives us a graph line (t,h) (simulated). At the same time we also have observed graph (observed values of h against t). How can I reduce the difference between observed (t,h) and simulated (t,h) graph by optimizing values of x,y and z? I want to change the simulated graph so that it imitates closer and closer to the observed graph in MATLAB/Python. In literature I have read that people have done same thing by Lavenberg-marquardt algorithm but don't know how to do it?

A: You are actually trying to fit the parameters x,y,z of the parametrized function h(x,y,z;t).
MATLAB
You're right that in MATLAB you should either use lsqcurvefit of the Optimization toolbox, or fit of the Curve Fitting Toolbox (I prefer the latter).
Looking at the documentation of lsqcurvefit:
x = lsqcurvefit(fun,x0,xdata,ydata);

It says in the documentation that you have a model F(x,xdata) with coefficients x and sample points xdata, and a set of measured values ydata. The function returns the least-squares parameter set x, with which your function is closest to the measured values.
Fitting algorithms usually need starting points, some implementations can choose randomly, in case of lsqcurvefit this is what x0 is for. If you have
h = @(x,y,z,t) ... %// actual function here
t_meas = ... %// actual measured times here
h_meas = ... %// actual measured data here

then in the conventions of lsqcurvefit,
fun   <--> @(params,t) h(params(1),params(2),params(3),t)
x0    <--> starting guess for [x,y,z]: [x0,y0,z0]
xdata <--> t_meas
ydata <--> h_meas

Your function h(x,y,z,t) should be vectorized in t, such that for vector input in t the return value is the same size as t. Then the call to lsqcurvefit will give you the optimal set of parameters:
x = lsqcurvefit(@(params,t) h(params(1),params(2),params(3),t),[x0,y0,z0],t_meas,h_meas);
h_fit = h(x(1),x(2),x(3),t_meas);  %// best guess from curve fitting

Python
In python, you'd have to use the scipy.optimize module, and something like scipy.optimize.curve_fit in particular. With the above conventions you need something along the lines of this:
import scipy.optimize as opt

popt,pcov = opt.curve_fit(lambda t,x,y,z: h(x,y,z,t), t_meas, y_meas, p0=[x0,y0,z0])

Note that the p0 starting array is optional, but all parameters will be set to 1 if it's missing. The result you need is the popt array, containing the optimal values for [x,y,z]:
x,y,z = popt
h_fit = h(x,y,z,t_meas)


text:
Q: Pass object's info to another activity I have a ListView that is populated with objects from an ArrayList.
When one of the items on the ListView is clicked, a new activity "Contact Info" is opened and displays the details of that contact.
I have a button "Edit" that when clicked, opens a new activity.
I want to fill the contact info with the info from the "Contact Info" activity.
I was able to do it with the onItemClick but I don't know how to do it using the button onClick.
Contacts.java:
https://imgur.com/LSlIcAi
ContactInfo.java:
https://imgur.com/uRhozED
Edit:
https://imgur.com/ND9sPPM

A: Use an Intent object, and use .putExtra() to put extra data on the intent.
When you are in the second activity, get the intent that started the activity with .getIntent(), and then use .getStringExtra() or any other data type you are using.
Example:
Putting extra data in Intent
Intent intent = new Intent(FirstActivity.this, ContactInfoActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

Retrieving data from Intent
String sessionId= getIntent().getStringExtra("EXTRA_SESSION_ID");

A: I finally fixed it.
I just had to add: int contactNo = (Integer)getIntent().getExtras().get(EXTRA_CONTACTNO);
inside the onCLick.
Thanks


text:
Q: How to convert a dataframe with daily returns to a dataframe index starting at 100 import pandas as pd
df = pd.read_excel('Daily Returns.xlsx', sheet_name='1')

My input dataframe:
       FECHA  TIGR US EQUITY  AMC US EQUITY  BBBY US EQUITY  BB US EQUITY
0 2019-03-14             NaN            NaN             NaN           NaN
1 2019-03-15             NaN       0.001381       -0.046092           NaN
2 2019-03-19             NaN      -0.016667       -0.002143           NaN
3 2019-03-20        0.365000       0.014237       -0.026485           NaN
4 2019-03-21       -0.043040       0.030749        0.022794           NaN
5 2019-03-22        0.035407      -0.023346       -0.015097     -0.036325
6 2019-03-25        0.044362       0.015936        0.012409     -0.021064

Desired dataframe:
       FECHA  TIGR US EQUITY  AMC US EQUITY  BBBY US EQUITY  BB US EQUITY
0 2019-03-14      100.000000     100.000000      100.000000    100.000000
1 2019-03-15      100.000000     100.138100       95.390800    100.000000
2 2019-03-19      100.000000      98.469098       95.186378    100.000000
3 2019-03-20      136.500000      99.871003       92.665366    100.000000
4 2019-03-21      130.625040     102.941936       94.777581    100.000000
5 2019-03-22      135.250081     100.538654       93.346724     96.367500
6 2019-03-25      141.250045     102.140838       94.505063     94.337615

A: You can achieve the desired behavior using cumsum():
from numpy import nan
import pandas as pd

df = pd.DataFrame.from_dict({
    'FECHA': ['2019-03-14', '2019-03-15', '2019-03-19', '2019-03-20', '2019-03-21', '2019-03-22', '2019-03-25'],
    'TIGR US EQUITY': [nan, nan, nan, .365, -.04304, .035407, .044362],
    'AMC US EQUITY': [nan, .001381, -.016667, .014237, .030749, -.023346, .015936],
    'BBBY US EQUITY': [nan, -.046092, -.002143, -.026485, .022794, -.015097, .012409],
    'BB US EQUITY': [nan, nan, nan ,nan, nan, -.036325, -.021064]
})

change_cols = ['TIGR US EQUITY', 'AMC US EQUITY', 'BBBY US EQUITY', 'BB US EQUITY']
df[change_cols] = (df[change_cols].cumsum() + 1) * 100
df[change_cols] = df[change_cols].fillna(100.0)
print(df)

Thanks to Matt for pointing out a better way of dealing with columns to update :)
output:
        FECHA  TIGR US EQUITY  AMC US EQUITY  BBBY US EQUITY  BB US EQUITY
0  2019-03-14        100.0000       100.0000        100.0000      100.0000
1  2019-03-15        100.0000       100.1381         95.3908      100.0000
2  2019-03-19        100.0000        98.4714         95.1765      100.0000
3  2019-03-20        136.5000        99.8951         92.5280      100.0000
4  2019-03-21        132.1960       102.9700         94.8074      100.0000
5  2019-03-22        135.7367       100.6354         93.2977       96.3675
6  2019-03-25        140.1729       102.2290         94.5386       94.2611

Keep in mind that values don't match exactly since I just have the first 6 decimal places from your preview, so there will be slight inaccuracies compared to the real data :)


text:
Q: How can I check if the message author has an admin role using Discord.js? I'm building a Discord bot and I want to have an if statement that will only proceed if the message author has an administrator role in the guild.
I've tried having role-specific permissions, but this means that there will have to be the exact same name role on all servers that the bot is on.
How can I check if the message author has an admin role? (The role has the administrator permission.)

A: These answers seem outdated:
Use: msg.member.roles.cache.has(roleID)

A: Some of the following code must be modified to use in the newest major Discord.js version (v12 at the time of this edit) due to the implementation of Managers.
There's really three different questions needed to be addressed here. They're all related, but each have different direct answers.

How do I check if the message author has an Admin role?

*

*The GuildMember that sent a message is accessed via the Message#member property, as opposed to Message#author which returns a User. Remember, a member has roles and permissions, not a user.

*A Collection of a member's roles can be retrieved with GuildMember#roles.

*You can search for a role two main ways:

*

*ID: Map#has()

*Property: Collection#find()
So, tying this all together:
if (message.member.roles.has'roleIDHere')) console.log('User is an admin.');

or
if (message.member.roles.find(role => role.name === 'Admin')) console.log('User is an admin.');

How do I check if the message author's role has the Administrator permission?

*

*Again, we need to use the GuildMember from Message#member.

*And again, we need to use the GuildMember#roles collection.

*And... déjà vu... you can search through a Collection with Collection#find().

*This time, you should specifically check Role#hasPermission() in the predicate function.

For example:
if (message.member.roles.find(role => role.hasPermission('Administrator'))) console.log('User is an admin.');

You can apply this concept to any specific role, too.

Best method for this situation...

How do I check if the message author has the Administrator permission?

*

*We continue to use Message#member to access the GuildMember.

*However, you can check all of a member's permissions at once via the GuildMember#hasPermission() method.

Consider this short example:
if (message.member.hasPermission('ADMINISTRATOR')) console.log('User is an admin.');

Quick, right?

Make sure you check that the message your client receives is not a DM before attempting to check if the user is an Admin. Message#member is undefined when the message isn't sent in a guild, and trying to use properties of it will throw an error.
Use this condition, which will stop if the message is a DM:
if (!message.guild) return;

A: On the GuildMember object, you have a hasPermission function available.
So you can just do member.hasPermission('ADMINISTRATOR')
If you are interested in all the other strings, that are permission resolvable, you can find them in the discord.js docs.


text:
Q: Making background image to center in Flex 4 CustomAppSkin Class
    <?xml version="1.0" encoding="utf-8"?>
<s:Skin name="CustomApplicationSkin"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        alpha.disabled="0.5">
    <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
    </s:states>

    <fx:Metadata>
        <![CDATA[
        [HostComponent("spark.components.Application")]
        ]]>
    </fx:Metadata>

    <!-- fill -->

    <s:BitmapImage id="img" fillMode="clip" horizontalCenter="0" verticalCenter="0"
                   source="@Embed('assets/images/bg_with_Steps.png')"
                   smooth="true"
                   left="0" right="0"
                   top="0" bottom="0" />

</s:Skin>

How can i align center the background image. This code is in my Skin class. My Main class....
<?xml version="1.0" encoding="utf-8"?>
<s:Application name="Spark_Application_skinClass_test"
               xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/halo"
               skinClass="CustomAppSkin">
    <s:layout>
        <s:VerticalLayout
            horizontalAlign="center"
            verticalAlign="middle"/>
    </s:layout>

</s:Application>

A: Try updating your CustomAppSkin to:
<?xml version="1.0" encoding="utf-8"?>
<s:Skin name="CustomApplicationSkin"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        alpha.disabled="0.5">
    <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
    </s:states>

    <fx:Metadata>
        <![CDATA[
        [HostComponent("spark.components.Application")]
        ]]>
    </fx:Metadata>

    <!-- fill -->
    <s:HGroup width="100%" height="100%" verticalAlign="middle" horizontalAlign="center">
        <s:BitmapImage id="img" fillMode="clip" horizontalCenter="0" verticalCenter="0"
                       source="@Embed('assets/images/bg_with_Steps.png')"
                       smooth="true"
                       left="0" right="0"
                       top="0" bottom="0" />
    </s:HGroup>
</s:Skin>


text:
Q: Visual basic and modules Im writing a application in visual basic to tell the user about their pc.
All this is in a module
Imports Microsoft.VisualBasic.Devices
Imports System.Management
Imports System.Net
Imports System.IO
Imports System.Windows.Forms
Imports System.Deployment.Application

Module ComputerSpecModule
    Public Enum infotypes
        ProcesserName
        VideocardName
        VideocardMem
    End Enum

    Public Function getinfo(ByVal infotype As infotypes) As String
        Dim info As New ComputerInfo : Dim value, vganame, vgamem, proc As String
        Dim searcher As New Management.ManagementObjectSearcher( _
            "root\CIMV2", "Select * FROM Win32_VideoController")
        Dim searcher1 As New Management.ManagementObjectSearcher( _
            "Select * FROM Win32_Processor")
        If infotype = infotypes.ProcesserName Then
            For Each queryObject As ManagementObject In searcher1.Get
                proc = queryObject.GetPropertyValue("Name").ToString
            Next
            value = proc
        ElseIf infotype = infotypes.VideocardName Then
            For Each queryObject As ManagementObject In searcher.Get
                vganame = queryObject.GetPropertyValue("Name").ToString
            Next
            value = vganame
        ElseIf infotype = infotypes.VideocardMem Then
            For Each queryObject As ManagementObject In searcher.Get
                vgamem = queryObject.GetPropertyValue("AdapterRAM").ToString
            Next
            value = Math.Round((((CDbl(Convert.ToDouble(Val(vgamem))) / 1024)) / 1024), 2) & " MB"
        End If
        Return value

    End Function

    Public oAddr As System.Net.IPAddress 'gets the ipv4 add
    Public sAddr As String

    Public EmailStarterMessage As String = "This message was sent by SpecMee. SpecMee is a light weight application designed to allow the users to find out the specifications of their machines. Please download this application free at http://www.wilson18.com/projects/SpecMee/" + _
    Environment.NewLine + _
    "" + _
    Environment.NewLine + _
    "" + _
    Environment.NewLine + _
    ""

    'PC SPEC CONTENT
    Public ComputerName As String = (My.Computer.Name.ToString)
    Public myOS As String = (My.Computer.Info.OSFullName)
    Public Processor As String = (getinfo(infotypes.ProcesserName))
    Public HDD As String = (Format((My.Computer.FileSystem.Drives.Item(0).TotalSize.ToString / 1024) / 1024 / 1024, "###,###,##0 GB"))
    Public RAM As String = (Format((My.Computer.Info.TotalPhysicalMemory / 1024) / 1024 / 1024, "###,###,##0 GB"))
    Public VideoCard As String = (getinfo(infotypes.VideocardName))
    Public VideoCardMemory As String = (getinfo(infotypes.VideocardMem))
    Public Function Resolution() As String
        Dim intx As Integer = Screen.PrimaryScreen.Bounds.Width
        Dim inty As Integer = Screen.PrimaryScreen.Bounds.Height
        Return intx & " x " & inty
    End Function
    Public Function InternalIPAddress()
        With System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
            oAddr = New System.Net.IPAddress(.AddressList(0).Address)
            InternalIPAddress = oAddr.ToString
        End With
    End Function
    Public Function ExternalIPAddress() As String
        Dim uri_val As New Uri("http://www.wilson18.com/projects/SpecMee/curip.php")
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri_val)

        request.Method = WebRequestMethods.Http.Get
        Dim response As HttpWebResponse = request.GetResponse()
        Dim reader As New StreamReader(response.GetResponseStream())
        Dim myip As String = reader.ReadToEnd()
        response.Close()
        Return myip
    End Function

    Public EmailContent As String = ("Computer Name: " & ComputerName & Environment.NewLine & "Operating System: " & myOS & Environment.NewLine & "Processor: " & Processor & Environment.NewLine & "Hard Drive Size : " & HDD & Environment.NewLine & "RAM: " & RAM & Environment.NewLine & "Graphics Card: " & VideoCard & Environment.NewLine & "Graphics Onboard Memory: " & VideoCardMemory & Environment.NewLine & "Resolution: " & Resolution() & Environment.NewLine & "Internal IP Address: " & InternalIPAddress() & Environment.NewLine & "External IP Address: " & ExternalIPAddress() & Environment.NewLine)

End Module

The problem I am having is that if one of the things in the module fails such as if the users graphics card does not have any onboard memory then it will fail.This is causing everything else to fail aswell...
I am very new to visual basic so ifyou could please excuse me if I have made any stupidly obvious errors and any suggestions are welcome
Thanks in advance.

A: Place the parts that can fail in a Try-Catch-statement
Public VideoCardMemory As String = getinfo(infotypes.VideocardMem)

Public Function getinfo(ByVal infotype As infotypes) As String
    Try
        ...
        value = ...
        ...
    Catch
        value = "Cannot be accessed!"
    End Try
    Return value
End Function


text:
Q: Laravel 5: use homestead in production It is good to use homestead in development.
But is it also good to use homestead in production?
If yes, should I run virtual box always?
If I host my app to clouding service, ex: AWS, how can homestead work?
Thanks

A: There's a script on Laravel's Github repo that tells you everything Homestead installs.
As far as using it in production, especially in AWS where you can easily choose another Linux box more suitable as a web server, I would seriously advise against it.


text:
Q: Parallel std::lists, removing items in list A based on state of items in list B? How would I accomplish the following?

List A is a series of Foos, list B is a series of doubles representing time remaining until the Foo at the ith position of List A is removed. That is, if a double in List B is less than zero, the Foo at the same position in List A as the less than zero double in List B is removed from List A and then the less-than-zero double is removed from List B.

List A:
A B C D E

List B (in seconds):
1.0 0.33 0.0 5.0 0.01

//1 tick of 0.33 seconds

List B:
0.67 0.0 -0.33 4.67 -0.32

//Remove offending List A elements based on state of List B
List A:
A B D

//Remove invalid List B elements
List B:
0.67 0.0 4.67

I'm thinking something along the lines of std::remove_if for List B, but how would I remove the items for List A if I do that? Sadly, iterators of different lists aren't compatible and, except using manual implementations, there is no way to iterate through a list AND know the index of each value.

A: You might want to consider using a list of structures instead of two lists. Then you can use remove_if and other list functions.


text:
Q: Java Scanner - Stop on last line I have a problem, in my program I want to read a .txt file with Scanner the txt file looks like:
10  2
20  3
30  5
40  6
750

I want to store each column in a List but the last row which is 750 to store separately in a int variable. I tried something like:
public class Testing {

    final static Charset ENCODING = StandardCharsets.UTF_8;

    public static LinkedHashMap<Integer, Integer> readTextFile() throws IOException {

LinkedHashMap<Integer, Integer> finalT = new LinkedHashMap<Integer, Integer>();
        int suma;
        List<Bancnota> bancnote = new ArrayList<Bancnota>();
        String userHomeFolder = System.getProperty("user.dir");
        String finalPath = userHomeFolder + "/src/atm/TEST.txt";
        Path path = Paths.get(finalPath);

        try (Scanner scanner = new Scanner(path, ENCODING.name())) {

            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                String arr[] = line.split(" ");
             if (arr.length == 2){

                finalT.put(scanner.nextInt(), scanner.nextInt());
                System.out.println(finalT);
         } else {

          suma = scanner.nextInt();
               }
             }
            scanner.close();
          }
        return finalT;
    }

But something is not working, when I delete 750 from text file and delete this part
String line = scanner.nextLine();
String arr[] = line.split(" ");

          if (arr.length == 2){

everything is working. Is there any way to make the scanner to stop at last row? Thank you

A: There are some problems here:
Your dataset 10  2. These Numbers are separated by two spaces " ", so your String.split method will result in an array with three entries. line.split(" ") -> {"10", "", "2"} unless you you use split("  ")
Then you are using the Scanner wrong. You read a full line with scanner.nextLine(); and then you are using scanner.nextInt() several times. But this will read the next number after the line you have already read.
I think you want to parse the Integers out of the line you have read.
So I think you want your lines
finalT.put(scanner.nextInt(), scanner.nextInt());
[...]
suma = scanner.nextInt();

to be something like this:
finalT.put(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]));
[...]
suma = Integer.parseInt(arr[0]);

A: change the while loop to below.
       while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String arr[] = line.split(" ");

            if (arr.length == 2) {

                finalT.put(Integer.parseInt(arr[0]),Integer.parseInt(arr[1]));
                System.out.println(finalT);
            } else {

                suma = Integer.parseInt(arr[0]);
            }
        }


text:
Q: Receiving GDAL Clipper Error from QGIS? I realise there has been quite a lot of discussion on this topic and have already read through the suggestions on this forum of how to rectify this problem, but still nothing has worked.
I am trying to clip a merged hillshade raster using a vector mask to define the clipped area.  I have turned on-the-fly-projection off and both layers align to the same CRS.  I am still getting the error message "cannot compute bounding box of cutline".
I have tried all the suggestions in previous posts, but nothing works!  This is getting so frustrating!  Does anyone have any further suggestions on how to solve this problem.
I am using QGIS Lyon 2.12.3, but I also get the same issue in 2.8.6 LTR version.
A link to the zip files is given below:
Attached Files

Also, when I clip using extents, it works no problems

A: The spatial reference of the tif is not defined. You will need to define it before proceeding with the clip.
C:\Users\frogman\Downloads>gdalinfo Hillshade_Wrap.tif

Driver: GTiff/GeoTIFF

Files: Hillshade_Wrap.tif

Size is 9600, 15120

**Coordinate System is **

Origin = (1773760.000000000000000,5897760.000000000000000)

Pixel Size = (1.000000000000000,-1.000000000000000)

Image Structure Metadata:

  INTERLEAVE=PIXEL

Corner Coordinates:

Upper Left  ( 1773760.000, 5897760.000)

Lower Left  ( 1773760.000, 5882640.000)

Upper Right ( 1783360.000, 5897760.000)

Lower Right ( 1783360.000, 5882640.000)

Center      ( 1778560.000, 5890200.000)

Band 1 Block=9600x1 Type=Float32, ColorInterp=Gray

Band 2 Block=9600x1 Type=Float32, ColorInterp=Alpha

Clip extents (as the extents exist) would work in this scenario but not clipper or extract by mask as the polygon does not overlay the raster.An FYI, the raster has 2 bands.


text:
Q: using value from select as parameter in spring form to get object by id When I select an option from a select box, in a form, I want to get the input fields of the form to get populated with the values from the object selected above every time the selection changes. Its purpose is to modify object after creation. I am using Spring MVC and Hibernate with JDBCTemplate.
listaProiecte is a List<Proiect>

Here is the form:
    <form:form method="post" id="modifica" action="/modifica" commandName="proiect">

                <sform:select path="idProiect" id="idProiectSelect"  cssClass="form-control input-sm">
                    <sform:option value="0" label="--- Select ---"/>
                    <c:forEach items="${listaProiecte}" var="proj">
                        <sform:option var="id" id="optiune"  value="${proj.idProiect}" label="${proj.nrProiect}  ${proj.numeProiect}"/>
                    </c:forEach>
                </sform:select>

                Nume Proiect
                <sform:input path="numeProiect" id="numeProiectInput" cssClass="form-control input-sm"/>

                Numar Proiect
                <sform:input path="nrProiect" id="nrProiectInput" cssClass="form-control input-sm"/>

                An
                <sform:input path="an" id="anInput" cssClass="form-control input-sm"/>

                Client
                <sform:select path="idClient" id="idClientInput" cssClass="form-control input-sm">
                    <option value="0" label="--- Select ---"/>
                    <c:forEach items="${listaClienti}" var="clnt">
                        <sform:option value="${clnt.idClient}" label="${clnt.client}"/>
                    </c:forEach>
                </sform:select>

                <button type="submit" class="btn " id="btnMod">
                    Modifica Proiect
                </button>

</form:form>

And the controller:
 @Qualifier("listaProiecteDAO")
    @Autowired
    private ListaProiecteJDBCDAO listaProiecteJDBCDAO;
    @Qualifier("clientiDAO")
    @Autowired
    private ClientiJDBCDAO clientiJDBCDAO;

    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String proiecte(ModelMap map) {

        map.addAttribute("proiect", new ListaProiecte());
        map.addAttribute("listaProiecte", listaProiecteJDBCDAO.getAll());
        map.addAttribute("client", new Client());
        map.addAttribute("listaClienti", clientiJDBCDAO.getAll());

        return "admin";
    }
     @RequestMapping(value = "/modifica", method = RequestMethod.POST)
    public String moddProiect(@ModelAttribute(value = "proiect") ListaProiecte proiect, BindingResult result) {

        listaProiecteJDBCDAO.update(proiect);
        return "redirect:/admin#modProj";
    }

And the JS I am trying to use on the change() event of the select:
 $("#idProiectSelect").change(function(){
    var id = $("#idProiectSelect").val();
   $("#numeProiectInput").val(${listaProiecte[id].numeProiect});
   $("#nrProiectInput").val(${listaProiecte[id].nrProiect);
   $("#anInput").val(${listaProiecte[id].an);
   $("#idClientInput").val(${listaProiecte[id].idClient);

});

And apparently EL in ecmascript doesn't work. What is a workaround for this?
How do I use the id from the select box as a parameter for my List?

A: Recommending to use freemarker and below mentioned is code to do the same.
This will be on the service side adding list of object to the model object.
@RequestMapping("/show")
    public String showFeesPage(Model model){
        model.addAttribute("batchlist", commonService.getBatchList());
        model.addAttribute("feeslist", commonService.getFeesList());
        return "fees";
    }

below mentioned u will be adding in the freemarker page.
<#list batchlist as batch>

    <option value="${batch.id}">${batch.batchName}</option>

</#list>


text:
Q: How to perform deep copying of struct with CUDA? Programming with CUDA I am facing a problem trying to copy some data from host to gpu.
I have 3 nested struct like these:
typedef struct {
    char data[128];
    short length;
} Cell;

typedef struct {
    Cell* elements;
    int height;
    int width;
} Matrix;

typedef struct {
    Matrix* tables;
    int count;
} Container;

So Container "includes" some Matrix elements, which in turn includes some Cell elements.
Let's suppose I dynamically allocate the host memory in this way:
Container c;
c.tables = malloc(20 * sizeof(Matrix));

for(int i = 0;i<20;i++){
    Matrix m;
    m.elements = malloc(100 * sizeof(Cell));
    c.tables[i] = m;
}

That is, a Container of 20 Matrix of 100 Cells each.

*

*How could I now copy this data to the device memory using cudaMemCpy()?

*Is there any good way to perform a deep copy of "struct of struct" from host to device?

Thanks for your time.
Andrea

A: The short answer is "just don't". There are four reasons why I say that:

*

*There is no deep copy functionality in the API

*The resulting code you will have to writeto set up and copy the structure you have described to the GPU will be ridiculously complex (about 4000 API calls at a minimum, and probably an intermediate kernel for your 20 Matrix of 100 Cells example)

*The GPU code using three levels of pointer indirection will have massively increased memory access latency and will break what little cache coherency is available on the GPU

*If you want to copy the data back to the host afterwards, you have the same problem in reverse

Consider using linear memory and indexing instead. It is portable between host and GPU, and the allocation and copy overhead is about 1% of the pointer based alternative.
If you really want to do this, leave a comment and I will try and dig up some old code examples which show what a complete folly nested pointers are on the GPU.


text:
Q: Getting error when fetching data with Next.js 13 I keep getting the following error when trying to fetch some JSON data using Next.js 13:
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I'm just looking to print out the titles from the JSON fetch. Not sure what might be causing the issue:
  async function getNotes() {
      const res = await fetch('https://jsonplaceholder.typicode.com/todos/')
      const data = await res.json();

      return data?.items as any[];
    }

    export default async function Page() {

      const notes = await getNotes();

      return (
        <>

hello

              {notes.map((note) => (

{note.title}

              ))}

        </>
      )
    }

A: You are trying to render a Promise object as a child of a React component
async function getNotes() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/');
  const data = await res.json();

  return data?.items as any[];
}

function NoteList() {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    async function fetchNotes() {
      const notes = await getNotes();
      setNotes(notes);
    }

    fetchNotes();
  }, []);

  return (

      {notes.map((note) => (

{note.title}

      ))}

  );
}


text:
Q: not able to download maven dependencies in spring tool Here is my pom.xml file, when i am importing the project,  its is showing error on the top line in pom.xml file as "failure to transfer xstream because its cached in the local directory, resolution will not be reattempted until the update interval of central has elapsed or updates are forced"
I am totally new to this please help me out.
I was learning through a tutorial Spring with JPA and Hibernate, but i am stuck with this please help me out, and thanks in advance
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.pluralsight</groupId>
  <artifactId>FitnessTracker</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>FitnessTracker Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.2.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.8</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

  </dependencies>
  <build>
    <finalName>FitnessTracker</finalName>
  </build>
</project>

A: Use -U parameter while building your project.
mvn clean install -U

If it does not work delete xstream's folder from your local maven repo and do
 mvn clean install -U


text:
Q: What does "stagger" mean in Overwatch? I frequently hear Overwatch players and commentators using the verb "stagger". What does this term refer to, and what is its significance?

A: Staggering refers to respawn timers. If all enemy players die at about the same time, they will respawn and be regrouped at about the same time. But if you let a baby d.va live for a few extra seconds, that delays their next push by that much


text:
Q: How to transfer a call using the PHP-SDK v2 API I've been in communication with the CallFire developers via email and really appreciate the help.  I have a question about a send call method from the example from the generated PHP-SDK v2 examples.php
Just to clarify I'm trying to accomplish, from a website I need to call a user, play a message, and then transfer to another number I will provide.
After searching the API documentation the word transfer occurs between 16 & 18 times for each SDK, but most of them are hidden, or have to do with Lease Configuration.  The other example I have found is contained in a XML transfer guide : https://answers.callfire.com/hc/en-us/articles/200769678-Transfer.
I know I can do this all in the PHP API but I need a little guidance.
In the PHP examples, liveMessageSoundid has 3 parameters in its json field, the integer is for the CallFire web backend but with machineMessage value it opens up a can of worms to follow, then machineMessageSoundId references transferMessage.  Transfering a call is what I need but transferNumber has values string/voice/string.  One of those strings must be the phone number but the SendCall method example never explicitly shows the transfer call command does it?
This is the example I'm working from which is building the json to transfer to CallFire.
   $request->getOperationConfig()->setBodyParameter("[phoneNumber" : "string",fromNumber" : "string",
                                                          "contactId" : integer,attributes" : [ "string" ],
                                                          "dialplanXml" : "string",liveMessage" : "string",
                                                          "liveMessageSoundId" : integer,machineMessage" : "string",
                                                          "machineMessageSoundId" : integer,transferMessage" : "string",
                                                          "transferMessageSoundId" : integer,transferDigit" : "string",
                                                          "transferNumber" : "string",voice" : "string"
                                                       }
                                                     ]");

This is what I have so far:
<?php

//These will be loaded from our site.
$number = "";
$name = "";
$rep_name = "";
$rep_number = "";

$live_message = "Hello," +$name+ " , Thank you for contacing Texas Home School Coalition, please stand by for a moment while we connect you to your representative.  Please have your statement ready regarding this important issue, we also left you a guide to read from on the action page you contacted us from":
$machine_message = "Hello, "+ $name +" , We received a request to give you a call from Texas Home School Coalition regarding an important issue for home schoolers and parents but we need you on the line in order to help you reach your representative.";

public static function main() {
    $client = \CallFire\Api\DocumentedClient::createClient("9dccec3d4ebb", "$PASSWORD");
    $request = $client->sendCalls();
    $request->getOperationConfig()->setHeaderParameters(array("Content-Type" => "application/json"));
    $body = '[
                {
            "defaultVoice" => "MALE1"
            "phoneNumber": "test_number",
            "fromNumber": "8067444441",
            "liveMessage": $live_message,
            "machineMessage": $machine_message,
            "transferMessage": $transfer_message,
            "transferNumber": $rep_number;
                }
             ]';
    $request->getOperationConfig()->setBodyParameter($body);
    $result = $client->request($request);
    $json = json_decode($result->getBody());
}

?>

A: as i mentioned in email - you code is correct, you just need to add one more param transferDigit to tell the system when to perform transfer.
These are all available params:
$request->getOperationConfig()->setBodyParameter("[
{
"phoneNumber" : "string",
"contactId" : integer,
"attributes" : [ "string" ],
"dialplanXml" : "string",
"liveMessage" : "string",
"liveMessageSoundId" : integer,
"machineMessage" : "string",
"machineMessageSoundId" : integer,
"transferMessage" : "string",
"transferMessageSoundId" : integer,
"transferDigit" : "string",
"transferNumber" : "string",
"voice" : "string"
}

So your body have to be like:
 {
                "defaultVoice" => "MALE1"
            "phoneNumber": "test_number",
            "fromNumber": "8067444441",
            "liveMessage": $live_message,
            "machineMessage": $machine_message,
            "transferMessage": $transfer_message,
            "transferNumber": $rep_number,
            "transferDigit" : "1 or 2 ....";
}

Please also regenerate code samples, i don't know where you found example with things like: "liveMessageSoundId" : integer,machineMessage".
Please see correct one


text:
Q: Do artifacts have to upload to gitlab to be reused between stages? I'm trying to use copy some Jars in my Dockerfile after I run a gradle build.
highlevel, the gitlab-yml has a build and a docker build and a deploy. I don't want to upload anything to gitlab artifact server, but simply just use the temporary files to build my image and publish it elsewhere. Is this possible? I'm wondering if artifacts implies an upload to the gitlab servers.

A: Artifacts are one way, but you can also use cache instead. Which one is the best option depends on your exact use case, but seems like the cache should work ok.
Alternatively, you can build the docker image, push it to the gitlab container registry, and pull it directly from there in later steps.


text:
Q: Galois group of $x^8+x^4+1$ As the title suggests, my objective is to characterize the Galois group of the splitting field of the polynomial $x^8+x^4+1$ over $\mathbb{Q}$. That is, if $L$ is the splitting field of $x^8+x^4+1$, I want to know what $\mathrm{Gal}(L/\mathbb{Q})$ is.
I know that the roots of the polynomial are
\begin{equation}
\sqrt[4]{\frac{-1\pm\sqrt{-3}}{2}}\zeta_4^k,
\end{equation}
where $\zeta_4$ is the 4-th root of unity. And here is where I have the rub: To find the splitting field $L$, I need to adjoin some of the roots above. Clearly I need to adjoin $\zeta_4$, whose degree is 2. Question is: What are the others? Do I adjoin only $\sqrt[4]{\frac{-1+\sqrt{-3}}{2}}$ (whose degree is 8, so the resulting degree of $L$ over $\mathbb{Q}$ is 16), or $\sqrt[4]{\frac{-1-\sqrt{-3}}{2}}$ as well?
I am new to this kind of question, so please guide me.
Thanks!

A: As Arthur mentioned, the roots are $12^{\text{th}}$ roots of $1$. Observe that $\zeta_{12}^8+\zeta_{12}^4+1=\zeta_{3}^2+\zeta_{3}+1=0$. So the four primitive $12^{\text{th}}$ roots of $1$ satisfy the polynomial. Similarly,
$\zeta_{6}^8+\zeta_{6}^4+1=\zeta_{3}+\zeta_{3}^2+1=0$, and $\zeta_{3}^8+\zeta_{3}^4+1=\zeta_{3}^2+\zeta_{3}+1=0$, which account for the remaining roots. Thus, the field you are interested in is just $\mathbb Q(\zeta_{12})$.
The Galois group of this field can be understood by its action on the group of $12^{\text{th}}$ roots of $1$, which is isomorphic to $\mathbb Z/12$. Since the primitive $12^{\text{th}}$ roots of $1$ are all conjugate, we may send any generator this group of roots to any other, and thus the Galois group is $\operatorname{Aut}(\mathbb Z/12)\cong (\mathbb Z/12)^\times\cong \mathbb Z/2\times \mathbb Z/2$.

A: Another way of looking at this:
\begin{align}
X^8+X^4+1&=(X^4-X^2+1)(X^2-X+1)(X^2+X+1)\\
&=\Phi_{12}\Phi_6\Phi_3\,,
\end{align}
where $\Phi_n$ is the cyclotomic polynomial, each irreducible, with roots the primitive $n$-th roots of unity.
So the splitting field is $\Bbb Q(\zeta_{12})$, Galois group well described by @BrettFrankel.


text:
Q: Unable to call the function to assign value to variable in constructor pattern in javascript I am trying to assign value to variable(chartWidth) by calling the method calculateChartWidth().
But I am facing the error that calculateChartWidth is not a defined function.
var ForceSimulationChart = function(){
    this.width = document.querySelector("svg").clientWidth;
    this.height = document.querySelector("svg").clientHeight;

    this.margin = {top:5, left:5, bottom:5, right:5 };

    //this.chartWidth = this.width - (this.margin.left+this.margin.right);
    //this.chartHeight = this.height - (this.margin.top+this.margin.bottom);

    this.chartWidth = this.calculateChartWidth();
    this.chartHeight = this.calculateChartHeight();

    this.svg = d3.select("#graph").append("svg");
    this.chartLayer = this.svg.append("g").classed("chartLayer", true);

    this.calculateChartWidth = function(){
        return this.width - (this.margin.left+this.margin.right);
    }

    this.calculateChartHeight = function(){
        return this.Height - (this.margin.top+this.margin,bottom);
    }
}

A: Your function isn't defined when you call it, from what I can see. You need to declare and define your function before your call this.chartWidth = calculateChartWidth();
Essentially, what you have is:
var dog = callUndefinedFunction();

var callUndefinedFunction = function() {
    // ...

When what you need is:
var callUndefinedFunction = function() {
    // ...
};

var dog = callDefinedFunction();

Looking at the code first code snippet (equivalent to what you have), you are - at the time of calling callUndefinedFunction - accessing an undefined variable: you haven't declared it or assigned a definition to it.
By moving the declaration of the variable and it's definition above the call (the second code block), you avoid this problem.
But Your Code Still Fails
I've gone back and modified your initial question - removing extraneous code; however, you will encounter the same problem with other code in your example, elsewhere, as you repeat this same problem in your call to calculateChartHeight.
calculateChartWidth failed because it was the first line to break in your code.
The rest will fail once that is resolved.
But You Like Your Ordering
Well, if you don't want to move a bunch of "stuff", you can read about hoisting in the context of Javascript. Functions are "hoisted" in Javascript differently than variables, so pay attention to that distinction.

A: Constructor functions are used to create instances of objects. They typically take arguments which are assigned as properties. See MDN's Working with objects
// Object Constructor Functions
function Credential(id, username, password) {
    this.id = id;
    this.username = username;
    this.password = password;
}

//push object to credentials array
try {
    credentials.push(new Credential(id, username, password));
}
catch (e) {
    console.log('Error: Failed Adding Credential ' + id + '.');
    return;
}


text:
Q: Should every job, SSIS project, SSRS have its own sql login Apologies for asking an opinion type question, but I'd like to know what is best practice.
I have a bunch of sql servers and every job as well as every connection manager for every SSRS report & SSIS project all use one login, sysadmin of course. I see it as a problem for two reasons:

*

*I would like every SSRS, SSIS etc to use their own logins with only the required permissions.

*I also would like to know immediately what's causing blocking etc., rather
than seeing one sysadmin login every time and then checking to see
what's running the offending query.

My fellow DBA believes this is madness due to the number of logins required (hundreds per server), suggesting one login per database with the db_datareader role would be more appropriate. Can anyone share links to articles or offer advice?
Thanks

A:
I have a bunch of sql servers and every job as well as every
  connection manager for every SSRS report & SSIS project all use one
  login, sysadmin of course.

Since you asked for best practices, by using sysadmin like that you are breaking The Principle of Least Privilege which states that:

[...] Administrative tasks are broken out using fixed server roles, and the
  use of the sysadmin fixed server role is severely restricted.

*

*I would like every SSRS, SSIS etc to use their own logins with only the required permissions.

I'd say creating and managing one login for each user, app, job or services would be going to the oposite extremity and that's a problem too, for, as your fellow DBA said, it would make it a really difficult job to manage so many logins, but you can achieve a middle term by using roles and Windows groups for that matter. Check the Principals doc.

*

*I also would like to know immediately what's causing blocking etc.,    rather than seeing one sysadmin login every time and then checking to
  see what's running the offending query.

Quoting @Dan Guzman's comment: For the purpose of identification, you can specify the application name in the connection string instead of separate logins.
Once you configured the Connection strings and application name you can retrieve it from sys.sysprocesses by using sp_who2, sp_whoisactive or sys.dm_exec_sessions DMV.


text:
Q: Template URL greyed out in SharePoint 2013
Do you know why this could be?
Another question: Is it possible to save a template in a different library (not the nameofmylibrary/Forms) ?? And just enter the link to the document..
Thank you!

A: Its because Content types are enabled. Forgot about that!

A: You can find and edit the template when you have created an custom content type. The template is located in .../Forms/[Name of your content type]/template.docx. Other template files are not in use anymore.


text:
Q: How to prevent Ansible / Jinja2 from randomly sorting my config I my Ansible config I have settings similar to
my_config:
  item1:
    var1: something
    var2: somethingelse
  item2:
    var1: something
    var2: somethingelse
  item2:
    var1: something
    var2: somethingelse

In a template file I have something similar to
{% for itm in my_config %}
  var1: {{ my_config[itm]['var1']}}
{% endfo %}

Now I noticed that Ansible or Jinja2 do not preserve order of my "items". I expected item1 to come before item2 etc but as it turns out Ansible or Jinja2 will perform some random sort if the items.
How can I render my template file in order of the config file? Without random sort?
Is it possible to sort on for example var1 value? How?

A: Depending on version of Python (Ansible is written in Python) dictionary keys are sorted or not. So, you can't depend on keys' order, instead you just need to create a list (which is ordered by design):
my_config:
- name: item1
  var1: something
  var2: somethingelse
- name: item2
  var1: something
  var2: somethingels
- name: item3
  var1: something
  var2: somethingelse

And then in Jinja:
{% for item in my_config %}
  var1: {{ item['var1'] }}
{% endfor %}


text:
Q: Discrete Mathematics: Prove Expression Is Even I'm brushing up for my Discrete Math final exam, and would like to know if the following proof is valid...

Prove by direct proof that $a^2-5a+8$ is even for any integer $a$.
Proof: By factoring, we achieve $a(a-5)+8$.
Suppose $a$ is an even integer. Then $a(a-5)$ would be even, as the product of an even integer and another integer is an even integer. So, $a(a-5)+8$ would also be even, as the sum of an even integer and an even integer is even.
Suppose $a$ is an odd integer. Then $a-5$ would be even, as the difference of two odd integers is even. So, $a(a-5)$ would also be even, as the product of an even integer and another integer is an even integer. So, $a(a-5)+8$ would also be even, as the sum of an even integer and an even integer is even.
Therefore, for any integer $a$, $a^2-5a+8$ will be even.

Let me know if this is a valid & satisfactory formal proof, or of anything I could change or improve.
Thanks!
Sam


text:
Q: Android Get height of the visible layout programmatically I want to get the exact height of the visible layout programmatically as I shown in figure. I used Sherlock fragment activity as main activity which contain different fragments. I tried to get the height and width of the screen through Display and display matrix, but it give whole screen height and width.but i want to get only visible view of the child activity. please help me. thanks in advance.

Main XML(of Tabbar)

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="@dimen/fr_layout_width"
                android:layout_height="@dimen/fr_layout_height"
                android:layout_weight="0" />

            <FrameLayout
                android:id="@+android:id/realtabcontent"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/fr_layout_height"
                android:layout_weight="1" />

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/hdpi_tab_layout_height"
                android:layout_weight="0"
                android:background="@android:color/transparent"
                android:gravity="bottom"
                android:orientation="horizontal" />
        </LinearLayout>
    </TabHost>
</android.support.v4.widget.DrawerLayout>

child xml (Xml of child Activity)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainscroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/topliner"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
         >

    </LinearLayout>

 </ScrollView>

A: It will get height of the whole window
Display display = getWindowManager().getDefaultDisplay();
Displayheight = display.getHeight();

Now take take height of ActionBar
ActionBar actionBar = getActionBar();
actionBarHeight = actionBar.getHeight();

let's take one tabHost & it's height for ex.
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, vTab1.class);
spec = tabHost.newTabSpec("First").setIndicator("First").setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, vTab2.class);
spec = tabHost.newTabSpec("Second").setIndicator("Second").setContent(intent);tabHost.addTab(spec);
int height = tabHost.getTabWidget().getHeight();

Now subtract Height of actionbar & tabWidget from Window Height
DesiredArea = DisplayHeight - (actionBarHeight + height);

this might be the solution or you can use similar type of logic.. i'm not telling this vl definately work.

A: Sorry for Disturb , I solved my question for getting some ideas through other answer but i see some deprecated method which is suggested to solve it.
for actionbar And tabbar height
     int tabHeight = mTabHost.getTabWidget().getHeight();
     int actionbarheight = getSupportActionBar().getHeight();//getActionbar() insted of for Api greater 13 than

height of statusbar
public int getStatusBarHeight() {
      int result = 0;
      int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
      if (resourceId > 0) {
          result = getResources().getDimensionPixelSize(resourceId);
      }
      return result;
}

 int statusbarheight = getStatusBarHeight();

for getting screen size
     Display display = getWindowManager().getDefaultDisplay();

    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2)
    {

        width = display.getWidth();  // deprecated
        height = display.getHeight()- (tabHeight + actionbarheight + statusbarheight );
    }
    else {

        Point size1 = new Point();
        display.getSize(size1);
        width = size1.x;
        height = size1.y - (tabHeight + actionbarheight + statusbarheight);//visible layout height
    }

A: int height = getWindow().getWindowManager().getDefaultDisplay().getHeight();


text:
Q: Bare bones PHP proxy I'm not a PHP guy, but I need to set up a bare bones proxy for a web service.  As an example, let's use google.  Let's say that I have a proxy server set up at: http://mydumbproxy.com/index.php and I want it to act just like http://www.google.com/search.  So for instance, if someone typed in the url http://mydumbproxy.com/index.php?q=dancing+banana, they would get the same thing as if they had typed in http://www.google.com/search?q=dancing+banana
How would I do this?
Note: Eventually this will become more than a straight passthrough.  It will provide a security layer between the public at large and dangerous access of the base web service.

A: This is probably a move in the right direction:
fpassthru(fopen('http://www.google.com/search?' . $_SERVER['QUERY_STRING'], 'r'));

A: After starting with Franks answer and googling a bit and put this scrap together which seems to do what I want:
<?php
echo file_get_contents('http://www.example.com/search?' . $_SERVER['QUERY_STRING'], 'r');
?>


text:
Q: Ratio of geodesic segments on the sphere Let $\mathbb{S}^2$ be the unit sphere. Let $0<\lambda<1$ be fixed. What is the smallest number $0<\mu<1$ (depending on $\lambda$) such that for any three points $A,B,C\in \mathbb{S}^2$, with $d(C,A)\le \pi/2, d(C,B)\le \pi/2$, one has $d(A_{\lambda},B_{\lambda})\le \mu d(A,B)$. Here $A_{\lambda}$ and $B_{\lambda}$ are points on the geodesic paths $[A,C]$ and $[B,C]$ such that $d(A_{\lambda},C)=\lambda d(A,C)$ and $d(B_{\lambda},C)=\lambda d(B,C)$. ($d$ is the geodesic distance.)
My conjecture is $\sin(\lambda\pi/2)$. Is this correct?

A: Yes, this is correct.
Since you've found this result, I'll assume that you figured out the case where $A$ and $B$ are at equal distance from $C$, and it remains only to be shown that this is the worst case. Let me know if you'd like me to write more on the simpler case.
We can write $A$ and $B$ in spherical coordinates with $C$ at one pole and $A$ at $\phi=0$:
$$A=\pmatrix{\sin\theta_A\\0\\\cos\theta_A},\quad B=\pmatrix{\sin\theta_B\cos\phi\\\sin\theta_B\sin\phi\\\cos\theta_B}\;.$$
Then
$$A_\lambda=\pmatrix{\sin\lambda\theta_A\\0\\\cos\lambda\theta_A},\quad B_\lambda=\pmatrix{\sin\lambda\theta_B\cos\phi\\\sin\lambda\theta_B\sin\phi\\\cos\lambda\theta_B}\;,$$
and the geodesic distances are the arccosines of the scalar products:
$$
\begin{eqnarray}
d(A,B)&=&\arccos\left(\sin\theta_A\sin\theta_B\cos\phi+\cos\theta_A\cos\theta_B\right)\;,\\
d(A_\lambda,B_\lambda)&=&\arccos\left(\sin\lambda\theta_A\sin\lambda\theta_B\cos\phi+\cos\lambda\theta_A\cos\lambda\theta_B\right)\;.
\end{eqnarray}
$$
We can rewrite them in terms of $\Sigma=\theta_A+\theta_B$ and $\Delta=\theta_A-\theta_B$:
$$
\begin{eqnarray}
d(A,B)&=&\arccos\frac12\left((1-\cos\phi)\cos\Sigma+(1+\cos\phi)\cos\Delta
\right)\;,\\
d(A_\lambda,B_\lambda)&=&
\arccos\frac12\left((1-\cos\phi)\cos\lambda\Sigma+(1+\cos\phi)\cos\lambda\Delta\right)
\;.
\end{eqnarray}
$$
To see where the desired inequality is most strongly violated, we can differentiate the discrepancy with respect to $\Delta$:
$$\frac{\partial}{\partial\Delta}\left(d(A_\lambda,B_\lambda)-\mu d(A,B)\right)=\frac12(1+\cos\phi)\left(\frac{\lambda\sin\lambda\Delta}{\sin d(A_\lambda,B_\lambda)}-\mu\frac{\sin\Delta}{\sin d(A,B)}\right)\;.$$
Since we already know $\mu\ge\sin(\lambda\pi/2)\ge\lambda$, we must have $d(A_\lambda,B_\lambda)\gt\lambda d(A,B)$ for the inequality to be violated, and thus $\sin d(A_\lambda,B_\lambda)\gt\lambda \sin d(A,B)$. As all the quantities are non-negative (since $\theta\le\pi/2$ and $0\lt\lambda\lt1$), we can bound the derivative thus:
$$
\begin{eqnarray}
\frac{\partial}{\partial\Delta}\left(d(A_\lambda,B_\lambda)-\mu d(A,B)\right)
&\le&
\frac12(1+\cos\phi)\left(\frac{\lambda\sin\lambda\Delta}{\lambda\sin d(A,B)}-\mu\frac{\sin\Delta}{\sin d(A,B)}\right)\\
&=&
\frac12\frac{1+\cos\phi}{\sin d(A,B)}\left(\sin\lambda\Delta-\mu\sin\Delta\right)\\
&\le&
\frac12\frac{1+\cos\phi}{\sin d(A,B)}\left(\sin\lambda\Delta-\sin\frac{\lambda\pi}2\sin\Delta\right)\\
&\le&0\;.
\end{eqnarray}
$$
Thus, the discrepancy is non-increasing wherever it is non-negative, and hence for it to be positive anywhere, it would have to be positive at $\Delta=0$. It therefore suffices to treat that case, which leads to the result you found.


text:
Q: Multiple values for a single row My site allows the user to attach multiple tags to their post (much like StackOverflow).
Is it better to store the tags in a single column, i.e.:
posts table
+---------+--------------------+
| post_id |        tags        |
+---------+--------------------+
|       1 | first,second,third |
|       2 | first              |
|       3 | first,third        |
+---------+--------------------+

Or is it better to create a separate table to hold the tags separately, i.e.:
post_tags table
+---------+--------+
| post_id |  tag   |
+---------+--------+
|       1 | first  |
|       1 | second |
|       1 | third  |
|       2 | first  |
|       3 | first  |
|       3 | third  |
+---------+--------+

Thanks!

A: It's a matter of preference, at least that's the way I see it.
Let's say you choose option post_table
You want to present the number of post for a given tag in a webpage. To do that you'll need to do a query using LIKE (or MATCH AGAINST if the tags column has a FULLTEXT index which is better). For example:
SELECT count(post_id) FROM post_table WHERE tags LIKE '%first%';

Will give you the number of post that have the "first" tag. (thanks to a comment I realized that if various tags have the "first" word in it, then it will give you an incorrect count of posts with the tag "first")
If you choose the option post_tags
You'll need a simple query like this:
SELECT count(post_id) FROM post_tags WHERE tag = 'first';

Since the first option could cause incorrect results to be retrieved from the tables, the second would be the only option to choose.
P.D. You can also create a separate "tag_table" to hold the tags with a numeric ID for each one, and also an union table "post_rel_tags" to hold the ID of the post and the ID of the tag. This way you save space in the database because you're dealing just with numeric values to make the relationships, but queries won't be so simple (actually they're simple, but with the options you proposed, they're even more simpler)

A: Your question can be rephrased as follows: Is it better to adhere to first normal form (1NF) or not?
When a table in 1NF is queried, a single value can always be obtained by a keyed search.  Keyed searches use indexes when they are available and relevant.  This is why 1NF was devised.
If you never have to search for tags, then suit yourself.  But why would you use a database in that case?


text:
Q: Multiple conditions on select query I have a select statement and I wish to calculate the cubic volume based on other values within the table. However I want to check that neither pr.Length_mm or pr.Width_mm or pr.Height_mm are NULL prior. I've looked at CASE statements, however it only seems to evaluate one column at a time.
SELECT
      sa.OrderName,
      sa.OrderType,
      pr.Volume_UOM
 ,pr.Length_mm*pr.Width_mm*pr.Height_mm AS Volume_Cubic
 ,pr.Length_mm*pr.Width_mm AS Volume_Floor
 ,pr.Length_mm
 ,pr.Height_mm
 ,pr.Width_mm
FROM CostToServe_MCB.staging.Sale sa
LEFT JOIN staging.Product pr
ON sa.ID = pr.ID

A: SELECT pr.Volume_UOM
 ,pr.Length_mm*pr.Width_mm*pr.Height_mm AS Volume_Cubic
 ,pr.Length_mm*pr.Width_mm AS Volume_Floor
 ,pr.Length_mm
 ,pr.Height_mm
 ,pr.Width_mm
FROM CostToServe_MCB.staging.Sale sa
LEFT JOIN staging.Product pr
ON sa.ID = pr.ID
and pr.Length_mm is not null
and pr.Width_mm is not null
and pr.Height_mm is not null

A: SELECT pr.Volume_UOM
 ,pr.Length_mm*pr.Width_mm*pr.Height_mm AS Volume_Cubic
 ,pr.Length_mm*pr.Width_mm AS Volume_Floor
 ,pr.Length_mm
 ,pr.Height_mm
 ,pr.Width_mm
FROM CostToServe_MCB.staging.Sale sa
    LEFT JOIN staging.Product pr ON sa.ID = pr.ID
where pr.Length_mm is not null and pr.Width_mm is not null and pr.Height_mm is not null

A: where pr.Length_mm is not null
  and pr.Width_mm is not null
  and pr.Height_mm is not NULL


text:
Q: isnt there any descriptive step by step guide for MAAS + juju + Ceph + Openstach HA deployment? I know this is the guide - https://wiki.ubuntu.com/ServerTeam/OpenStackHA , but Its not just descriptive enough? I saw in few question's answers that above link is still yet to be updated, but when?
I really want to use juju for openstack deployment, but its lacking in documentation, that's really annoying.


text:
Q: How to store variables in a db and then interpolate them on retrieval I have in my mysql db the following value for the 'statement' field:
on the $x day of $month
Then when i fetch it out of the db, I want to be able to define the variables and then echo out the statement with the variables being interpolated.
like this:
$x = '4th';
$month = 'july';
// query and fetch..
$sentence = $result['statement'];
echo $sentence;  // I want this to read 'on the 4th day of july'

the problem is all that i get is 'on the $x day of $month'.
I've tried putting quotes and double quotes around things, but just can't figure out how do to this.

A: If I understand you right you want to put variable name into database?
You have two options:
Ugly and dirty
Save to database:
'Something on'.$x.' day of '.$month.' will happen';
To call it:
echo eval($sentence);
Eval will execute everything what you will give so it's very unsafe.
Nice and more safe:
Save to database:
Something on %s day of %s will happen
To call it:
echo sprintf($sentence, $x, $month);
sprintf will format string and "validate" variables for you. For example if you will put %d in sentence then sprintf will want a integer there.


text:
Q: Authorizing REST API calls to GCP I am totally new to GCP products. I am trying to create and manage the resources i.e. Virtual Machines using the REST API's provided in the documentation. One of the endpoints which I am trying is
GET https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances?key={API_KEY}

Though to make authorized calls to the platform I need to configure the OAuth 2.0 authentication for which I created the relevant service account. I am not sure how to further use it to authorize the requests. Any leads on this would be greatly helpful. Thanks!
Edit:
I intend to call the REST APIs from Python. Not sure if that's the right way.

A: I was finally able to authorize the API calls to GCP by creating JWT, serializing it to UTF-8 representation (UTF-8 is important), signing it using the google client library google.auth and finally making a request to https://oauth2.googleapis.com/token having passed POST parameters grant_type = urn:ietf:params:oauth:grant-type:jwt-bearer and assertion whose value is the signed jwt for the token using the signed JWT token.
Reference: https://developers.google.com/identity/protocols/oauth2


text:
Q: Erase all elements from vector until first non-zero element C++ I have a vector that will store a variable number of zero elements at its beginning. These need to be erased.
I have tried:
while(v.at(0) == 0)
{
    v.erase(v.begin());
}

But this throws out an std::out_of_range error.
Any assistance would be appreciated.

A: You can use std::find_if to find the first non-zero value and then erase those elements:
auto first_non_zero = std::find_if(begin(v), end(v), [](int n){ return n != 0; });
v.erase(begin(v), first_non_zero);

(live demo)