text:
Q: Present a rotatable view controller over another view controller locked to portrait orientation on iOS 8 I have a fullscreen view controller, let's call it the background view controller, that is my root view controller. I want to present a view controller on top of it, in the foreground, that doesn't fill the screen. I've done this somewhat successfully using self.presentViewController() with the foreground view controller's modalPresentationStyle set to OverCurrentContext.
My problem is that I want my background view controller to stay locked to portrait, and I want my foreground view controller to be able to rotate with the device. So far I've been able to rotate the foreground view controller, but the background view controller rotates with it. Both view controllers control UIScrollViews, if that make a difference.
I've tried overriding supportedInterfaceOrientations() and setting it to Portrait and All for the background and foreground view controller respectively, but that results in nothing rotating at all. I've also tried playing with shouldAutorotate() but that didn't help.
How can I accomplish this? Thanks in advance.


text:
Q: service worker cache takes time to respond with latency This is my first interaction for using service workers to cache some stuff. As part of my POC i am trying to cache assets like "js", "css" ,
i am using sw-toolbox

(function (global) {
  'use strict';

  // Ensure that our service worker takes control of the page as soon as possible.

  global.addEventListener('install', function (event) {
    return event.waitUntil(global.skipWaiting());
  });
  global.addEventListener('activate', function (event) {
    return event.waitUntil(global.clients.claim());
  });

  // The route for any requests from the googleapis origin
  toolbox.router.get('/(.*)', global.toolbox.cacheFirst, {
    cache: {
      name: 'modjs',
      maxEntries: 30,
      maxAgeSeconds: 86400
    },
    debug: true,
    origin: /\.abc\.com\:8044$/
  });
})(self);

I can see network calls are coming from service workers but they are still showing some latency.
Let me what is wrong ?

A: For better page rendering performance, try to linked the .css files after the .js files. Check the ordering of the files. Make sure also that the user have access to the script file. The project might had their web.config denying access to anonymous users.

Uncaught ReferenceError bassically means you are trying to access a variable or function that has not been defined yet.
For more details, kindly check this document: https://developers.google.com/web/showcase/2015/service-workers-iowa#top_of_page

redpajama_set_name: RedPajamaStackExchange


text:
Q: mojofailureException in Graphhopper I am new to such complex solutions and some environments.
I am trying to get a control over Graphhopper solution.
I have cloned it from GIT, and tried to compile and run it from bash with
$ ./graphhopper.sh web slovenia-latest.osm.pbf

## using java 1.8.0_161 (64bit) from
## using existing osm file slovenia-latest.osm.pbf
## building graphhopper jar: tools/target/graphhopper-tools-0.10-SNAPSHOT-jar-with-dependencies.jar
## using maven at C:\Martin\WS5\Graphhopper\graphhopper\maven
## compilation of parent failed
[INFO] Scanning for projects...
[WARNING] The project com.graphhopper:graphhopper-parent:pom:0.10-SNAPSHOT uses prerequisites which is only intended for maven-plugin projects but not for non maven-plugin projects. For such purposes you should use the maven-enforcer-plugin. See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] GraphHopper Parent Project
[INFO] GraphHopper Core
[INFO] GraphHopper Reader for OpenStreetMap Data
[INFO] GraphHopper Reader JSON
[INFO] GraphHopper Tools
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building GraphHopper Parent Project 0.10-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building GraphHopper Core 0.10-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ graphhopper-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] Copying 48 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.5.1:compile (default-compile) @ graphhopper-core ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 288 source files to C:\Martin\WS5\Graphhopper\graphhopper2\core\target\classes
[WARNING] Unable to autodetect 'javac' path, using 'javac' from the environment.
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] GraphHopper Parent Project ......................... SUCCESS [  0.160 s]
[INFO] GraphHopper Core ................................... FAILURE [  4.929 s]
[INFO] GraphHopper Reader for OpenStreetMap Data .......... SKIPPED
[INFO] GraphHopper Reader JSON ............................ SKIPPED
[INFO] GraphHopper Tools .................................. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.339 s
[INFO] Finished at: 2018-02-11T18:36:38+01:00
[INFO] Final Memory: 12M/114M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (default-compile) on project graphhopper-core: Compilation failure -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :graphhopper-core

It seems that the "core" is not compiled due to MojoFailureException, but I have no idea how to fix it.
On the other hand, I can open the project with IntelliJ, and try to run graphhopper.sh from there, I get
"C:\Program Files\Java\jdk1.8.0_161\bin\java" -Dmaven.multiModuleProjectDirectory=C:\Martin\WS5\Graphhopper\graphhopper2 "-Dmaven.home=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.4\plugins\maven\lib\maven3" "-Dclassworlds.conf=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.4\plugins\maven\lib\maven3\bin\m2.conf" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.4\lib\idea_rt.jar=59256:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.4\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar" org.codehaus.classworlds.Launcher -Didea.version=2017.3.4
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] GraphHopper Parent Project
[INFO] GraphHopper Core
[INFO] GraphHopper Reader for OpenStreetMap Data
[INFO] GraphHopper Reader for Gtfs Data
[INFO] GraphHopper Reader JSON
[INFO] GraphHopper Tools
[INFO] GraphHopper Directions API hand-crafted Java Client.
[INFO] GraphHopper Web
[INFO] GraphHopper Reader for Shapefile Data
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] GraphHopper Parent Project ......................... SKIPPED
[INFO] GraphHopper Core ................................... SKIPPED
[INFO] GraphHopper Reader for OpenStreetMap Data .......... SKIPPED
[INFO] GraphHopper Reader for Gtfs Data ................... SKIPPED
[INFO] GraphHopper Reader JSON ............................ SKIPPED
[INFO] GraphHopper Tools .................................. SKIPPED
[INFO] GraphHopper Directions API hand-crafted Java Client. SKIPPED
[INFO] GraphHopper Web .................................... SKIPPED
[INFO] GraphHopper Reader for Shapefile Data .............. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.270 s
[INFO] Finished at: 2018-02-11T19:06:34+01:00
[INFO] Final Memory: 7M/77M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException

I also don't know where and which goals should I set... :/
Any help is appreciated, thank you!


text:
Q: docker-compose how to pass all env vars from .env file to container without explicitly defining them in compose file? Say I have hundreds of env vars defined in .env file
ENV1=blah
...
ENV100=foo

Is there a way so that docker-compose doesn't require me to define them again in the docker-compose.yml file?
eg.
services:
  my_app:
    restart: always
    image: some_image
    hostname: my_app
    environment:
      - pass all from .env

A: Thanks to my colleague, I missed the section that I can point to an .env file within a service
services:
  my_app:
    restart: always
    image: some_image
    hostname: my_app
    env_file:
      - ../.env


text:
Q: Create a list of items within 'var response' I have the following code:
var request = new GeocodingRequest();
request.Address = postcode;
request.Sensor = "false";
var response = GeocodingService.GetResponse(request);

var result = response.Results. ...?

I'd very much like to get result as a list, but I can't seem to convert it.  I know I can do something like response.Results.ToList<string>();, but have had no luck.
Can anyone help please :)

A: Well you can just use:
GeocodingResult[] results = response.Results;

or
List<GeocodingResult> results = response.Results.ToList();

If you want a list of strings, you'll need to decide how you want to convert each result into a string. For example, you might use:
List<string> results = response.Results
                               .Select(result => result.FormattedAddress)
                               .ToList();

A: It is defined as:
    [JsonProperty("results")]
    public GeocodingResult[] Results { get; set; }

if you want to make it list call: response.Results.ToList().
But why do you want to make it list? You can insert items into list, but I don't think you need it.

A: assuming response.Results is IEnumerable, just make sure System.Linq is available as a namespace and say response.Results.ToList()


text:
Q: Python regex match issue and grouping multiple groups I am trying to parse a command output, which looks like:
2.437 GHz (Channel 6)
Quality=39/70  Signal level=-71 dBm
Encryption key:on
ESSID:"testssid"
IE: IEEE 802.11i/WPA2 Version 1
IE: WPA Version 1

..and essentially convert it to:
channel = 6
quality = "39/70"
signal = -71
encryption = true
essid = "testssid"
wpa = true

I am not particularly good with regular expressions but here's my attempt at extracting these fields:
    m = re.search('Channel (.+)\)', n)
    if m:
            print m.group(1)

    m = re.search('Quality\=(.{5})', n)
    if m:
            print m.group(1)

    m = re.search('level\=(.+)', n)
    if m:
            print m.group(1)

    m = re.search('key\:(.+)', n)
    if m:
            print m.group(1)

    m = re.search('ESSID\:\"(.+?)\"', n)
    if m:
            print m.group(1)

This outputs:
6
39/70
-71 dBm
off
testssid

There are two problems: First one is the 'Quality' value, as I have a hardcoded value that might break if the match is shorter than 5 characters and the second one is the 'signal value', which I rather have without the "dBM" portion. I guess in both cases I'd like to match until the next whitespace character, couldn't get it working with \s though.
Also, having a few re.search operations look cluttered and messy, is there a way to combine these or tidy it up generally?
Thanks.

A: re.search('Quality\=(\d+/\d+)', n) #matches a number a slash and a number #/#
re.search('level\=([+-]?\d+)', n) #matches 1 or more numbers so ignore dbm

to clean it up you could do
patterns = {'quality':'Quality\=(\d+/\d+)',
            'level': 'level\=([+-]?\d+)',
            'key':'key\:(.+)',
            'channel':'Channel (.+)\)'}
body_of_text = open("somefile.txt").read()
results = dict([(key,re.search(regex,body_of_text).group(1)) for  key,regex in patterns.items()])
print results


text:
Q: Add next/ previous page buttons JavaScript How could I add the next/ previous page buttons to an Array in JavaScript?
I have this Array:
let products = {
    data: [
      {
        productName: "Product1",
      },
      {
        productName: "Product2",
      },
      {
        productName: "Product3",
      },
      {
        productName: "Product4",
      },
      {
        productName: "Product5",
      },
      {
        multiple other products
      },
],
};

After 5 products, a new page should begin. I have done this using the following JavaScript code:
const nav = document.getElementById('nav');
const content = document.getElementById('content');

let pageIndex = 0;
let itemsPerPage = 3;

loadItems();
function loadItems() {
  content.innerHTML = "";
  for (let i = pageIndex * itemsPerPage; i < (pageIndex * itemsPerPage) + itemsPerPage; i++) {
    if (!items[i]) break;
    const item = document.createElement('div');
    item.innerHTML = `

            <button>${items[i].desc}</button>

    `;
    content.append(item);
  }
  loadPageNav();
}

function loadPageNav() {
  nav.innerHTML = "";
  for (let i = 0; i < items.length / itemsPerPage; i++) {
    const button = document.createElement('button');
    button.classList.add('btn');
    button.innerHTML = i + 1;
    button.addEventListener('click', (e) => {
      pageIndex = e.target.innerHTML - 1;
      loadItems();
    });
    if (i === pageIndex) {
      /*button.style.fontSize = "2rem";*/
    }
    nav.append(button);
  }
}

I now also want to include the next and previous buttons. This means that when the user clicks the next button, the next page should be shown. When the user clicks the previous page button, the previous page should be shown.
When the first page is shown, the previous page button should be a different colour. When the last page is shown, the next page button should be a different colour.


text:
Q: show that ln is the reverse function of exp my problem:
For $z \in \Omega:=\mathbb{C} \backslash(-\infty, 0]$ let the main value Arg $z$ of the argument of $z$ be $−\pi < \operatorname{Arg} z < \pi$. (argument $\varphi$ of $z$ ist modulo 2$\pi$  defined as $z=|z| e^{i \varphi}$.) the main branch of the logarithm is given as:
$\operatorname{Ln} z:=\ln |z|+i \cdot \operatorname{Arg} z$
show:
(a)Ln is the reverse function of $\exp :\{z \in \mathbb{C} ;-\pi<\operatorname{Im} z<\pi\} \rightarrow \Omega$.
(b) Ln is holomorph and $\operatorname{Ln}^{\prime}(z)=\frac{1}{z}$ .
My idea: maybe in (a) i have to start with the lnz definition and then try to get to the exp function? how to use the other informations?


text:
Q: Is a way to configure rsync to explain why it think two files are different? I have a script that synchronized the content between two directories. It's reasonably straightforward and boils down to
rsync -vran --delete $source_dir $dest_dir

I moved recently to a new computer and just ran this script and it spits outs that EVERYTHING has changed.
I checked and see that the files still have the same checksum and modification date. However, I see they have different attributes (owner, group, etc).
I removed "a" (archive) option. However, it still thinks that files are different. I wonder is there a way for it to tell me why it believes it's different (to let me figure out which options should I add to ignore that).


text:
Q: Session node js alguien me echa una mano por favor, tengo un minikube con 3 replicas para un StatefulSet de mysql y un servicio de mysql, 3 replicas para un Deployment de mi app de node, la app se conecta a la BD sin problema, pero no me loguea a la app, haber si os hago un resumen.
Cuando inicio session, me sale el mensaje de que he logueado, pero sin embargo la pagina que me muestra sigue siendo el login, con el boton de loguear etc etc.
Esto pasa cuando tengo 3 replicas, pero si construyo el deployment con una replica no tengo ese problema, me logueo sin problemas.
Entonces intento entender es problema de mi APP en NODE o de minikube?
contenedores que uso       APP : lopuma/liburutegia:1.4, y BD : lopuma/db-liburutegia:1.0
    $ k get all -o wide
NAME                               READY   STATUS    RESTARTS   AGE   IP            NODE       NOMINATED NODE   READINESS GATES
pod/db-liburutegia-0               1/1     Running   0          13h   172.17.0.3    minikube   <none>           <none>
pod/db-liburutegia-1               1/1     Running   0          25m   172.17.0.9    minikube   <none>           <none>
pod/db-liburutegia-2               1/1     Running   0          25m   172.17.0.10   minikube   <none>           <none>
pod/liburutegia-7cccdd78dc-phm88   1/1     Running   0          23m   172.17.0.11   minikube   <none>           <none>

NAME                      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE   SELECTOR
service/db-liburutegia    ClusterIP   10.110.60.178   <none>        3306/TCP         13h   app=db-liburutegia
service/kubernetes        ClusterIP   10.96.0.1       <none>        443/TCP          13h   <none>
service/svc-liburutegia   NodePort    10.107.100.80   <none>        3000:30000/TCP   13h   role=liburutegia

NAME                          READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS    IMAGES                   SELECTOR
deployment.apps/liburutegia   1/1     1            1           13h   application   lopuma/liburutegia:1.4   app=liburutegia,role=liburutegia

NAME                                     DESIRED   CURRENT   READY   AGE     CONTAINERS    IMAGES                   SELECTOR
replicaset.apps/liburutegia-7cccdd78dc   1         1         1       23m     application   lopuma/liburutegia:1.4   app=liburutegia,pod-template-hash=7cccdd78dc,role=liburutegia
replicaset.apps/liburutegia-7ff7c49f8d   0         0         0       4h28m   application   lopuma/liburutegia:1.4   app=liburutegia,pod-template-hash=7ff7c49f8d,role=liburutegia

NAME                              READY   AGE   CONTAINERS       IMAGES
statefulset.apps/db-liburutegia   3/3     13h   db-liburutegia   lopuma/db-liburutegia:1.0

MANIFIESTO DE LA BD
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db-liburutegia
spec:
  replicas: 1
  serviceName: "db-liburutegia"
  selector:
    matchLabels:
      app: db-liburutegia
  template:
    metadata:
      labels:
        app: db-liburutegia
    spec:
      nodeName: minikube
      containers:
      - name: db-liburutegia
        image: lopuma/db-liburutegia:1.0
        ports:
        - name: tpc
          protocol: TCP
          containerPort: 3306
        env:
          - name: MYSQL_DATABASE
            value: "sanmiguel"
          - name: MYSQL_PASSWORD
            value: "*******"
          - name: MYSQL_ROOT_PASSWORD
            value: "*******"
        volumeMounts:
          - name: mysql-store
            mountPath: /var/lib/mysql
  volumeClaimTemplates:
    - metadata:
        name: mysql-store
      spec:
        storageClassName: standard
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 5Gi

SERVICIO MYSQL
apiVersion: v1
kind: Service
metadata:
  name: db-liburutegia
spec:
  ports:
  - port: 3306
  #clusterIP: None
  selector:
    app: db-liburutegia

MANIFIESTO DE APP
apiVersion: apps/v1
kind: Deployment
metadata:
  #creationTimestamp: null
  labels:
    app: liburutegia
  name: liburutegia
spec:
  #progressDeadlineSeconds: 600
  #revisionHistoryLimit: 10
  replicas: 1
  selector:
    matchLabels:
      role: liburutegia
      app: liburutegia
  template:
    metadata:
      labels:
        role: liburutegia
        app: liburutegia
    spec:
      nodeName: minikube
      containers:
      - name: application
        image: lopuma/liburutegia:1.4
        ports:
        - containerPort: 3000
          protocol: TCP
        env:
          - name: NODE_ENV
            value: "production"
          - name: NODE_PORT
            value: '3000'
          - name: MYSQL_HOST
            value: "db-liburutegia" #AQUI VA EL SERVICIO DE MYSQL
          - name: MYSQL_USER
            value: "root"
          - name: MYSQL_PASSWORD
            value: "*****"
          - name: MYSQL_ROOT_PASSWORD
            value: "******"
          - name: MYSQL_DATABASE
            value: "sanmiguel"

A: Cada réplica guarda tu sesión. Debes de habilitar la affinidad para que el service te mande al mismo pod en cada petición.
kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
  sessionAffinity: ClientIP


text:
Q: Let $E = \{(x,y) \in \mathbb{R}^2 \mid y=x^2 \}$. Show that $(E,d_E)$ is a complete metric space.
Let $E = \{(x,y) \in \mathbb{R}^2 \mid y=x^2 \}$. Show that $(E,d_E)$ is a complete metric space. Here $d_E$ is just the restriction of $d_2$ to $E$.

I'm trying to show this using the preimage definition. I have that $$E=\{(x,y)\mid f(x,y)=0\}$$ where $f(x,y)=y-x^2$. Note that $f$ is continous so if $E$ is the preimage of a closed set then $E$ is closed and since $\mathbb{R}^2$ is complete and $E \subset \mathbb{R}^n$ this would imply that $E$ is also complete. I'm not sure I entirely understand the concept of preimage. It's quite clear that it's just the set of elements that map to the image of $f$, but how do I find it? I'm tempted so say that $$f^{-1}(\{0\}) = E$$ but this would mean that only $0$ gets mapped to $0$ which isn't true since if $x=y=1$ then $f(x,y)=0$ so the preimage would be $f^{-1}(\{0,1\})$?

A: We define $F(x,y)=x^2-y$. So $F^{-1}(\{0\})=\{(x,y):x^2=y\}=E$, and since $F$ is continuous as you mentioned, and ${0}$ is closed in $\Bbb{R}$ we get that $E$ is closed in $\Bbb{R^2}$ (as the preimage of a closed set under a continuous function). So $E\subseteq\Bbb{R^2}$ is a closed subset in a complete metric space and therefore $(E,d_E)$ is complete.

A: About your concern regarding the preimage notation:
$$E = f^{-1}(\{0\})$$
is really just another way of writing the definition of $E$:
$$(x,y) \in f^{-1}(\{0\}) \iff f(x,y)\in \{0\} \iff f(x,y) = 0.$$

A: Given any function $g:X\to Y$ and $A\subseteq Y$ we have that
$$g^{-1}(A)=\{x\in X\ |\ g(x)\in A\}$$
This is simply the definition.
And so in your case $f^{-1}(\{0\})=E$ pretty much by the definition.

but this would mean that only 0 gets mapped to 0

That doesn't even make sense, since $0\not\in\mathbb{R}^2$ and $f^{-1}(\{0\})\subseteq\mathbb{R}^2$. Note that $(x,y)\in f^{-1}(\{0\})$ means that $f(x,y)=0$. Its equivalent.

if $x=y=1$ then $f(x,y)=0$

Yes, and thus for $x=y=1$ we have that $(x,y)=(1,1)$ is an element of $f^{-1}(\{0\})$. And at the same time an element of $E$.

A: That's true that $f$ is continuous, and $E = f^{-1}(0)$, and since point zero is closed in $\mathbb R$ then by continuity of $f$ set $E$ is closed.You misunderstand the symbol $f^{-1}$, it's not and inverse map, we define the preimage of set $X \subset \mathbb R$ the same way$$f^{-1}(X) = \{(x, y) \in \mathbb R | f(x,y) \in X\}$$


text:
Q: I can't seem to be aligning these images properly This is really some basic html problem, I want to create a small website but I wanted to have my header in the middle of 2 images, my problem basically goes that I cannot get both images to align properly.
The result I want is in blue letters and the result I have has black letters, I'm sure this was kinda unneeded but I decided to include it anyway.
I'm sure, considering I'm a newbie at html/css that I'm doing something wrong over here but basically this is what I have:
HTML FILE:
    <!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Conversor de Coordenadas</title>

        <link rel="stylesheet" href="conversor.css">

 Conversor de Coordenadas

<input type="button">

And my CSS FILE:
#globe1 {
   float: left;
    margin: 0px 0px 15px 20px;
    height: 100px;
    width: 100px;
}

#globe2 {
   float: right;
    margin: 0px 0px 15px 20px;
    height: 100px;
    width: 100px;
   margin: 0px 0px 15px 20px;
}

.box {

    width:  1000px;
}

Before anything, I tried to do my research but most of the stuff I found wouldn't fix my problem, I've been using w3schools and I've searched a couple of questions here to learn what I know but I seem to have hit a stump cuz I just can't seem to fix this...
Thanks in advance.

A: Set your h1 and images to display: inline-block;

From CSS display: inline vs inline-block

A: If you add this CSS rule they will line up
.box h1 {
  float: left;
  width:  760px;
  text-align: center
}

Sample

#globe1 {
  float: left;
  margin: 0px 0px 15px 20px;
  height: 100px;
  width: 100px;
}
#globe2 {
  float: right;
  margin: 0px 0px 15px 20px;
  height: 100px;
  width: 100px;
  margin: 0px 0px 15px 20px;
}
.box {
  width:  1000px;
}
.box h1 {
  float: left;
  width:  760px;
  text-align: center
}

 Conversor de Coordenadas

  <input type="button">

Or you can do this, where you change the markup some and add a CSS rule
HTML

 Conversor de Coordenadas

CSS
.box h1 {
  margin: 0 120px;
  text-align: center
}

Sample 2

#globe1 {
  float: left;
  margin: 0px 0px 15px 20px;
  height: 100px;
  width: 100px;
}
#globe2 {
  float: right;
  margin: 0px 0px 15px 20px;
  height: 100px;
  width: 100px;
  margin: 0px 0px 15px 20px;
}
.box {
  width:  1000px;
}
.box h1 {
  margin: 0 120px;
  text-align: center
}

 Conversor de Coordenadas

  <input type="button">

A: You can try to put the two image ont afther the other :

 Conversor de Coordenadas

I'm not sure that will work but you can try.

A: I would try wrapping all elements in their own div tag.

title

and the CSS
#globe1 {
   float: left;
    margin: 0px 0px 15px 20px;
    height: 100px;
    width: 100px;
    margin: 0px 0px 15px 20px;
}

#globe2 {
   float: left;
    margin: 0px 0px 15px 20px;
    height: 100px;
    width: 100px;
   margin: 0px 0px 15px 20px;
}

.title {
  float: left;
  text-align: center;
  width: 300px;
}

.box {

}

Demo: https://jsfiddle.net/4thkxhwm/

A: You can achieve this using the CSS3 FlexBox module, see code and fiddle below:
HTML:

 Conversor de Coordenadas

CSS
.container{
  display:flex;
  justify-content:space-between;
  border:solid;
}

h1{
  border:solid;
  padding-top:10px;
}

img{
  width:100px;
  height:100px;
}

https://jsfiddle.net/smlrolland/8x4nyh1o/


text:
Q: Re-establish route to localhost on Windows Vista
route -f

How do you re-establish a route to localhost after this? I can re-establish connections to the Internet via wireless using
route add {wirelessgateway} {wirelessip} if {wirelessif}
route add 0.0.0.0 {wirelessgateway}

but a lot of things fail because there is no route to 127.0.0.1. Also, Internet access via the browser is very slow, while Internet access via programs like telnet does not work.
ping 127.0.0.1

does not work.

A: Why did you run route -f? The quickest way to restore things is to restart the PC - this will restore all dynamic routing info.


text:
Q: How to add controls and buttons to map? This is probably a really basic question, but I can't figure it out. I'm building a map using D3. My code creates and svg, appends a g element to it and then draws the map within it. What I want is to render a set of buttons and controls that are positioned inside the map viewer. They would be zoom buttons, a dropdown to display different sets of data and a timeline slider.
For example, with the dropdown selector I want placed I did this:
I tried using d3 as in:
svg.append("select")
  .attr("class", "field_dropdown")
  .data(['housing_unit', 'tenure', 'median_contract_rent', 'median_value', 'median_income'])
  .enter()
  .append("option")
  .attr("value", function(d) {
       return d
   });

but this rendered the select item and option items separate from each other, and not even visible within the map container.
As mentioned, not only do I wanna add a dropdown, but also buttons for zoom and a slider, among other items. How do I render and position them in the map container?
Thanks

A: This has been asked several times (surely a duplicate): you cannot append HTML elements ("div", "p", "select", "h1" etc) to an SVG. It will simply not work.
The best solution, in your case, is creating the drop down menu and the other controls outside the SVG, in the HTML.
But, if you really want to create this drop down inside the SVG (which I don't advise), you can use foreignObject (which will not work on IE):
var foreign = svg.append("foreignObject")
    .attr("width", 100)
    .attr("height", 100)
    .append("xhtml:body");

var select = foreign.append('select')
    .attr("class", "field_dropdown")
    //the rest of your code


text:
Q: Laravel Eloquent query recursive relationship model with pagination I am building a store, where I have to display to the user all products in a given category and all other products that are contained in the subsequent subcategories of the currently accessed one. The categories have the N+1 problem since there can be infinite subcategories. I want to be able to filter trough these products and also to be able to paginate them.
This is my categories model:
   class CatalogCategory extends Model
   {

    public function parent()
    {
        return $this->belongsTo('App/CatalogCategory','parent_id');
    }

    public function children()
    {
        return $this->hasMany($this,'parent_id')
            ->orderBy('order_place','ASC')
            ->with('children');
    }

    /*
    *   Return products, that belong just to the parent category.
    */

    public function products()
    {
        return $this->hasMany('App\CatalogProduct','parent_id')
            ->where('is_active', 1)
            ->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
            ->orderBy('created_at','DESC');
    }

    /*
    *   Return all products contained in the parent category and its children categories.
    */

    public function all_products()
    {
        $products = $this->products;

        foreach ($this->children as $child) {
            $products = $products->merge($child->all_products());
        }

        return $products;
    }

}

The all_products() method returns all of the products, that I want, but since it's a collection i'm unable to paginate or filter through it. My question is if there is a better way to retrieve the products and how to retrieve them so, that i can query them for filtering and paginate them?

A: You could use nested set technique to store categories.
Nested set technique allows to retrieve all descendants or ancestors for a certain node in hierarchical structures in one query.
You could try this package: https://github.com/lazychaser/laravel-nestedset. Imho it's the best implentation of nested set in laravel.
Installation and configuring will cost you 10 min.
After that you could retrieve your products something like this:
public function products($slug)
{
    //first query: retrieving current category
    $category = CatalogCategory
        ::where('slug', $slug)
        ->first();

    //second query: retrieving all category descendants and self ids.
    $categoryIds = $category
        ->descendants
        ->pluck('id')
        ->push($category->id);

    //third query: retrieving all products.
    $products = CatalogProduct
        ::whereIn('parent_id', $categoryIds)
        ->where('is_active', 1)
        ->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
        ->orderBy('created_at', 'desc');
        ->paginate(50);

    return view('path_to_view', compact('products', 'category'));
}


text:
Q: Is this a bad Moq setup or a deficiency in Moq? I am attempting to test the following code:
public async Task<Activity> Get(long ID, Recruiter User, bool IsArchived = false)
{
    Activity result = await collection.FirstOrDefault(x => x.ID == ID && x.Recruiter.CompanyID == User.CompanyID && (!x.Archived || IsArchived));
    return result;
}

With the following test:
[TestMethod]
public async Task GetDoesThings()
{
    long ID = 1;
    bool IsArchived = false;
    Recruiter User = new Recruiter()
    {
        CompanyID = 1
    };

    ActivitiesMock.Setup(x => x.FirstOrDefault(y => y.ID == ID && y.Recruiter.CompanyID == User.CompanyID && (!y.Archived || IsArchived))).ReturnsAsync(new Activity());

    Activity result = await repo.Get(ID, User);

    ActivitiesMock.Verify(x => x.FirstOrDefault(y => y.ID == ID && y.Recruiter.CompanyID == User.CompanyID && (!y.Archived || IsArchived)));
}

(I know there are different ways of writing it, this is the most recent iteration we've tried.)
The ActivitiesMock relates to the collection found in Get(long ID, Recruiter User, bool IsArchived = false). We recently wrote wrappers in order to try and test our Entity calls more efficiently, but we're running into this error when trying to verify the calls are made correctly:

Test method ExampleProject.Tests.Backend.Repositories.ActivityRepositoryTests.GetDoesThings threw exception:
  Moq.MockException:
  Expected invocation on the mock at least once, but was never performed: x => x.FirstOrDefault(y => (y.ID == .ID && y.Recruiter.CompanyID == .User.CompanyID) && (!(y.Archived) || .IsArchived))
Configured setups:
  x => x.FirstOrDefault(y => (y.ID == .ID && y.Recruiter.CompanyID == .User.CompanyID) && (!(y.Archived) || .IsArchived)), Times.Never
Performed invocations:
  IAppCollection`2.FirstOrDefault(x => (((x.ID == value(ExampleProject.Backend.Repositories.ActivityRepository+<>c__DisplayClass2_0).ID) AndAlso (x.Recruiter.CompanyID == value(ExampleProject.Backend.Repositories.ActivityRepository+<>c__DisplayClass2_0).User.CompanyID)) AndAlso (Not(x.Archived) OrElse value(ExampleProject.Backend.Repositories.ActivityRepository+<>c__DisplayClass2_0).IsArchived)))

In this instance the wrapper (collection) is a mock of the interface. The goal is to ensure that the repository is calling the correct expression on the wrapper, so that we know the predicate that's being passed to the Entity DbSet is correct without having to worry about all the messy async abstractions.
The Mock Setup() with the full predicate doesn't appear to be found when the test is ran, and when I change the Setup() to It.IsAny<Expression<Func<Activity, bool>>>() it runs the mock and provides the return, but the Verify call doesn't work. So, running:
ActivitiesMock.Setup(x => x.FirstOrDefault(It.IsAny<Expression<Func<Activity, bool>>>())).ReturnsAsync(new Activity());

Activity result = await repo.Get(ID, User);

Assert.IsNotNull(result);
ActivitiesMock.Verify(x => x.FirstOrDefault(y => y.ID == ID && y.Recruiter.CompanyID == User.CompanyID && (!y.Archived || IsArchived)));

Passes the assert but fails the Verify, whereas running:
ActivitiesMock
    .Setup(x => x.FirstOrDefault(y => y.ID == ID && y.Recruiter.CompanyID == User.CompanyID && (!y.Archived || IsArchived)))
    .ReturnsAsync(new Activity())
    .Verifiable();

Activity result = await repo.Get(ID, User);

Assert.IsNotNull(result);
ActivitiesMock.Verify();

Fails on the assert.
It looks like it's failing because it's expecting the same object types. Am I trying to do something that Moq can't handle, or am I missing something that I need to do in order to get the verification to be correct?
By request, the concrete implementation of the LINQ-to-Entity wrapper (collection) is:
public Task<T> FirstOrDefault(Expression<Func<T, bool>> Predicate)
{
    return DbSet.FirstOrDefaultAsync(Predicate);
}

Though the wrapper itself isn't being used, but an interface for it is being mocked, and it's that mock that we're testing.

A: The answer is neither. Since the anonymous functions have to create class instances to store the data being provided, they create DisplayClass instances to hold the data. Since those instances are being created in different namespaces (among other things) they don't pass when Moq calls .Equals against them.
We solved this problem by writing our tests as such:
ActivitiesMock
    .Setup(x => x.Where(It.IsAny<Expression<Func<Activity, bool>>>()))
    .Returns((Expression<Func<Activity, bool>> x) =>
    {
        actualPredicate = x;
        return queryMock.Object;
    });

Then creating valid and invalid activities to provide to the predicate to ensure it returns true or false correctly:
Assert.IsTrue(actualPredicate.Compile().Invoke(validActivity));

Granted for now it's a bit hacky, but at first glance it doesn't seem too much like a dumpster fire solution, and it's a way for us to ensure the calls being provided do what we expect them to, which is what we want.
Update (Sep 7th, 2016): So far this has been working well for us. We've ran into an issue where LINQ-to-Entity statements don't run as expected because the LINQ is case-sensitive and the SQL generated isn't, but since that isn't a deal breaker for us we're just fine.


text:
Q: open a new tab only if it is not already open Is it possible to open a new tab only if it is not already open.
index.php
$('.title').on('click', function(){
    if tab `images.php` is already open -> go to that tab
    else {window.open('images.php', '_blank')  // open a new tab
});

So I don't want to open a new tab if it already exists.
In both cases, current tab (index.php) stays as open, but it's not active.

A: Just give the window a name and also make sure that doesn't start with an underscore, otherwise it will behave like html's _target attribute:
$('.title').on('click', function(){
  window.open('images.php', 'myWindow')
  // it will open the same window on following clicks
});

If you don't want to reload the page:
var myWindow = null;
$('.title').on('click', function(){
  if(myWindow == null || myWindow.closed)
    myWindow = window.open('images.php', 'myWindow')
  else
    myWindow.focus()
});

You may read more about window.open in the docs.

A: Copied from MDN window.open() docs "Best Practices" section
var windowObjectReference = null; // global variable

function openFFPromotionPopup() {
  if(windowObjectReference == null || windowObjectReference.closed)
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */

  {
    windowObjectReference = window.open("http://www.spreadfirefox.com/",
   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
    /* then create it. The new window will be created and
       will be brought on top of any other window. */
  }
  else
  {
    windowObjectReference.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
  };
}


text:
Q: SSIS export data to excel empty I have weird problem: I have data in DB, when I click on Preview... in Ole DB Sources I see data but when I link them to Excel - the document is empty only firs row with name is there. When I debug project I have red cross in excel file and information:
Data viewer at path 'OLE DB Source Output' of task 'Data Flow Task' [DataflowID: {6007EF3C-0A2C-45C9-995D-FA9DF2F5CE9C}; IDString: Paths[OLE DB Source.OLE DB Source Output]; PackageRPath: test2\Package.dtsx]
What is going on???

A: Reason for this run-time error is excel do not have 64-bit driver which is selected by default in SSIS running on 64bit OS. So solution is also hidden behind the reason, change the driver from default and you are good to go.
Navigate to Project-> [PROJECT_NAME] Properties.
Navigate to "Debugging" option from left panel and from Right panel change Run64BitRuntime value to false.


text:
Q: How do I join two tables and return the values from the first that aren't in the second table? I have two tables, the first containing the id and employee_name, and the second containing the employee_id (same as id) and some other columns. How do I join the first table with the second so that I can output all the employee ID's (and the rest of the columns) in the first table that don't appear in the second? The query I've gotten to is this:
select employee_id
from data2 left join data1 on data2.employee_id = data1.id
where employee_id is NULL

This outputs the correct number of rows, but there are no values in them. Any help is greatly appreciated!

A: Your tables are flipped in your SQL. Based on your narrative, the SQL should be:
select data1.*
from data1
left join data2 on data2.employee_id = data1.id
where data2.employee_id is NULL

A: You need not use join, you can simply use 'not in' clause
select id
from table1
where id not in (select employee_id from table2)

Let me know, if it works.

A: If I understand your question correctly, you want to get the records from data1 whose values of employee_id do not exist in the column id in data2.
The way the current query is structured, you are asking for employee_id ... where employee_id is NULL so that will only return null records. Instead, make a query of data1 like this:
select * from data1 where employee_id not in
(select id from data2)
This uses the subquery to find a list of id values in data2 and then only returns records from data1 whose employee_id does not exist in that list.


text:
Q: Use a custom VBA function within a VBA sub I am trying to create a function that will take the value of a cell formatted something like 5.23*10^-3 and be able to use it in a calculation.
Sub Multiplication_Stuff
Dim a As Double

a = Range('ActiveSheet!$B$2').Value   *****
c = multiplyme(a)

Range("Sheet1!B7) = C
End Sub

Public Function multiplyme(a As Double) As Double
multiplyme = a * 15
End Function

I received the following error in the code:

run-time error'1004' Method 'Range'Of object'_Global' failed

I have also had it formatted the way the range for c is formatted and recieved the same error. i would prefer it to not pull from active sheet but sheet 1 instead.

A: In VBA, a Sheet and a Cell are two DIFFERENT objects:
Sub Multiplication_Stuff
    Dim a As Double, c As Double

    a = ActiveSheet.Range("B2").Value
    c = multiplyme(a)

    Sheets("Sheet1").Range("B7").Value = c
End Sub

Public Function multiplyme(a As Double) As Double
    multiplyme = a * 15
End Function


text:
Q: Converting native javascript code to aura component javascript I have the following JS code  and I'm trying to convert to aura component JS Controller, I'm getting error on the yield how would you make equivalent aura component code
    function* createChunkGenerator(
         itemList = [], chunkSize = 1, chunkCount = 0
    ) {
        chunkSize = Math.max(chunkSize, 1);

     while (itemList.length >= 1) {
       ++chunkCount;
       yield {
        chunkCount,
        itemList: itemList.splice(0, chunkSize),
      };
    }
}

const chunkGenerator = createChunkGenerator(data, 5);

Aura component javascript:
 createChunkGenerator: function( ) {

    //....
 },

A: Aura doesn't support ES6 function generators, it only supports ES5 and ES6 Promises. Either import the function as a third-party library with ltng:require, or use a Lightning Web Component (LWC), which supports everything your browser supports (with limitations based on Locker Service or Lightning Web Security, whichever you're using). You can also write an LWC, and then call that LWC from Aura:
utils.js
import { LightningElement, api } from 'lwc';
export default class Utils extends LightningElement {
  @api *createChunkGenerator(
    itemList = [], chunkSize = 1, chunkCount = 0
  ) {
    chunkSize = Math.max(chunkSize, 1);
    while (itemList.length >= 1) {
      ++chunkCount;
      yield {
        chunkCount,
        itemList: itemList.splice(0, chunkSize),
      };
    }
  }
}

utils.html
<template></template>

Aura CMP
<aura:component>
  <c:utils aura:id="utils" />
</aura:component>

Aura Controller
myFunction: function(component, event, helper) {
  let generator = component.find("utils").createChunkGenerator(data, 5);
  // Rest of logic here
}


text:
Q: Non-persistent annoying message Annoying message from time to time on my .Net application start appears just after splash screen disappears:
System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

I don't know how to fix this type of exceptions and why it appears?
Any help will be appreciated.!

A: This problem usually happens if you add code to the constructor of a form/control, since at that time it isn't linked to a windows control handle. If you have added extra code here, try moving it to OnLoaded or similar.

A: It seems you are trying to invoke a method belonging to a class instance as not previously created, make sure that the invocations of methods or functions of classes or objects after a re made explicit initialization.
Call myClass_Method  'or myObject_method
myClass as <objecttype> = New <objecttype>

Make sure it is as follows:
myClass as <objecttype> = New <objecttype>
Call myClass_Method 'or myObject_method

That I guess since you do not give more details or code samples


text:
Q: How can I create DIV "rows" while having a DIV float beside them? I'm trying to make one large DIV that floats to the left of my content and then use additional DIVs that are rows beside the content.
How would I do that and be sure that each "row" div is actually a row, but still respect the larger DIV on the left (the first few should not pop down below it).
I duplicated the problem on jsFiddle here:
http://jsfiddle.net/Dracorat/Xf9Qv/1/
CSS:
.DropCapImage {
    border: 2px solid purple;
    color: #EEE;
    display: block;
    width: 200px;
    height: 300px;
    float: left;
    margin: 0 10px 10px 0;
}

.DialogAction {
    padding: 10px;
    font-style: italic;
    float: left;
    clear: right;
}

.DialogLine {
    float: left;
    clear: right
}

.DialogWho {
    font-weight: bold;
    float: left;
    width: 100px;
}

.DialogWhat {
    float: left;
    white-space: pre-wrap;
    font-family: 'consolas', monospace;
}

HTML:

Pretty Image Here

KING CLAUDIUS

Short Text

Exeunt all but HAMLET

Something Else

Another Else

HAMLET

O, that this too too solid flesh would melt
Thaw and resolve itself into a dew!
Or that the Everlasting had not fix'd
His canon 'gainst self-slaughter! O God! God!
How weary, stale, flat and unprofitable,
Seem to me all the uses of this world!
Fie on't! ah fie! 'tis an unweeded garden,
That grows to seed; things rank and gross in nature
Possess it merely. That it should come to this!
But two months dead: nay, not so much, not two:
So excellent a king; that was, to this,
Hyperion to a satyr; so loving to my mother
That he might not beteem the winds of heaven
Visit her face too roughly. Heaven and earth!
Must I remember? why, she would hang on him,
        ... etc

Speaker Below

This should be below the purple area

As you can see, the floating is totally bogus with small divs.

A: Do not float the .DialogLine and .DialogAction elements
Just give them the correct margin-left (equal to the width of the left column)
And do not forget to give overflow:hidden to them as well so the will expand to fit their contents..
.DialogAction {
    padding: 50px;
    font-style: italic;
    margin-left:210px;
}
.DialogLine {
    margin-left:210px;
    overflow:hidden;
}

Demo at http://jsfiddle.net/gaby/Xf9Qv/4/


text:
Q: JQuery Mobile .selectmenu not working I am developing a website using Jquery Mobile and Jquery, and i update the value of dropdown dynamically with JSON, but the value in dropdown doesn't show the update value. I am trying to using selectmenu("refresh") and trigger("change") but i doesn't work.
Html code:

                            @Html.DropDownList("credit_card_expiry_month", CCMonthList, "Month", new { id = "credit_card_expiry_month", @class = "font12 required", autocomplete = "off" })

                            @Html.DropDownList("credit_card_expiry_year", CCYearList, "Year", new { id = "credit_card_expiry_year", @class = "font12 required", autocomplete = "off" })

                        @Html.DropDownList("credit_card_issuing_bank_country", (IEnumerable<SelectListItem>)ViewBag.CountriesListItem, "Issuing bank country", new { id = "credit_card_issuing_bank_country", @class = "required", autocomplete = "off" })

JSON function call
function LoadCardInfo()
 {
     $.getJSON("GetCardInfo", function (result) {
         if (result != null) {
             $("#credit_card_number").val(result.credit_card_no);
             $("#credit_card_holder_name").val(result.card_holder_name);
             $("#credit_card_expiry_month").val(result.expiry_month);
             $("#credit_card_expiry_year").val(result.expiry_year);
             $("#credit_card_issuing_bank_country").val(result.issuing_bank_country_code_A2);
             $("#credit_card_issuing_bank_name").val(result.issuing_bank_name);
             LoadCardIcon(result.credit_card_no);
         } else {

         }
     });

 }

$('document').on('pageshow', function () {
    $("#credit_card_expiry_month").trigger("change");
    $("#credit_card_expiry_month").selectmenu('refresh', true);
});

A: I think you are missing the # to match an id selector, try:
$('document').on('pageshow', function () {
    $("#credit_card_expiry_month").trigger("change");
    $("#credit_card_expiry_month").selectmenu('refresh', true);
});


text:
Q: Get run time type of stack frames I was wondering if it were possible to obtain the run time type of method callers in the stack trace.
Consider the following example:
class Parent
{
    public void Foo()
    {
        var stack = new StackTrace();

        foreach (var frame in stack.GetFrames())
        {
            var methodInfo = frame.GetMethod();
            Console.WriteLine("{0} (ReflectedType: {1})", methodInfo.ToString(), methodInfo.DeclaringType);
        }
    }
}

class Child : Parent
{
}

If I create an instance of Child and call Foo
var child = new Child();
child.Foo();

Foo will print:
Void Foo() (ReflectedType: Parent)
Is there any way to get the actual run time types (Child in this case) of method callers in the stack trace?

A: No. The reason is described by Raymond Chen here.
The relevant quote is:

An object in a block of code can become eligible for collection during execution of a function it called.

It's not intuitive, read the part about JIT and GC working together.
Getting the actual Type requires the instance, but the optimization effort is geared toward making that Garbage, so you can't rely on it still being there.

A: You are calling Parent.Foo(), that's why you are getting Parent type.
One way would be create a method in Child:
class Parent
{
}

class Child : Parent
{
    public void Foo()
    {
        var stack = new StackTrace();
        foreach (var frame in stack.GetFrames())
        {
            var methodInfo = frame.GetMethod();
            Console.WriteLine("{0} (ReflectedType: {1})", methodInfo.ToString(), methodInfo.DeclaringType);
        }
    }
}

Proof.
But what I can think is the usage. Where do you plan to get that info about stack, types, methods? More likely in some logger. And then you don't really need to know is it Parent.Foo() or Child.Foo(), because you (as programmer) know for sure where Foo() is.
Other thing is what it may be enough (for logger) to only know caller, then it's as simple as
public static void Log(string message, Exception exception = null)
{
    var method = new StackFrame(1).GetMethod();
    // get caller name, so that you don't need to specify it, when calling Log()
    var caller = method.DeclaringType.Name + "." + method.Name;
    ...
}


text:
Q: Calculation should wait for Dispatcher I have an algorithmic calculation using depth-first search (sudoku solver) and I want to have a way to control the update rate of the ui to display all/most of the numbers that are calced during the calculation.
I know this slows down the calc time, but the visual feedback is more important to me.
Currently the ui elements, each representing a field in a sudoku game, are bound via binding to the data sources with binding mode "oneway".
I came across Dispatcher.Invoke and called that method with a low priority after a datasource send the value changed event, and now one can see how a part of the calculation progress is displayed at least, but it s still way too fast.
So my question is, how do I manage it, that my calculation waits for the Dispatcher thread to display a changed value before calculating the next (changed) value?

A: It looks like you want to use either a storyboard animation or a timer.
Have a look at DispatcherTimer it sounds like what you really are after. Use a queue/list and then gradually add solved items at your desired rate to your presentation in the view. In the example below I assume you have a clas called SudokuItem. The timer_Tick method will be invoke every seccond, which is controlled by the Interval property. I just grab and remove the first item in the queue. You may set the Dispatcher property on the DispatcherTimer. There is a fictional SudokuService there, which simulates generation of items.
Simple Example - Can bee refactored. No async-await here etc.
protected ISudokuService SudokuService; // Fictional TDD Service for handling generation of Sudoku boards
private List<SudokuItem> queue = new List<SudokuItem>();
private DispatcherTimer timer;
private ObservableCollection<SudokuItem> sudokuItems = new ObservableCollection<SudokuItem>();

public ObservableCollection<SudokuItem> SudokuItems
{
    get { return sudokuItems; }
    set
    {
        if (Equals(value, sudokuItems)) return;
        sudokuItems = value;
        OnPropertyChanged();
    }
}

public void StartGeneration()
{
    new Thread(DoYourSudokuMagic).Start(); // Start heavy lifting in a separate thread
    timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 0, 1), IsEnabled = true};
    timer.Tick += timer_Tick;
    timer.Start();
}

private void DoYourSudokuMagic()
{
    // fetch/generate new SudokuItems somehow... replace this with your code
    SudokoService.StartGeneratingBoard();
    while( SudokuService.HasMoreItems ){
        var items = SudokoService.GetNextItems();
        if (items != null && items.Any())
        {
            lock (queue)
            {
                queue.AddRange(items);
            }
        }
    }
}

// Always invoked on the Dispatcher thread
void timer_Tick(object sender, EventArgs e)
{
    // note that you must call timer.Stop(); when you are done
    lock (queue)
    {
        if (queue.Any())
        {
            SudokuItems.Add(queue.FirstOrDefault());
            queue.RemoveAt(0);
        }
    }
}

Another timer you can use, which really is for forms, is the BackgroundWorker class, it could be practical in your case.
Dispatcher.Invoke blocks until it gets access. Dispatcher.BeginInvoke continues your code, and let you update your Properties or DependencyProperties when it gets access. You  should also check for access first, I typically put this in a baseclass.
// Note that Dispatcher is an interface in this baseclass for TDD, you have to set it or replace it with your dispatcher.
protected void BeginInvoke(Action action, DispatcherPriority priority)
{
    if (!Dispatcher.CheckAccess())
        Dispatcher.BeginInvoke(action, priority); // doesn't block
    else
        action(); // hey we are on the gui thread already :)
}

protected void Invoke(Action action, DispatcherPriority priority)
{
    if (!Dispatcher.CheckAccess())
        Dispatcher.Invoke(action, priority); // blocks
    else
        action(); // hey we are on the gui thread already :)
}

I hope this is of some help, and that I haven't missunderstood your question.
Cheers

A:
So my question is, how do I manage it, that my calculation waits for the Dispatcher thread to display a changed value before calculating the next (changed) value?

That's not really what you want to do. You really just want to throttle the updates.
The standard modern way of doing CPU-bound operations with UI updates is to use Task.Run and IProgress<T>. So, I'll assume that your CPU-bound code looks something like this:
struct SolveProgress { ... }
void Solve(IProgress<SolveProgress> progress)
{
  while (...)
  {
    ...
    if (progress != null)
      progress.Report(new SolveProgress(...));
  }
}
async void Button_Click()
{
  var progress = new Progress<SolveProgress>(value =>
  {
    // Update UI
  });
  await Task.Run(() => Solve(progress));
}

The problem is that the background work is issuing lots of updates. What you want is a consistent UI experience across various computer capabilities, no more than a few times per second. Personally, I really like 100ms updates - it's just enough to convey the feeling "this software is working really hard" while still being "seeable". If you want it more readable, 250ms may be better.
Throttling is a time-based operation, and I like to use Rx for anything time-based. First, replace the Progress<T> implementation (which just executes the delegate for every progress) with an ObserverProgress<T> that converts progress updates into an observable stream. This type is very simple:
public sealed class ObservableProgress<T> : IObservable<T>, IProgress<T>, IDisposable
{
    private readonly Subject<T> _subject = new Subject<T>();

    void IProgress<T>.Report(T value)
    {
        _subject.OnNext(value);
    }

    public void Dispose()
    {
        _subject.Dispose();
    }

    IDisposable IObservable<T>.Subscribe(IObserver<T> observer)
    {
        return _subject.Subscribe(observer);
    }
}

Then the consuming code looks like this (after installing the NuGet packages Rx and Rx-WPF):
using (var progress = new ObservableProgress<SolveProgress>())
using (progress.ObserveOn(this)
    .Subscribe(value =>
    {
        // Update UI
    }))
{
    await Task.Run(() => Solve(progress));
}

ObservableProgress<T> by default will not synchronize to the UI thread like Progress<T> will, so that's why the ObserveOn is necessary. With this in place, it's easy to throttle the progress updates:
using (var progress = new ObservableProgress<SolveProgress>())
using (progress.Sample(TimeSpan.FromMilliseconds(100))
    .ObserveOn(this)
    .Subscribe(value =>
    {
        // Update UI
    }))
{
    await Task.Run(() => Solve(progress));
}

A nice benefit of the Rx approach is that the throttling logic is done on the background thread; it only switches to the UI thread when it has some UI work to do. This means that the time-based throttling is actually done at the source, saving CPU cycles. Since it's time-based (and not, e.g., using a counter), you get a reliable, smooth user experience, whether running on an older machine or a newer one.


text:
Q: Can sphinx link to documents that are located in one path above the .rst document? I'm trying to use the basics of Sphinx to document a small project. But I can't get him to find the files that are in a directory above.
The project structure is as follows:
/Users/machine/workspace/project1
├── BDRespostas.py
├── constantes.py
├── docs
│   ├── conf.py
│   ├── index.rst
│   └── make.bat
├── estatisticas.py
├── migrate_postgre_sqlite.py
├── preProcessamentoTextual.py
└──

And I have tried to configure index.rst in several ways, without success:
.. toctree::
   :maxdepth: 2
   :caption: Contents:

   :ref:'estatisticas.py'
   ../BDRespostas.py
   '/Users/machine/workspace/project1/constantes.py'

I also combined several attempts with adding sys.path.insert () to the project directory. If you already managed to make this reference and can help me, I really appreciate it.

A: As said above, toctree is for including documents (.rst files), not Python sources. Tell us what do you want to achieve.
To don't gloss over it - toctree can include documents only from the current folder or child folders. I.e. you can't
.. toctree::

   ../one.rst
   ../two/three.rst


text:
Q: Find the index of a partial dictionary element in a list I have a list of dictionary as follows:
myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'},
        {'id':6,'key1':'a','key2':'p'}]

To find index of element, I am currently executing following statement:
print myList.index({'id':8,'key1':'c','key2':'d'})

which returns 1
However, I would like to do something like this:
print myList.index({'id':8})

should return 1

A: If you're looking for a one-liner (as opposed to reusable code), and your data size is small, you could do something like:
[elem["id"] for elem in myList].index(8)

which extracts the id from each dict, and then finds the index of the provided id. Depending on what your overall goals and data set look like, this might or might not be what you want...

A: Should be relatively simple to implement. Written for Python 3, in Python 2 you should use .iteritems() (doesn't create a temporary list).
def partial_dict_index(dicts, dict_part):
    for i, current_dict in enumerate(dicts):
        # if this dict has all keys required and the values match
        if all(key in current_dict and current_dict[key] == val
                for key, val in dict_part.items()):
            return i
    raise ValueError("...")

Could use better names though...

A: Edit: Please change your accepted answer to @delnan's corrected answer which is very similar and likely performs better.

A: You could implement your own list. Here is an example that prints the first found result. I added the ValueError to duplicate the existing behavior of .index().
class DictList(list):

    def index(self, obj):
        for i, o in enumerate(self):
            if o['id'] == obj['id']:
                return i
        else:
            raise ValueError('x not in list')

myList = DictList(({'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'},
                   {'id':6,'key1':'a','key2':'p'}))

>>> print myList.index({'id': 8})
1

>>> print myList.index({'id': 10})
ValueError: x not in list


text:
Q: Try to connect to Mosquitto MQTT over WebSockets with Mqtt.js I want to build a web page to send and receive topics. I'm using mosquitto and MQTT.js.

*

*I'm using this as an config file:
protocol websockets
listener 1884

*I run sudo mosquitto -c /etc/mosquitto/mosquitto.conf and get
1647529861: mosquitto version 2.0.14 starting
1647529861: Config loaded from /etc/mosquitto/mosquitto.conf.
1647529861: Opening websockets listen socket on port 1884.
1647529861: mosquitto version 2.0.14 running

*I'm using a simple mqtt.html (full source):
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
const client = mqtt.connect("ws://localhost:1884")
</script>

Problem:

*

*In Chrome it just connects with 101 and does it again and again. When you check the websockets messages, the "server" receives: 00000000: 2002 0005. When I check the log of mosquitto: I get a lot of 1647530429: Client mqttjs_b0e54ea4 closed its connection.
I'm running on:
LSB Version:    n/a
Distributor ID: ManjaroLinux
Description:    Manjaro Linux
Release:    21.2.5
Codename:   Qonos

A: You need to add allow_annonymous true to your config file.
The default for mosquitto 2.x is to not allow connections from unauthenticated clients.
You should also reverse the lines in your config,
The protocol option only applies to the last listener in order down the file.
What you have will apply the websocket protocol to the default listener on port 1883.
allow_anonymous true
listener 1884
protocol websockets


text:
Q: Identification of private key in Pkcs11Interop.PDF library I am trying to setup up an example application with the Pkcs11Interop.PDF extension. I am unfortunately getting a System.ArgumentNullException setting the ckaId. What would work here? I tried different numbers here which all gave me a System.ArgumentOutOfRangeException.
The setup is using the VirtualCryptoki-64-1.0.6.7.exe application to simulate a Smartcard.
The troubling call is:
pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, hashAlgorithm);

The hash algorithm I use is:
HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256;

Update after using the pkcs11-tool:
The content of the virtual card is:
    C:\Program Files\OpenSC Project\OpenSC\tools>pkcs11-tool.exe --module "C:\windows\System32\vcki.dll" --list-slots --list-objects --login --pin 1234
Available slots:
Slot 0 (0xd47db04d): Virtual Smart Card Reader
  token label:   Virtual SC-A0101010101
  token manuf:   Cryptware
  token model:   VirtualSmartCard
  token flags:   rng, login required, PIN initialized, token initialized, other flags=0x200
  serial num  :
Using slot 0 with a present token (0xd47db04d)
Certificate Object, type = X.509 cert
  label:      ibisit
  ID:         4a656e73204b6175666d616e6e
Public Key Object; RSA 1024 bits
  label:      ibisit
  ID:         4a656e73204b6175666d616e6e
  Usage:      encrypt, verify
Private Key Object; RSA
  label:      ibisit
  ID:         4a656e73204b6175666d616e6e
  Usage:      decrypt, sign
warning: PKCS11 function C_GetAttributeValue(ALWAYS_AUTHENTICATE) failed: rv = CKR_ATTRIBUTE_TYPE_INVALID (0x12)

Public Key Object; RSA 1024 bits
  label:      ibisit
  ID:         4a656e73204b6175666d616e6e
  Usage:      encrypt, verify
Private Key Object; RSA
  label:      ibisit
  ID:         4a656e73204b6175666d616e6e
  Usage:      decrypt, sign
warning: PKCS11 function C_GetAttributeValue(ALWAYS_AUTHENTICATE) failed: rv = CKR_ATTRIBUTE_TYPE_INVALID (0x12)

The parameters I use are:
string libraryPath = @"C:\Windows\System32\vcki.dll";
string tokenSerial = null;
string tokenLabel = @"Virtual SC-A0101010101";
string pin = @"1234";
string ckaLabel = @"ibisit";
string ckaId = "4a656e73204b6175666d616e6e";
HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256;

I am unfortunatly getting a Net.Pkcs11Interop.PDF.ObjectNotFoundException setting the ckaId. Changing the pin gives me a different exception so I am definetely accessing the right device here.
Update after switching to SoftHSM:
jariq stated that too many objects with the same id were there problem here. Unfortunately the Virtual Key Explorer would not let me delete any object so I switched to SoftHSM (which I was using at the beginning). I am getting "Certificate with label "ibis-it key" and id "A1B2" was not found". I suppose the problem here is that this virtual card only holds a RSA keypair not a certificate.
The output of the pkcs11-tool is:
C:\Program Files (x86)\OpenSC Project\OpenSC\tools>pkcs11-tool.exe --module "C:\SoftHSM\lib\libsofthsm.dll" --list-slots --list-objects --login --pin smart
Available slots:
Slot 0 (0x0): SoftHSM
  token label:   SoftHSM
  token manuf:   SoftHSM
  token model:   SoftHSM
  token flags:   rng, login required, PIN initialized, token initialized, other flags=0x40
  serial num  :  1
Using slot 0 with a present token (0x0)
Public Key Object; RSA 2048 bits
  label:      ibis-it key
  ID:         a1b2
  Usage:      verify
Private Key Object; RSA
  label:      ibis-it key
  ID:         a1b2
  Usage:      sign

The Problem is that SoftHSM only imports PKCS#8 (RSA) key pairs, so there will never be a certificate here. I suppose you have been using it with RSA key pairs but not with certificates.

A: Parameters passed to the constructor of Net.Pkcs11Interop.PDF.Pkcs11RsaSignature class identify following things:

*

*which PKCS#11 library should be used (libraryPath)

*which token/smartcard stores the private key (tokenSerial and/or tokenLabel)

*which private key should be used for signing (ckaLabel and/or ckaId)

*which hash algorithm should be used during signature creation (hashAlgorithm)

If you know which PKCS#11 library should be used to access the smartcard then you can determine correct values for the rest of the parameters i.e. by running pkcs11-tool utility which is bundled with OpenSC middleware. Please find below the exact command and the output generated for my testing card (important parts are highlighted with bold text):
C:\Program Files (x86)\OpenSC Project\OpenSC\tools>pkcs11-tool.exe --module cardos11.dll --list-slots --list-objects --login --pin 11111111
Available slots:
Slot 0 (0x1): SCM Microsystems Inc. SCR33x USB Smart Card Reader 0
  token label        : Pkcs11Interop
  token manufacturer : www.atos.net/cardos
  token model        : CardOS V4.3B
  token flags        : rng, login required, PIN initialized, token initialized, other flags=0x800
  hardware version   : 102.63
  firmware version   : 200.8
  serial num         : 7BFF2737350B262C
Using slot 0 with a present token (0x1)
Private Key Object; RSA
  label:      John Doe
  ID:         ec5e50a889b888d600c6e13cb0fdf0c1
  Usage:      sign
Certificate Object, type = X.509 cert
  label:      John Doe
  ID:         ec5e50a889b888d600c6e13cb0fdf0c1
Based on this output these are the correct values of individual parameters for this card:

*

*libraryPath="cardos11.dll"

*tokenSerial="7BFF2737350B262C" and/or tokenLabel="Pkcs11Interop"

*ckaLabel="John Doe" and/or ckaId="ec5e50a889b888d600c6e13cb0fdf0c1"

Hope this helps.
Update for ObjectNotFoundException:
You are getting ObjectNotFoundException because there are two private keys with the exactly same label and ID stored in your token and therefore Pkcs11RsaSignature class cannot be sure which one should be used for signature creation. Just delete or rename one of them and it should be working.
Update for SoftHSM:
You can import PKCS#8 private key to SoftHSM with softhsm.exe tool:
C:\SoftHSM\bin>softhsm.exe --import doe.key --slot 0 --label "John Doe" --pin 11111111 --id "ec5e50a889b888d600c6e13cb0fdf0c1"
The key pair has been imported to the token in slot 0.

You can import DER encoded X.509 certificate to SoftHSM with pkcs11-tool.exe tool:
C:\SoftHSM\bin>"c:\Program Files (x86)\OpenSC Project\OpenSC\tools\pkcs11-tool.exe" --module libsofthsm.dll --login --pin 11111111 --write-object doe.der --type cert --label "John Doe" --id "ec5e50a889b888d600c6e13cb0fdf0c1"
Using slot 0 with a present token (0x0)
Created certificate:
Certificate Object, type = X.509 cert
  label:      John Doe
  ID:         ec5e50a889b888d600c6e13cb0fdf0c1

Just make sure you will import the certificate with the same ID as the ID of private key.


text:
Q: Reset / Reuse / Clone cURL Multi Handle I have a specific problem which requires me to reuse cURL multi handles. Is there a way to do that? I tried to use
curl_copy_handle()

And it did not work saying
 curl_copy_handle(): supplied resource is not a valid cURL handle resource

Which is not totally unexpected. Is there a way to reuse or clone a cURL multi handle?
Edit: Calling
clone

Also does not work
Fatal error:  __clone method called on non-object

A: I don't think this is possible with a single built-in function.
As you creating the original cURL multi handle, right before each curl_multi_add_handle() call, save a copy of each easy (regular) handle in an array A with curl_copy_handle().
Then, when you need to re-use the multi handle:

*

*Create a new empty one with curl_multi_init()

*Loop through each element of A

*In the loop, use curl_multi_add_handle() to add a copy (again, with curl_copy_handle()) of each easy handle to the new multi handle


text:
Q: MPAndroid Chart dissapears after calling invalidate() with new data In my Weather app, I have a MainFragment which has a button that opens a different fragment (SearchFragment) (via replace), allows a user to select a location and then fetches weather data for that location and loads it in various views including an MPAndroid LineChart. My issue is that whenever I come back from the search fragment, although the new data is fetched for the chart and I'm calling chart.notifyDataSetChanged() & chart.invalidate() (also tried chart.postInvalidate() since it was suggested when working on another thread) after the invalidate() is called the chart simply disappears. What am i missing here?
MainFragment:
const val UNIT_SYSTEM_KEY = "UNIT_SYSTEM"
const val LATEST_CURRENT_LOCATION_KEY = "LATEST_CURRENT_LOC"

class MainFragment : Fragment() {

// Lazy inject the view model
private val viewModel: WeatherViewModel by viewModel()
private lateinit var weatherUnitConverter: WeatherUnitConverter

private val TAG = MainFragment::class.java.simpleName

// View declarations
...

// OnClickListener to handle the current weather's "Details" layout expansion/collapse
private val onCurrentWeatherDetailsClicked = View.OnClickListener {
    if (detailsExpandedLayout.visibility == View.GONE) {
        detailsExpandedLayout.visibility = View.VISIBLE
        detailsExpandedArrow.setImageResource(R.drawable.ic_arrow_up_black)
    } else {
        detailsExpandedLayout.visibility = View.GONE
        detailsExpandedArrow.setImageResource(R.drawable.ic_down_arrow)
    }
}

// OnClickListener to handle place searching using the Places SDK
private val onPlaceSearchInitiated = View.OnClickListener {
    (activity as MainActivity).openSearchPage()
}

// RefreshListener to update the UI when the location settings are changed
private val refreshListener = SwipeRefreshLayout.OnRefreshListener {
    Toast.makeText(activity, "calling onRefresh()", Toast.LENGTH_SHORT).show()
    swipeRefreshLayout.isRefreshing = false
}

// OnClickListener to allow navigating from this fragment to the settings one
private val onSettingsButtonClicked: View.OnClickListener = View.OnClickListener {
    (activity as MainActivity).openSettingsPage()
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val view = inflater.inflate(R.layout.main_fragment, container, false)
    // View initializations
    .....
    hourlyChart = view.findViewById(R.id.lc_hourly_forecasts)
    return view
}

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    setUpChart()
    lifecycleScope.launch {
        // Shows a lottie animation while the data is being loaded
        //scrollView.visibility = View.GONE
        //lottieAnimView.visibility = View.VISIBLE
        bindUIAsync().await()
        // Stops the animation and reveals the layout with the data loaded
        //scrollView.visibility = View.VISIBLE
        //lottieAnimView.visibility = View.GONE
    }
}

@SuppressLint("SimpleDateFormat")
    private fun bindUIAsync() = lifecycleScope.async(Dispatchers.Main) {
        // fetch current weather
        val currentWeather = viewModel.currentWeatherData

    // Observe the current weather live data
    currentWeather.observe(viewLifecycleOwner, Observer { currentlyLiveData ->
        if (currentlyLiveData == null) return@Observer

        currentlyLiveData.observe(viewLifecycleOwner, Observer { currently ->

            setCurrentWeatherDate(currently.time.toDouble())

            // Get the unit system pref's value
            val unitSystem = viewModel.preferences.getString(
                UNIT_SYSTEM_KEY,
                UnitSystem.SI.name.toLowerCase(Locale.ROOT)
            )

            // set up views dependent on the Unit System pref's value
            when (unitSystem) {
                UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> {
                    setCurrentWeatherTemp(currently.temperature)
                    setUnitSystemImgView(unitSystem)
                }
                UnitSystem.US.name.toLowerCase(Locale.ROOT) -> {
                    setCurrentWeatherTemp(
                        weatherUnitConverter.convertToFahrenheit(
                            currently.temperature
                        )
                    )
                    setUnitSystemImgView(unitSystem)
                }
            }

            setCurrentWeatherSummaryText(currently.summary)
            setCurrentWeatherSummaryIcon(currently.icon)
            setCurrentWeatherPrecipProb(currently.precipProbability)
        })
    })

    // fetch the location
    val weatherLocation = viewModel.weatherLocation
    // Observe the location for changes
    weatherLocation.observe(viewLifecycleOwner, Observer { locationLiveData ->
        if (locationLiveData == null) return@Observer

        locationLiveData.observe(viewLifecycleOwner, Observer { location ->
            Log.d(TAG,"location update = $location")
            locationTxtView.text = location.name
        })
    })

    // fetch hourly weather
    val hourlyWeather = viewModel.hourlyWeatherEntries

    // Observe the hourly weather live data
    hourlyWeather.observe(viewLifecycleOwner, Observer { hourlyLiveData ->
        if (hourlyLiveData == null) return@Observer

        hourlyLiveData.observe(viewLifecycleOwner, Observer { hourly ->
            val xAxisLabels = arrayListOf<String>()
            val sdf = SimpleDateFormat("HH")
            for (i in hourly.indices) {
                val formattedLabel = sdf.format(Date(hourly[i].time * 1000))
                xAxisLabels.add(formattedLabel)
            }
            setChartAxisLabels(xAxisLabels)
        })
    })

    // fetch weekly weather
    val weeklyWeather = viewModel.weeklyWeatherEntries

    // get the timezone from the prefs
    val tmz = viewModel.preferences.getString(LOCATION_TIMEZONE_KEY, "America/Los_Angeles")!!

    // observe the weekly weather live data
    weeklyWeather.observe(viewLifecycleOwner, Observer { weeklyLiveData ->
        if (weeklyLiveData == null) return@Observer

        weeklyLiveData.observe(viewLifecycleOwner, Observer { weatherEntries ->
            // update the recyclerView with the new data
            (weeklyForecastRCV.adapter as WeeklyWeatherAdapter).updateWeeklyWeatherData(
                weatherEntries, tmz
            )
            for (day in weatherEntries) { //TODO:sp replace this with the full list once the repo issue is fixed
                val zdtNow = Instant.now().atZone(ZoneId.of(tmz))
                val dayZdt = Instant.ofEpochSecond(day.time).atZone(ZoneId.of(tmz))
                val formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
                val formattedNowZtd = zdtNow.format(formatter)
                val formattedDayZtd = dayZdt.format(formatter)
                if (formattedNowZtd == formattedDayZtd) { // find the right week day whose data we want to use for the UI
                    initTodayData(day, tmz)
                }
            }
        })
    })

    // get the hourly chart's computed data
    val hourlyChartLineData = viewModel.hourlyChartData

    // Observe the chart's data
    hourlyChartLineData.observe(viewLifecycleOwner, Observer { lineData ->
        if(lineData == null) return@Observer

        hourlyChart.data = lineData // Error due to the live data value being of type Unit
    })

    return@async true
}

...

private fun setChartAxisLabels(labels: ArrayList<String>) {
    // Populate the X axis with the hour labels
    hourlyChart.xAxis.valueFormatter = IndexAxisValueFormatter(labels)
}

/**
 * Sets up the chart with the appropriate
 * customizations.
 */
private fun setUpChart() {
    hourlyChart.apply {
        description.isEnabled = false
        setNoDataText("Data is loading...")

        // enable touch gestures
        setTouchEnabled(true)
        dragDecelerationFrictionCoef = 0.9f

        // enable dragging
        isDragEnabled = true
        isHighlightPerDragEnabled = true
        setDrawGridBackground(false)
        axisRight.setDrawLabels(false)
        axisLeft.setDrawLabels(false)
        axisLeft.setDrawGridLines(false)
        xAxis.setDrawGridLines(false)
        xAxis.isEnabled = true

        // disable zoom functionality
        setScaleEnabled(false)
        setPinchZoom(false)
        isDoubleTapToZoomEnabled = false

        // disable the chart's legend
        legend.isEnabled = false

        // append extra offsets to the chart's auto-calculated ones
        setExtraOffsets(0f, 0f, 0f, 10f)

        data = LineData()
        data.isHighlightEnabled = false
        setVisibleXRangeMaximum(6f)
        setBackgroundColor(resources.getColor(R.color.bright_White, null))
    }

    // X Axis setup
    hourlyChart.xAxis.apply {
        position = XAxis.XAxisPosition.BOTTOM
        textSize = 14f
        setDrawLabels(true)
        setDrawAxisLine(false)
        granularity = 1f // one hour
        spaceMax = 0.2f // add padding start
        spaceMin = 0.2f // add padding end
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            typeface = resources.getFont(R.font.work_sans)
        }
        textColor = resources.getColor(R.color.black, null)
    }

    // Left Y axis setup
    hourlyChart.axisLeft.apply {
        setDrawLabels(false)
        setDrawGridLines(false)
        setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
        isEnabled = false
        isGranularityEnabled = true
        // temperature values range (higher than probable temps in order to scale down the chart)
        axisMinimum = 0f
        axisMaximum = when (getUnitSystemValue()) {
            UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> 50f
            UnitSystem.US.name.toLowerCase(Locale.ROOT) -> 150f
            else -> 50f
        }
    }

    // Right Y axis setup
   hourlyChart.axisRight.apply {
       setDrawGridLines(false)
       isEnabled = false
   }
}
}

ViewModel class:
class WeatherViewModel(
private val forecastRepository: ForecastRepository,
private val weatherUnitConverter: WeatherUnitConverter,
context: Context
) : ViewModel() {

private val appContext = context.applicationContext

// Retrieve the sharedPrefs
val preferences:SharedPreferences
    get() = PreferenceManager.getDefaultSharedPreferences(appContext)

// This will run only when currentWeatherData is called from the View
val currentWeatherData = liveData {
    val task = viewModelScope.async {  forecastRepository.getCurrentWeather() }
    emit(task.await())
}

val hourlyWeatherEntries = liveData {
    val task = viewModelScope.async {  forecastRepository.getHourlyWeather() }
    emit(task.await())
}

val weeklyWeatherEntries = liveData {
    val task = viewModelScope.async {
        val currentDateEpoch = LocalDate.now().toEpochDay()
        forecastRepository.getWeekDayWeatherList(currentDateEpoch)
    }
    emit(task.await())
}

val weatherLocation = liveData {
    val task = viewModelScope.async(Dispatchers.IO) {
        forecastRepository.getWeatherLocation()
    }
    emit(task.await())
}

val hourlyChartData = liveData {
    val task = viewModelScope.async(Dispatchers.Default) {
        // Build the chart data
        hourlyWeatherEntries.observeForever { hourlyWeatherLiveData ->
            if(hourlyWeatherLiveData == null) return@observeForever

            hourlyWeatherLiveData.observeForever {hourlyWeather ->
                createChartData(hourlyWeather)
            }
        }
    }
    emit(task.await())
}

/**
 * Creates the line chart's data and returns them.
 * @return The line chart's data (x,y) value pairs
 */
private fun createChartData(hourlyWeather: List<HourWeatherEntry>?): LineData {
    if(hourlyWeather == null) return LineData()

    val unitSystemValue = preferences.getString(UNIT_SYSTEM_KEY, "si")!!
    val values = arrayListOf<Entry>()

    for (i in hourlyWeather.indices) { // init data points
        // format the temperature appropriately based on the unit system selected
        val hourTempFormatted = when (unitSystemValue) {
            UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> hourlyWeather[i].temperature
            UnitSystem.US.name.toLowerCase(Locale.ROOT) -> weatherUnitConverter.convertToFahrenheit(
                hourlyWeather[i].temperature
            )
            else -> hourlyWeather[i].temperature
        }

        // Create the data point
        values.add(
            Entry(
                i.toFloat(),
                hourTempFormatted.toFloat(),
                appContext.resources.getDrawable(determineSummaryIcon(hourlyWeather[i].icon), null)
            )
        )
    }
    Log.d("MainFragment viewModel", "$values")
    // create a data set and customize it
    val lineDataSet = LineDataSet(values, "")

    val color = appContext.resources.getColor(R.color.black, null)
    val offset = MPPointF.getInstance()
    offset.y = -35f

    lineDataSet.apply {
        valueFormatter = YValueFormatter()
        setDrawValues(true)
        fillDrawable = appContext.resources.getDrawable(R.drawable.gradient_night_chart, null)
        setDrawFilled(true)
        setDrawIcons(true)
        setCircleColor(color)
        mode = LineDataSet.Mode.HORIZONTAL_BEZIER
        this.color = color // line color
        iconsOffset = offset
        lineWidth = 3f
        valueTextSize = 9f
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            valueTypeface = appContext.resources.getFont(R.font.work_sans_medium)
        }
    }

    // create a LineData object using our LineDataSet
    val data = LineData(lineDataSet)
    data.apply {
        setValueTextColor(R.color.colorPrimary)
        setValueTextSize(15f)
    }
    return data
}

private fun determineSummaryIcon(icon: String): Int {
    return when (icon) {
        "clear-day" -> R.drawable.ic_sun
        "clear-night" -> R.drawable.ic_moon
        "rain" -> R.drawable.ic_precipitation
        "snow" -> R.drawable.ic_snowflake
        "sleet" -> R.drawable.ic_sleet
        "wind" -> R.drawable.ic_wind_speed
        "fog" -> R.drawable.ic_fog
        "cloudy" -> R.drawable.ic_cloud_coverage
        "partly-cloudy-day" -> R.drawable.ic_cloudy_day
        "partly-cloudy-night" -> R.drawable.ic_cloudy_night
        "hail" -> R.drawable.ic_hail
        "thunderstorm" -> R.drawable.ic_thunderstorm
        "tornado" -> R.drawable.ic_tornado
        else -> R.drawable.ic_sun
    }
}

}
LazyDeferred:
fun<T> lazyDeferred(block: suspend CoroutineScope.() -> T) : Lazy<Deferred<T>> {
    return lazy {
        GlobalScope.async {
            block.invoke(this)
        }
    }
}

ScopedFragment :
abstract class ScopedFragment : Fragment(), CoroutineScope {
private lateinit var job: Job

override val coroutineContext: CoroutineContext
    get() = job + Dispatchers.Main

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    job = Job()
}

override fun onDestroy() {
    job.cancel()
    super.onDestroy()
}
}

A: Without the entire environment it's really hard for me to help you debug the whole thing but I am happy to provide you with a couple of things that seem a little bit off at a first glance.
First of all I would avoid managing all CoroutinesScopes and lifecycles by yourself and it's easy to get it wrong. So I would rely on what the Android team has already done. Take a quick look here, it's really easy to setup and use. The dev experience is great.
Posting Deferred on a LiveData and awaiting on the view side looks like a code smell…

*

*What if there's a network error?
It would result in an exception or cancellation exception being thrown.

*What if the task was already perform and causes some type of UI consistency problem? These are a couple of edge cases I would not really want to handle.
Just observe a LiveData since it is its main purpose: it's a value holder and it's intended to live throught several lifecycle events in the Fragment. So once view is recreated the value is ready in the LiveData inside the ViewModel.
Your lazyDeferred function is quite smart but in the Android world it's also  dangerous. Those coroutines don't live inside any lifecycle-controlled scope so they have a really high chance to end up being leaked. And trust me, you don't want any coroutines being leaked since they continue their work even after viewmodel and fragment destruction which is something you definetely don't want.
All of these are easily fixable by using the dependency I've mentioned before, which I'll paste here once more
Here's a snippet on how you could use those utilities in your ViewModel to ensure the lifecycle of things nor coroutines are causing any issues:
class WeatherViewModel(
    private val forecastRepository: ForecastRepository,
    context: Context
) : ViewModel() {

    private val appContext = context.applicationContext

    // Retrieve the sharedPrefs
    val preferences:SharedPreferences
        get() = PreferenceManager.getDefaultSharedPreferences(appContext)

    // This will run only when currentWeatherData is called from the View
    val currentWeatherData = liveData {
        val task = viewModelScope.async { forecastRepository.getCurrentWeather() }
        emit(task.await())
    }

    val hourlyWeatherEntries = liveData {
        val task = viewModelScope.async { forecastRepository.getHourlyWeather() }
        emit(task.await())

    }

    val weeklyWeatherEntries = liveData {
        val task = viewModelScope.async {
            val currentDateEpoch = LocalDate.now().toEpochDay()
            forecastRepository.getWeekDayWeatherList(currentDateEpoch)
        }
        emit(task.await())
    }

    val weatherLocation = liveData {
        val task = viewModelScope.async(Dispatchers.IO) {
            forecastRepository.getWeatherLocation()
        }
        emit(task.await())
    }

}

By using the following approach all network calls are performed in a parallel fashion and they are all tied to the viewModelScope without writing a single line of handling the CoroutineScope's life. When the ViewModel dies, so will the scope. when the view gets re-created the routines won't execute twice and values will be ready to read.
Regarding the configuration of the chart: I would highly suggest you configure the chart as soon as you have created the view, since it is highly tied together. Configuration is something you want to do just once and may cause visual bugs if some instructions are executed more than once (which I believe it could be happening to you), just saying so because I've had problems with MPAndroid using a Piechart.
More on the chart: All of the logic of constructing the LineData would be better off on a background thread and being exposed through a LiveData in the ViewModel side like you would do with all of the other
val property = liveData {
    val deferred = viewModelScope.async(Dispatchers.Default) {
        // Heavy building logic like:
        createChartData()
    }
    emit(deferred.await())
}

Pro Kotlin tip: Avoid repeating yourself during those long MPAndroid configurations functions.
Instead of:
view.configureThis()
view.configureThat()
view.enabled = true

Do:
view.apply {
    configureThis()
    configureThat()
    enabled = true
}

I'm sad that I can just give you these hints and being unable to exactly pin-point what your issue is since the bug is heavily related to what is happenning throughout the lifecycle evolution of the runtime but hopefuly this is going to be useful
Answering your comment
If one of your data-streams (LiveData) is dependent on what another data-stream (another LiveData) is going to emit you are looking for LiveData.map and LiveData.switchMap operations.
I imagine that hourlyWeatherEntries is going to be emitting values from time to time.
In that case you can use LiveData.switchMap.
What this does is that everytime the source LiveData emits a value, you're going to get a callback and you are expected to return a new live data with the new value.
You could arrange something like the following:
val hourlyChartData = hourlyWeatherEntries.switchMap { hourlyWeather ->
    liveData {
        val task = viewModelScope.async(Dispatchers.IO) {
            createChartData(hourlyWeather)
        }
        emit(task.await())
    }
}

Using this approach has the benefit that it is completely lazy. That means that NO COMPUTATION is going to take place UNLESS data is being actively observed by some lifecycleOwner. That just means that no callbacks are being triggered unless data is observed in the Fragment
Further explanation on map and switchMap
Since we need to do some asynchronous computation that we don't know when it's going to be done we can't use map. map applies a linear transformation between LiveDatas. Check this out:
val liveDataOfNumbers = liveData { // Returns a LiveData<Int>
    viewModelScope.async {
         for(i in 0..10) {
             emit(i)
             delay(1000)
         }
    }
}

val liveDataOfDoubleNumbers = liveDataOfNumbers.map { number -> number * 2}

This is really useful when the computation is linear and simple. What is happening behind the hood is that the library is handling observing and emitting values for you by means of a MediatorLiveData. What happens here is that whenever liveDataOfNumbers emits a value and liveDataOfDoubleNumbers is being observed the callback gets applied; so the liveDataOfDoubleNumbers is emitting: 0, 2, 4, 6…
The snippet above is equivalent to the following:
val liveDataOfNumbers = liveData { // Returns a LiveData<Int>
    viewModelScope.async {
         for(i in 0..10) {
             emit(i)
             delay(1000)
         }
    }
}

val liveDataOfDoubleNumbers = MediatorLiveData<Int>().apply {
    addSource(liveDataOfNumbers) { newNumber ->
        // Update MediatorLiveData value when liveDataOfNumbers creates a new number
        value = newNumber * 2
    }
}

But just using map is much much simpler.
Fantastic!!
Now going to your use-case. Your computation is linear but we want to defer that work to a background coroutine. So we can't exactly tell when something is going to end.
For these use-cases they have created the switchMap operator. What it does it's just the same as map but wraps everything within another LiveData. The intermediate LiveData just acts as a container for the response that is going to come from the coroutine.
So what ends up happening is:

*

*Your coroutine publishes into intermediateLiveData

*switchMap does something similar to:

return MediatorLiveData().apply {
    // intermediateLiveData is what your callback generates
    addSource(intermediateLiveData) { newValue -> this.value = newValue }
} as LiveData

Summing up:
1. Coroutine passes value to intermediateLiveData
2. intermediateLiveData passes value to the hourlyChartData
3. hourlyChartData passes value to the UI
And everything without adding or removing observeForever
Since the liveData {…} is a builder to help us create asynchronous LiveDatas without dealing with the hassle of instantiating them we can use it so our switchMap callback is less verbose.
The function liveData returns a live data of type LiveData<T>. If your repository call already returns a LiveData it's really simple!
val someLiveData = originalLiveData.switchMap { newValue ->
   someRepositoryCall(newValue).map { returnedRepoValue -> /*your transformation code here*/}
}

A: Separate the setupChart and setData logics. Setup chart once out of the observer, inside the observer setData and after that call invalidate().

A: Try commenting out the invalidate() part and wherever you are calling your search function before it try yourlineChart.clear(); or yourlineChart.clearValues();. This will clear the previous values of the chart and will form chart with new values. So, invalidate() and chart.notifyDataSetChanged() won't not be necessary and it should solve your problem.


text:
Q: glob.glob print returns unknown character block When I run my function, it shows the tuple as being empty, even though it should find something in the directory.
The first function "check_files('\\SERVER1\C$\DIRECTORY\', '*.pdf', 'Test 0')" Returns TRUE, since there is a file in the directory.
For the following functions, it returns FALSE, even though there are files in the directory. Doing a print statement of "Output" it shows

This makes me think it cant find the directory and throwing the whole thing off.
What gives??
import os
import glob

def check_files(mydir, myext, name):
     check = mydir + myext
     print(str(check))
     Output = glob.glob(check)
          if Output == []: #FALSE
               print (str(name) + 'All Operational.')
          else: #TRUE
               print (str(name) + 'I see some files here, please check the process.')

check_files('\\\SERVER1\\C$\\DIRECTORY\\', '*.pdf', 'Test 0')
check_files('\\\10.2.2.1\\Directory\\', '*.pdf', 'Test 1: ')
check_files('\\\10.3.2.1\\Directory\\', '*.pdf', 'Test 2: ')
check_files('\\\10.4.2.1\\Directory\\', '*.pdf', 'Test 3: ')

A: You need to escape all of the \ characters.  Try running print('\1') to see why.
check_files('\\\\10.2.2.1\\Directory\\', '*.pdf', 'Test 1: ')

etc.


text:
Q: Connect Firebase with React Native I'm trying to connect React Native with Firebase. I'm using the following method to connect Firebase.
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
  apiKey: "<YOUR-API-KEY>",
  authDomain: "<YOUR-AUTH-DOMAIN>",
  databaseURL: "<YOUR-DATABASE-URL>",
  storageBucket: "<YOUR-STORAGE-BUCKET>"
};
firebase.initializeApp(firebaseConfig);

app.authWithPassword({
  "email": "abc@abc.com",
  "password": "abc1234"
}, (error, user_data) => {
  if (error) {
    alert('Login Failed. Please try again');
  } else {
    AsyncStorage.setItem('user_data', JSON.stringify(user_data));
  }
});

But it returns the following error:

app.authWithPassword is not a function.

I'm using Firebase 3.4 and React Native 0.32.

A: From the Firebase documentation:
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});