text:
Q: Docker-compose skips CMD command to login into a service I'm trying to start the service "windsribe vpn" and then login. my docker file is able to run the start command etc/init.d/windscribe-cli start to start the service but it skips the command  windscribe login,
when I run sudo docker-compose up the output is:
Starting windscribe ... OK
which means it started but it stays there, is not showing any errors.
it doesn't show any other output but should be showing
Windscribe Username: example-username
Windscribe Password: example-password

in the output to login
I'm using the line
 CMD bash -c "/etc/init.d/windscribe-cli start && windscribe login" and I even try to run other lines like:
CMD bash -c "/etc/init.d/windscribe-cli start && python3 myscript.py" which works for starting the service and running the python script but for some reason it never shows the login output
this is my DockerFile
FROM ubuntu:latest
RUN apt-get update
#install windscribe
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-key FDC247B7
RUN echo 'deb https://repo.windscribe.com/ubuntu bionic main' | tee /etc/apt/sources.list.d/windscribe-repo.list
RUN apt-get -y update
RUN apt-get install -y windscribe-cli

ENV HOME /home/host

COPY ["./"]

CMD bash -c "/etc/init.d/windscribe-cli start && windscribe login"

and this is my docker-compose.yml
version: "3"
services:
  app:
    image: my-app:latest
    deploy:
      replicas: 1
      update_config:
        parallelism: 1
        delay: 5s
      restart_policy:
        condition: on-failure
    build: .
    environment:
      - DISPLAY=${DISPLAY}
    volumes:
      - /tmp/.X11-unix:/tmp/.X11-unix
    networks:
      - scrapping
    tty: true

networks:
  scrapping:
    ipam:
      driver: default
      config:
        - subnet: 192.168.150.0/24

EDIT here I'm adding the output for the command windscribe status and the cmd line would look like this CMD bash -c "/etc/init.d/windscribe-cli start && windscribe status && windscribe login"
and it's output is:
 Starting windscribe ... OK
 windscribe -- pid: 19, status: running, uptime: 0m, %cpu: 0.0, %mem:
 0.2

A: Due to && short circuiting, if /etc/init.d/windscribe-cli start fails, windscribe login will never run.
/etc/init.d/windscribe-cli start won't work, because there's no init system in the Ubuntu docker image.
On a best practices note, you will for all practical purposes never find a Docker image with an init system in it.
You can take a look at the windscribe docs and figure out how to run it manually. That's the process you'll want to use in your Docker image.

A: windscribe login is probably an interactive command, but you are not running the container with the interactive setting. This can cause all kinds of weird behaviors with interactive commands, and may be the cause of what you're seeing.
As per this answer: Interactive shell using Docker Compose
Try adding the interactive setting and see if that fixes the problem:
    stdin_open: true # docker run -i

Or for the full thing:
version: "3"
services:
  app:
    image: my-app:latest
    deploy:
      replicas: 1
      update_config:
        parallelism: 1
        delay: 5s
      restart_policy:
        condition: on-failure
    build: .
    environment:
      - DISPLAY=${DISPLAY}
    volumes:
      - /tmp/.X11-unix:/tmp/.X11-unix
    networks:
      - scrapping
    stdin_open: true # docker run -i
    tty: true


text:
Q: Beaglebone Angstrom: how to enable read only root file system I am developing applications on Beaglebone board with Angstrom Linux distro.
I tend to mount root file system as read only because, it is not robust on readable/writeable  configuration across power offs.
Can you make suggestions about how to mount root file system as read only?
What are the steps for mounting root file system read only and then turn it back to readable/writable?
With these step i tend to get a more robust file system.
Regards

A: You would need to edit the boot arguments that you pass to the kernel to use ro instead of rw for mounting the root file system. For example root=/dev/mmcblk0p1 ro. They are modifiable via the uboot environment variables

A: On a similar Angstrom-based system, I got the same "must specify the filesystem type" message.
After trying a few different things, I was able to remount root as ro using:
busybox mount -o remount,ro /
I have to admit I'm not certain why calling busybox directly worked when the "mount" command (which is a link to busybox) did not work, but I didn't have time to dig further.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extremum of a function I want to know whether it is possible that a point be an extremum without the derivative at that point being zero ?
I encountered this point when reading about the fact that entropy maximizes as function of energy but we know that $1/T=\frac{\partial S}{\partial E}$ (assuming Entropy is smooth and differentiable in the desired domain) which would make temperature infinite.
I already read a similar post on Physics Stackexchange but didn't get satisfactory answer.

A: It is possible, if your domain is compact with boundary or has a discontinuity: for the easiest example, think of a graph of a straight line y=x on $0 \leq x \leq 10$ having a maximum at (10, 10) and a minimum at (0,0).
If there's a discontinuity in the domain or the range (far more treacherous), an extremum could occur there (again, the graph of the function would 'break off' and continue elsewhere).

A: More ever of the points that derivative is equal to zero the the span boundaries also should be considered as critical points

A: Just pointing out another example, to add to all of this.
The absolute value function does not have a definite value for the derivative at the Origin (the extremum), as the relevant limit does not exist at said point.

A: Consider $f(x) = |x|$.  It has a minimum at $x= 0$, but the derivative isn't $0$ at $x=0$.  Or consider the function $g:[-1,2]\to [0,4]$ via $g(x) = x^2$.  It has a maximum at $x=2$ but $g'(2) = 4$.
These are exceptions of course.  If $f$ is continuous, differentiable and $x$ is not an extreme point of a compact domain then an extremum and $x$ would imply that the derivative at $x$ is zero.  That should be easy to show by definitions.  (Intuitively if the derivative is positive or negative, the function is increasing or decreasing which means there will be points before and after which are larger on one side and smaller on the other.)


text:
Q: Typescript Error, Cannot find name 'gapi', transpile failed I trying to implement google auth in my ionic2 app. I need it works in browser. So, I installed:
npm install --save @types/gapi
npm install --save @types/gapi.auth2

There is two warnings:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0
  (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup
  SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for
  fsevents@1.0.15: wanted {"os":"darwin","arch":"any"} (current:
  {"os":"win32","arch":"x64"})

In node_modules folder I have gapi and gapi.auth2 folders but I have typescript error: Cannot find name 'gapi', transpile failed.
I installed
npm install typings -g
typings install dt~gapi --global --save
typings install dt~gapi.auth2 --global --save

Still have the same error: Cannot find name 'gapi', transpile failed
my code:
auth2: any;

login() {
      gapi.load('auth2', () => {
          this.auth2 = gapi.auth2.init({
             client_id: 'xxxxxxxxx.apps.googleusercontent.com',
             scope: 'https://www.googleapis.com/auth/userinfo.email'
          });
        });
      };

my package.json:
"@angular/core": "2.2.1",
"ionic-angular": "2.0.0-rc.4",
"ionic-native": "2.2.11",
"rxjs": "5.0.0-beta.12",
"typescript": "2.0.9"

A: The current declarations for gapi and for gapi.auth2 are global declarations.
They might not be automatically with @types because looking into node_modules either requires an explicit import or adding your libraries to the types field in your tsconfig.json.
So try fixing up the following types field to your compilerOptions:
"compilerOptions": {
     "types": ["gapi", "gapi.auth2"]
}


text:
Q: How can I "snap scroll" and trigger the event when snapped? I tried using scroll-snap CSS property which works well in terms of the representation.
but I need to trigger an event when scrolled/snapped. how can I do that?

A: As Mladen suggested, using the Intersection Observer Api seems to (kinda) work.
(Seems buggy on latest Firefox -- when scrolling up, observer goes crazy and logs only first section -- works fine on latest Chrome)

const observer = new IntersectionObserver(entries => {
  entries.forEach(elem => {
    if (elem.isIntersecting) {
      const text = elem.target.querySelector('h2').innerText;
      console.log('Ping! Visible: ', text);
    }
  });
});

document.querySelectorAll('section').forEach(elem => observer.observe(elem));
.scroller {
  height: 300px;
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
}

.scroller section {
  height: 300px;
  background: gray;
  border: 1px solid black;
  scroll-snap-align: start;
}

Section one

Section two

Section three

I don't know if there's another way.

A: The CSS Scroll Snap Module Level 2 specification defines two events snapChanging and snapChanged. The first one is obviously triggered when scrolling away from a snap position and the latter when the scroll position got snapped. The latter obviously covers your use case.
Though, as of the time of posting this answer, the specification is an early draft and no browser supports those events.
So, as long as they are not available, you'll have to use some polyfill.


text:
Q: Graphviz/Python: Recoloring a single node after it has been generated I am getting acquainted with graphviz within Python 2.7.  Is it possible to change the properties of a single node after it has been drawn?
e.g.
from graphviz import Digraph
q = Digraph()
q.node('a')
q.node('b')
q.edge('a','b')

q

Is it possible to change the color of node 'b' after the fact?  I am aware that I can set it at the time of generation by
q.node('b', color = 'blue')

But, I'd like to be able to change it after generating it.
This link Color a particular node in Networkx and Graphviz
suggests using the graph's .node property to update a dict
G.node[2]['fillcolor']='red'

By analogy, I tried
q.node['b']['color'] = 'blue'

which gives an error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-43b05071d09a> in <module>()
----> 1 q.node['b']['color'] = 'blue'

TypeError: 'instancemethod' object has no attribute '__getitem__'

I think this may be because I am not using networkx as in the previous case.
I've also read the graphviz docs at http://graphviz.org/content/attrs
but none of my experiments have worked.  I'm sure it is something straightforward but I am missing it...
--- Old Guy In The Club

A: I've read through the API docs and don't think it's possible to edit a node after construction.
If you don't want to use networkx, one workaround would be to store the graph in your own data structure and use that to create the graphviz graph at the point when you're ready to (re-)render it. For example, you could keep a list of the names of all the nodes that should be blue, and then refer to that at the point of constructing your graphviz graph. Separating the model from its rendering in this way might also lead to easier maintenance.

A: One way to do it is by editing the graph object directly.
>>> from graphviztest import *
>>> import json
>>> dot = Digraph(comment='My graph', format='png')
>>> dot.node('A', 'hurr')
>>> dot.node('B', 'durr')
>>> dot.edge('A','B')
>>> print dot
// My graph
digraph {
    A [label=hurr]
    B [label=durr]
    A -> B
}
>>> print json.dumps(dot.__dict__, indent=2)
{
  "comment": "My graph",
  "_encoding": "utf-8",
  "name": null,
  "edge_attr": {},
  "_format": "png",
  "body": [
    "\tA [label=hurr]",
    "\tB [label=durr]",
    "\tA -> B"
  ],
  "filename": "Digraph.gv",
  "graph_attr": {},
  "strict": false,
  "node_attr": {}
}
>>> dot.body[0] = '\tA [label=derp]'
>>> dot.body[1] = '\tB [label=blah]'
>>> print dot
// My graph
digraph {
    A [label=derp]
    B [label=blah]
    A -> B
}
>>>

A: You could also save the resulting graph in SVG and edit the SVG directly, changing the color of a given node using CSS. In SVG, generated nodes have ids, making it easy to change the color (stroke attribute).

A: If you set your output format to dot, the layout is calculated, but not actually drawn.
You can then modify that (augmented) Graphviz file with Python, sed, awk, or gvpr (https://www.graphviz.org/pdf/gvpr.1.pdf) to modify colors and/or other attributes.
Then use this command to draw the graph: neato -n2 -Tpng myfile.dot >myfile.png
See here for more info on delayed drawing:  https://www.graphviz.org/faq/#FaqDotWithCoordsor


text:
Q: Cannot match any routes in Angular 2.1 I am using Angular 2.1.0 in a Visual Studio 2015 AspNetCore project and having an issue with routing in my lazy loaded modules. The error is as below:

core.umd.js:3257 EXCEPTION: Uncaught (in promise): Error: Cannot match
  any routes. URL Segment: 'Home/MyList' Error: Cannot match any
  routes. URL Segment: 'Home/MyList'
      at ApplyRedirects.noMatchError (http://localhost:31534/libraries/@angular/router/bundles/router.umd.js:769:20)
      at CatchSubscriber.eval [as selector] (http://localhost:31534/libraries/@angular/router/bundles/router.umd.js:747:33)
      at CatchSubscriber.error (http://localhost:31534/libraries/rxjs/operator/catch.js:52:31)
      at MapSubscriber.Subscriber._error (http://localhost:31534/libraries/rxjs/Subscriber.js:128:26)
      at MapSubscriber.Subscriber.error (http://localhost:31534/libraries/rxjs/Subscriber.js:102:18)
      at MapSubscriber.Subscriber._error (http://localhost:31534/libraries/rxjs/Subscriber.js:128:26)
      at MapSubscriber.Subscriber.error (http://localhost:31534/libraries/rxjs/Subscriber.js:102:18)
      at MapSubscriber.Subscriber._error (http://localhost:31534/libraries/rxjs/Subscriber.js:128:26)
      at MapSubscriber.Subscriber.error (http://localhost:31534/libraries/rxjs/Subscriber.js:102:18)
      at LastSubscriber.Subscriber._error (http://localhost:31534/libraries/rxjs/Subscriber.js:128:26)

I have followed the Tour Of Heroes tutorial and adapted it according to the lazy load topic here
I am loading a login page first {Home/Login} in the Bootstrapped module called AppModule. On clicking login I want to show the next page MyList, {Home/MyList}  which is lazily loaded into a feature module called MyModule.

MyModule is based on the HeroModule from the second link above.

MyList page and related component is the first page/component under MyModule which also has a MyListDetail page/component {Home/MyListDetail}.
I navigate to {Home/MyList} on a button click using this code
let link = ['Home/MyList'];
this.router.navigate(link);

Why are my routes not being found? Here is how I have them setup.
app-routing.module.ts
import { NgModule }             from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const routes: Routes = [
  { path: '', redirectTo: 'Home/Login', pathMatch: 'full'},
  { path: 'Home/MyList', loadChildren: 'scripts/My.Module#MyModule' }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

login-routing.module.ts
import { NgModule }            from '@angular/core';
import { Router, RouterModule }        from '@angular/router';

import { LoginCmpnt }  from './Login';

@NgModule({
  imports: [RouterModule.forChild([
    { path: 'Home/Login', component: LoginCmpnt}
  ])],
  exports: [RouterModule]
})
export class LoginRoutingModule {}

MyList-routing.module.ts
import { NgModule }            from '@angular/core';
import { Routes } from '@angular/router';
import { RouterModule }        from '@angular/router';
import { SharedModule } from './shared.module';
import { MyComponent } from './MyComponent';
import { MyListComponent }  from './MyListComp';
import { MyListDetailComponent }  from './MyListDetailComp';

const routes: Routes = [
  { path: '',
    component: MyComponent,
    children:   [{ path: 'Home/MyList',    component: MyListComponent },
         { path: 'Home/MyListDetail/:id', component: MyListDetailComponent }]
  }];

@NgModule({
    imports: [RouterModule.forChild([routes]), SharedModule ],
    exports: [RouterModule]})

export class MyListRoutingModule {}

In the MyList-routing.module above what should I put for the path against MyComponent? The login method routes to Home/MyList
EDIT
Even this with the slash preceding the path in the login click doesn't work.
let link = ['/Home/MyList'];
this.router.navigate(link);

A: Lazy loaded module most be like this:
 export class default MyModule{

 }

and in app.routing you most use load Child.


text:
Q: After Ubuntu 16.04 update some programs were lost I use Ubuntu 16.04. A couple of days ago I found that several programs, particularly R, KRDC, PlayOnLinux, cannot be launched and the OS does not see them at all. I looked at the installed packages with apt list --installed but also did not find any traces of them.
I repeated the installation of KRDC and it starts to work and founds all previous settings. However I do not think that this is a right way, since for R I'll need to re-install a lot of packages and dependencies.
I suspect that it was happened after one of automatic updates. But I did not launch those programs for a week or two and now I don't know how to detect what was wrong and how to fix this. Could you advice me something?
UPDATE.
I found partially broken Software center. Software & updates menu did not work. Re-installation fixed this. Probably there are more damaged software.

A: The upgrade process disables third-party ppas. If the programs you are missing came from this kind of source, you will have to re-enable the ppas and re-install the programs.

A: TRY TO INSERT THE REPOSITORY FILES INTO SOURCES.LIST FILE USING SUDO TO RESOLVE
USE THIS COMMANDS TO RESOLVE THE PROBLEM WITH PLAY ON LINUX
wget -q "http://deb.playonlinux.com/public.gpg" -O- | sudo apt-key add -
sudo wget http://deb.playonlinux.com/playonlinux_precise.list -O /etc/apt/sources.list.d/playonlinux.list
sudo apt-get update
sudo apt-get install playonlinux


text:
Q: calculating distances of equally distributed lines in 3d space I have 5 lines (d1 -> d5) equally distributed from each other in 3d perspective, and I have the values of angle (a), (d1) and (b5). I need to calculate (b2, b3, b4, d2, d3, d4, d5).

I can calculate d5 with:
d5 = d1 - ( b5 * Math.tan(a))

but I have no idea how to calculate b2, b3 and b4. (d1 is divided into 4 identical segments.)
Any help would be appreciated.


text:
Q: Best way to handle access to web dashboard displayed on "dumb" screen My web application has a dashboard page written in angularjs that is intended to be displayed on a screen in a room as a way of monitoring the information therein.
It's a dumb screen connected up to a machine with no easy access to input devices so I want to minimise the need to interact with the browser window. This leaves me with a puzzle as to how best retrieve the information and display it.
Using django as a backend, obviously the preferred solution would be to have a "Dashboard" user set up that is used to access the dashboard on the screen, however this then requires logging in (and as the session cookie will expire, this will need to be done every X days/weeks).
Leaving it open to viewable by anyone regardless of login isn't ideal- the data isn't particularly sensitive but I'd rather neither the page nor the API endpoint that fetches the data were exposed to the world.
I could use nginx reverse proxy to limit access to the dashboard to a specific (internal) ip/range but then that prevents users of the site who ARE logged in/authenticated and should otherwise be able to see the data from viewing the dashboard outside of the internal network.
Is there a balanced way to make the dashboard convenient to use while still maintaining security?
(I'll also need to handle refreshing the page automatically when changes are made to it, but there are solutions to that out there already).


text:
Q: Infinite loop scala code object Prop {
  def simplify(prop : Prop) : Prop = {
    prop match {
      case Not(Or(a,b)) => simplify(And(Not(a),Not(b)))
      case Not(And(a,b)) => simplify(Or(Not(a),Not(b)))
      case Not(Not(a)) => simplify(a)
      case _ => {
        if (simplify(prop) == prop) prop
        else prop
      }
    }
  }
}

I'm pretty sure I've an infinite loop caused by my 'default' case. I'm using recursion in all cases. Which is meant to be, but, only if the Prop can be simplified. As soon as the Prop can't be simplified, it should return the whole thing.
I don't see how I can test for any further simplification. (I'm not allowed to use other libraries, as suggested in freenodes #scala channel).
Can someone explain whether it IS the 'case _' causing the loop, and how to solve it? How can I test for possible simplification without making a loop?
Thanks in advance!

A: It is pretty obvious what happens and you are right with the default case. If your input prop does not match any of the cases you are invoking:
simplify(prop)

with the same argument. Because previously it caused recursive call to simplify() and you are calling your function with the same input, it enters simplify() again. So this is not an infinite loop but rather never terminated recursive call:
...simplify(simplify(simplify(simplify(simplify(simplify(simplify(prop)))))))

However the fix (based on your code) is simple:
if (simplify(prop) == prop) prop
    else prop

just replace it with...
 case _ => prop

Both branches return the same value. This is actually correct if you think about if for a while. You have a set of optimizations. If none of them matched your expressions it means it can no longer be simplified. Hence you are returning it as-is.
BTW looks like you are doing boolean expressions simplification using case classes. You might by interested in my article where I do the same but with arithmetic expressions.

A: The problem is that you're trying to do two things in one step that need to happen in sequence—applying De Morgan's law (and removing double negation) and recursively simplifying any children. This is why just dropping a case And(a, b) => And(simplify(a), simplify(b)) into your match won't work.
Try the following:
val deMorganAndDoubleNegation: Prop => Prop = {
  case Not(Or(a, b)) => And(Not(a), Not(b))
  case Not(And(a, b)) => Or(Not(a), Not(b))
  case Not(Not(a)) => a
  case a => a
}

val simplify: Prop => Prop = deMorganAndDoubleNegation andThen {
  case And(a, b) => And(simplify(a), simplify(b))
  case Or(a, b) => Or(simplify(a), simplify(b))
  case Not(a) => Not(simplify(a))
  case a => a
}

A: Yes, default case is causing the loop.
if (simplify(prop) == prop) prop is problematic line.
You don't need to test if it can be simplified further because when you are in the default case all possible simplifications are tried.


text:
Q: counter example of equicontinuous Consider the functions on $[0,1]$:
$f_n(x)=nx$, when $x$ is between $0$ and $1/n$
$f_n(x)=2-nx$, when $x$ is between $1/n$ and $2/n$
$f_n(x)=0$, otherwise
How to see it is not (uniformly) equicontinuous?
I checked $0$. For $\epsilon$=$1/2$, no matter how small the neighborhood around $0$ we pick, we can choose a $N$ large enough s.t. $1/N$ < $\delta$. So for $n> N$ , we will have some $x$=$1/n$, which satisfies $|x- 0|$ < $1/N$< $\delta$, but makes $|f_n(x)-0|$= $1$, instead of smaller than $1/2$.
Is it correct?

A: Your answer looks perfectly fine.

A: The idea is fine, but you may want to make the formalism a bit more rigorous:
Let $1 > \epsilon > 0$. We must show that $\forall\delta > 0 \exists x\in[0,1], N\in\mathbb N$ such that $|x|<\delta$ but $|f_N(x)| > \epsilon$.
For this pick $N = \lceil \frac1\delta \rceil
+1$ and $x = \frac1N < \delta$. Then $|f_N(x)| = 1 > \epsilon$ as claimed. Therefor $(f_n)_n$ is not equicontinuous.


text:
Q: Unresolved reference: animateColorAsState I'm trying to understand Android Compose Animation and I get this error
import androidx.compose.animation.animateColorAsState
...

val backgroundColor by animateColorAsState(if (isSelected) Color.Red else Color.Transparent)

Android Studio highlights animateColorAsState in red and writes " Unresolved reference: animateColorAsState"

A: Make sure you are using the correct "Color": below is an example
// notice the androidx.comose.ui.graphics.Color and MaterialTheme.colors (which returns androidx.comose.ui.graphics.Color)
val surfaceColor: androidx.compose.ui.graphics.Color by animateColorAsState(
   if (isExpanded) MaterialTheme.colors.primary else MaterialTheme.colors.surface
)

In your example, I think you are using incorrect "Color". You should check your import on if you are using:
import androidx.compose.ui.graphics.Color // <--- Correct one
// and NOT below
import android.graphics.Color // <--- Incorrect one

A: The name has changed to animateAsState


text:
Q: avoid sorting in X axis in matplotlib and plot common X axis with multiple y axis I wish to clarify two queries in this post.
I have a pandas df like below picture.

1. Plotting problem : .
When i try to plot column 0 with column 1, the values gets sorted.
example : in col_0 I have values starting from 112 till 0.
the values gets sorted in ascending order and the graph shows reversed X axis plot when i use the below code.
plt.plot(df.col_0, df.col_1)

What will be best way to avoid sorting X axis values. ?
2. All paramaters in single graph
I would like to plot all the params in a single plot. Except X axis all other params values are between 0 to 1 (same scale)
What will be best pythonic way of doing.
Any help would be appreciated.

A: I don't understand what you mean by they get sorted - does it not plot 112, 0.90178 and connect it to 110.89899, 0.90779, etc?
To share the X axis but have 2 Y axes that certain sets are plotted on, use twinx
fig, ax1 = plt.subplots()
ax1.plot(df.col_0, df.col_1)
ax2 = ax1.twinx()
ax2.plot(df.col_0, df.col_2)

re: how to plot in the order you want
I believe your intention is to actually plot these values vs. time or index. To that end, I suggest:
fig, ax1 = plt.subplots()
ax1.plot(df['Time'], df.col_0) # or df.index, df.col_0
ax2 = ax1.twinx()
ax2.plot(df['Time'], df.col_1)

A: Try to draw the series/dataframe against the index:
col_to_draw = [col for col in df.columns if col!='col0']

# if your data frame is indexed as 0,1,2,... ignore this step
tmp_df = df.reset_index()

ax = tmp_df[col_to_draw].plot(figsize=(10,6))
xtick_vals = ax.get_xticks()
ax.set_xticklabels(tmp_df.col0[xtick_vals].tolist())

Output:


text:
Q: Supervisord on linux CentOS 7 only works when run with root I am trying to run a process in the background as a deamon but it only works when I use root as user.
This is what I did.
Installed supervisor as told on their website
$ yum -y install python-setuptools

$ easy_install supervisor

created the config folders
$ mkdir -p /etc/supervisor/conf.d

populate with default settings
$ echo_supervisord_conf > /etc/supervisor/supervisord.conf

add a new user
$ useradd gogopher

on CentOS 7 to make it start automatically I had to do this
$ vim /usr/lib/systemd/system/supervisord.service

added the code below
[Unit]
Description=supervisord - Supervisor process control system for UNIX
Documentation=http://supervisord.org
After=network.target

[Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisor/supervisord.conf
ExecReload=/usr/bin/supervisorctl reload
ExecStop=/usr/bin/supervisorctl shutdown
User=gogopher

[Install]
WantedBy=multi-user.target

now I can enable it so that it starts on reboot. this all works fine.
$ systemctl enable supervisord

$ systemctl start supervisord

$ systemctl status supervisord

OK
editing the config file to include files from conf.d folder
$ vim /etc/supervisor/supervisord.conf

adding at the end of file
[include]
files = /etc/supervisor/conf.d/*.conf

adding a simple program
$ vim /etc/supervisor/conf.d/goapp.conf

[program:main]
command=/srv/www/websiteurl.com/bin/main
autostart=true
autorestart=true
startretries=10
user=gogopher

$ systemctl restart supervisord
no error, but the process does not work
if I reboot nothing happens
$ systemctl status supervisord

shows that it supervisord is running but not the daemon program.
if I run
$ supervisorctl reload

I get the error
error: <class 'socket.error'>, [Errno 111] Connection refused: file: /usr/lib64/python2.7/socket.py line: 571

if I run
$ supervisorctl status main

I get the error
http://localhost:9001 refused connection

I have already disabled selinux.
but the weird part is that if I change both of them to root, it works.
The executable is able to be executed by user group and others.
So I have no idea what is going on. I have heard that I should not use
root as user that is running a webserver for security reasons.

A: For all the people out there having the same problem, this works for me.
cd
echo_supervisord_conf > /etc/supervisord.conf
# content of /etc/supervisord.conf ...

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL  for a unix socket

[inet_http_server] ; inet (TCP) server disabled by default
port=*:9001        ; (ip_address:port specifier, *:port for all iface) - I had all this wrong from my original config.
username=user
password=passwd

Paste this content into /etc/rc.d/init.d/supervisord ( I´m not the owner of this script, by now i don´t remember where i got it from )
#!/bin/sh
#
# /etc/rc.d/init.d/supervisord
#
# Supervisor is a client/server system that
# allows its users to monitor and control a
# number of processes on UNIX-like operating
# systems.
#
# chkconfig: - 64 36
# description: Supervisor Server
# processname: supervisord

# Source init functions
. /etc/rc.d/init.d/functions

prog="supervisord"

prefix="/usr/local/"
exec_prefix="${prefix}"
prog_bin="${exec_prefix}/bin/supervisord -c /etc/supervisord.conf"
PIDFILE="/var/run/$prog.pid"

start()
{
       echo -n $"Starting $prog: "
       daemon $prog_bin --pidfile $PIDFILE
       sleep 1
       [ -f $PIDFILE ] && success $"$prog startup" || failure $"$prog startup"
       echo
}

stop()
{
       echo -n $"Shutting down $prog: "
       [ -f $PIDFILE ] && sleep 1 && killproc $prog || success $"$prog shutdown"
       echo
}

case "$1" in

 start)
   start
 ;;

 stop)
   stop
 ;;

 status)
       status $prog
 ;;

 restart)
   stop
   start
 ;;

 *)
   echo "Usage: $0 {start|stop|restart|status}"
 ;;

esac

Make the script executable and register it as a service
sudo chmod +x /etc/rc.d/init.d/supervisord
sudo chkconfig --add supervisord
sudo chkconfig supervisord on

# Start the service
sudo service supervisord start

# Stop the service
sudo service supervisord stop

# Restart the service
sudo service supervisord restart


text:
Q: Java JXLS API ForEach I am using JXLS API for generating Excel reports. I am trying to achieve nested loops in such a way that I want to iterate FIRST column-wise the array of OuterObjects, where each OuterObject has an array for InternalObject, and then iterate SECOND row-wise the array of InternalObjects. Below is the template Expression Language used: requirement
| <jx:forEach items="teams" var="team"> | <jx:forEach items="team.employees" var="employee"> | </jx:forEach> |

|                                       | ${employee.leaveDates}                             |               |
|                                       | </jx:forEach>                                      |               |

Assuming I have m teams and each team has n employees, my excel should be m x n table. However, using the above template I'm able to achieve only 1 x 1 table.
Can anyone help me to correct my Expression Language?


text:
Q: Should I build a TCP server or use simple http messages for a back-end? I am building a back end that will handle requests from web apps and mobile device apps.
I am trying to decide if an TCP server is appropriate for this vs. Regular http GET and POST requests.
Use case 1:
1. Client on mobile device executes a search on the device for the word "red".

*

*Word sent to server (unclear wether JSON or TCP somehow)

*The word red goes to the server and the server pulls all rows from a mysql db that have red as their color (this could be ~5000 results).
Alternate step 2 (maybe TCP should make more sense here):  there is a hashmap built with the word red as the key and the value a pointer to an array of all the objects with the word red (I think this will be a faster look up time).

*Data is sent to the phone (either JSON or some other way, not sure). I am unclear on this step.

*The phone parses, etc...
There is a possibility that I may want to keep the array alive on the server until the user finishes the query (since they could continue to filter down results).
Based on this example, what is the architecture I should be looking at?
Any different way is highly appreciated.
Thank you

A: In your case I would use the HTTP because:

*

*Your service is stateless.

*If you use TCP you will have problem scaling up your service (since every request will be directed to the server that establish the TCP connection ), this relate to that your service is stateless. In HTTP you just add more servers behind load balane

*For TCP you will need to state some port which can be block due to firewall and ect' - you can use port 80/8080 but I don't think this is good practice

*if you service were more like suggestion that change as the use typein his word you may want to use TCP/HTTP Socket

*TCP is used for more long term connection - like Security system that report the state of the system every X seconds - which is not the case


text:
Q: Identify Ctrl+Click event in a Kivy application I am writing a Kivy application where I want to select a Region Of Interest (ROI) on a scatter image widget. I want to identify when the user presses CTRL+Left Click and then draw a rectangle over the image. Is it possible from within the on_touch_down callback to identify that the user is holding the CTRL button?
Thanks,
Amit


text:
Q: Необходимо проверить txt файл на совпадение цифр. Python Есть файл user.txt в нем содержится набор цифр:

*

*111

*222

*333

*444

*555

Нужно следующее: Пользователь вводит число, к примеру 333, если число 333 содержатся в файле user.txt то оно его не записывает, а если такого числа нет? он его записывает в конец строки.
Вот код который пытался написать, но он не правильный.
 number(chislo)
 f = open("user.txt", 'a+')
 if f == number:
    f.close()
 else:
    f.write(number) + '\n')

A: Можно как-то так, если учитывать, что все ваши числа разделены пробелами или записаны с новой строчки:
with open("test.txt", mode="r+") as f:
    text = f.read()
    numbers_list = [int(x) for x in text.split()]
    num = int(input("Вводим искомое число: "))
    if num in numbers_list:
        print("Такое число есть")
    else:
        print("Такого числа нет, записываю")
        f.write(' ' + f"{num}")  # или ('\n' + f"{num}"), если каждое число с новой строки необходимо записать


text:
Q: Prevent Spring from creating new session if authentication fails With the folowing code a new WebSession is created each time someone accesses my site. The state of the WebSession is set to NEW containing no attributes. This session is never deleted for some reason.
  @Bean
  public SecurityWebFilterChain securityWebFilterChainCatchAll(ServerHttpSecurity http) {
    return http
        .csrf().disable()
        .authorizeExchange()
        .pathMatchers("/", "/static/**")
        .permitAll()
        .anyExchange()
        .denyAll()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(this::returnPage)
        .accessDeniedHandler(this::returnPage)
        .and()
        .formLogin().disable()
        .httpBasic().disable()
        .build();
  }

  private Mono<Void> returnPage(ServerWebExchange exchange, RuntimeException denied) {
    Resource indexHtml = new ClassPathResource("/static/index.html");
    return ok().contentType(MediaType.TEXT_HTML).syncBody(indexHtml).flatMap(d -> d.writeTo(exchange, new HandlerStrategiesResponseContext(HandlerStrategies.withDefaults())));
  }

class HandlerStrategiesResponseContext implements ServerResponse.Context
{
  private final HandlerStrategies strategies;

  HandlerStrategiesResponseContext(HandlerStrategies strategies) {
    this.strategies = strategies;
  }

  @Override
  public List<HttpMessageWriter<?>> messageWriters() {
    return this.strategies.messageWriters();
  }

  @Override
  public List<ViewResolver> viewResolvers() {
    return this.strategies.viewResolvers();
  }
}

This is a catchall ServerHttpSecurity I have more specific configuration for my /api endpoint but they are working as expected when the WebSession is set in STARTED state and the attribute of SPRING_SECURITY_CONTEXT.
I have two questions regarding this.

*

*What does it mean for WebSession to be in NEW state and why is that
not deleted, only STARTED state is deleted.

*What do I need to change to either not creating any session or make sure the sessions created are deleted when expired.


text:
Q: How to edit Azure App Service using Azure Python SDK? I'm following the example here https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-example-web-app?tabs=cmd#4-write-code-to-provision-and-deploy-a-web-app trying to update an existing App Service using the Python SDK.
Here is my code
from azure.mgmt.web import WebSiteManagementClient
from azure.common.client_factory import get_client_from_cli_profile
import os

def insert_access_restriction():
    rg_name = os.environ.get('RESOURCE_GROUP_NAME', None)
    location = os.environ.get('LOCATION', None)
    sp_name = os.environ.get('SERVICE_PLAN_NAME', None)
    web_app_name = os.environ.get('WEB_APP_NAME', None)
    sub_id = os.environ.get('AZURE_SUBSCRIPTION_ID', None)

    app_service_client = get_client_from_cli_profile(WebSiteManagementClient)
    poller = app_service_client.app_service_plans.create_or_update(rg_name,
        sp_name,
        {
            "location": location,
            "reserved": True,
            "sku" : {"name" : "S1"}
        }
    )
    plan_result = poller.result()

    poller = app_service_client.web_apps.create_or_update(rg_name,
        web_app_name,
        {
            "location": location,
            "server_farm_id": plan_result.id,
            "site_config": {
                "ip_restriction": {
                    "ip_address": "3.3.3.3/32"
                },
                "ip_restriction": {
                    "ip_address": "4.4.4.4/32"
                }
            }
        }
    )

The call to this function app_service_client.app_service_plans.create_or_update returns

azure.mgmt.web.v2019_08_01.models._models_py3.DefaultErrorResponseException:
Operation returned an invalid status code 'Bad Request'

My location is centralus. The goal of this program is to update the ip restrictions on an existing app service programmatically from a Function App when a new list of ip addresses is added to a storage container. The error is very vague, how do I get an existing app service plan, its app service, and then update the app service using the Python SDK?

A: if you want to update the ip restrictions settings on an existing app service with python sdk, please refer to the following code

*

*Create a service principal and assign Contributor to the sp

az login
# create sp and assign Contributor role to the sp at subscription level
az ad sp create-for-rbac -n "MyApp"

*Code

client_id = 'your sp appId'
secret = 'your sp password'
tenant = 'your sp tenant'
credentials = ServicePrincipalCredentials(
        client_id = client_id,
        secret = secret,
        tenant = tenant
)

Subscription_Id = ''

web_client=WebSiteManagementClient(
    credentials,
    Subscription_Id
)
resorurce_group_name='your appservice group name'
name='you appservice name'

web_client.web_apps.create_or_update_configuration(resorurce_group_name, name,{

    'ip_security_restrictions':[

        {
            'ip_address': "0.0.0.0/0",
            'action': "Allow",
            'priority': 30,
            'name': "test"
        }
    ]
})

for more details, please refer to here and here

#Update
If you want to run the script in Azure function, please refer to the following steps.

*

*Create Azure function

*Enable Azure MSI for Azure Function

*Assign role fro the MSI

*code (I use HTTP trigger to get web app configuration)
import logging
import pyodbc
import json
import azure.functions as func
from msrestazure.azure_active_directory import MSIAuthentication
from azure.mgmt.web import WebSiteManagementClient

async def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    creds =MSIAuthentication()
    Subscription_Id = 'e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68'
    group_name='0730BowmanWindowAndLinux2'
    name='413Bowman'

    web_client=WebSiteManagementClient(
        creds,
        Subscription_Id
    )
    result =web_client.web_apps.get_configuration(group_name, name,raw=True)
    return func.HttpResponse(json.dumps(result.response.json()))


text:
Q: When coin 1 is flipped, it lands on heads with probability .4; when coin 2 is flipped, it lands on heads with probability .7. When coin 1 is flipped, it lands on heads with probability .4; when coin 2 is flipped, it lands on heads with probability .7. One of these coins is randomly chosen and flipped 10 times.
(a) What is the probability that the coin lands on heads on exactly 7 of the 10 flips?
(b) Given that the first of these 10 flips lands heads, what is the conditional probability that exactly 7 of the 10 flips land on heads?
I know how to to do by finding the probability of coin 1 being chosen then finding the probability it gets exactly 7 heads by using a bernoulli sum and adding that probability to the probability of coin 2 being chosen and doing another bernoulli sum for that coin, but is there a better or more efficient way of calculating the probability of part a instead of doing it the long way like I did?
and part b does not make sense to me because if it's given that the first 10 flips are heads how can you find the probability that exactly 7 of the 10 landed on heads if it's given that they all landed on heads?

A: As stressed in the comments, the extra information available in part b) is that fact that the first toss gives you Heads. Conceptually, the problem is "how do you use the new information?".  Informally, the fact that you see $H$ on the first trial increases the probability that you have coin #$2$.  But by how much?
To answer that, suppose you toss each coin ten times.  You'll see $4$ Heads from coin #$1$ and $7$ from coin #$2$. Thus you'll see $11$ Head all in all, $7$ of which come from coin #$2$.  Thus, if all you are told was that you saw Heads, the probability that it came from coin #2 is $\frac 7{11}$.
Accordingly, you can now redo part a), looking for exactly $6$ Heads out of the next $9$ tosses where you have coin #$1$ with probability $\frac 4{11}$ and coin #$2$ with probability $\frac 7{11}$.

A: for question a)
Do some conditionnal expectation

P being the probability of your event
P is a random variable that you have no idea what it is.

However

P knowing What coin you are using is a known distribution

Therefore

P | Coin one ~ binomial(10, 0.4) => P(binomial(10, 0.4) = 7)
+
P | Coin two ~ binomial(10, 0.7) => P(binomial(10, 0.7) = 7)

and since you have 1/2 of picking either one coin, the expected value of P is the sum of the two previous probability, each one multiplied by 1/2 :)
for question b)
you have to re-ponder the 1/2 of my previous question since you have new information about which coin was selected.
Since it went on head, it means that the probabiltiy of having the first coin selected is smaller than the probability of second one. from that point i believe your text book will let you know what formula to use :)

A: a) Denote X to be the number of heads observed. If coin 1 is chosen, X~Bin(n,0.4) and if coin 2 is chosen X~Bin(n,0.7). Each coin is chosen randomly, implying there is 0.5 chance of picking coin 1 or coin 2. Hence we need to multiply the 2 probabilities by 0.5 and add them together to get the expected value.
P(X=7) = P(Coin 1 and X=7) OR P(Coin 2 and X=7)
P(X=7) = (0.5)(10C7)(0.4^7)(0.6^3) + (0.5)(10C7)(0.7^7)(0.7^3) = 0.1548
b)P(X=7|First is head) = P(X=7 AND First is head)/ P(First is head)
 =((0.5)(9C6)(0.4^6)(0.6^3) + (0.5)(9C6)(0.7^6)(0.7^3))/((0.5)(0.4) + (0.5)(0.7))

=0.310

A: The answer to number (b) is correct except that Uvin from above missed to multiply the equation with .7 and .4. I've edited the solution below:
=((0.5)(0.4)(9C6)(0.4^6)(0.6^3) + (0.5)(0.7)(9C6)(0.7^6)(0.7^3))/((0.5)(0.4) + (0.5)(0.7))
Because you must multiply the probability of getting a Head on both the events.


text:
Q: Drop Down list is not working to change between values I've created this dropdown menu to switch between charts based on URL of that chart, but it is not working on either in VS code or on my site !
basically, I want to change the chart when I select the other country from dropdown menu
Here is my code:

function switchVis(chartId) {
  document.querySelector('iframe').src = 'https://datawrapper.dwcdn.net/' + chartId;
}

Select country

<select onchange="switchVis(this.value)">
  <option value="SRbHj/4/">Belguim</option>
  <option value="BGQvN/4/">Austria</option>
</select>


text:
Q: Nvidia GT218 repository drivers don't work I upgraded all packages with sudo apt-get upgrade command on my Ubuntu 10.04 box and I have Ubuntu 12.04 3.2.0-29-generic-pae now. I have two monitors and the following GPU:
01:00.0 VGA compatible controller: NVIDIA Corporation GT218 [NVS 300] (rev a2)

After upgrading to 12.04, I somehow lost my previous setup with one common workspace stretched across two monitors. When Ubuntu starts only one monitor is on. I can see the message on the active monitor:
Not optimum mode. Recommended mode: 1680x1050 60Hz

I used Nvidia proprietary drivers on 10.04 but now jockey-text --list shows:
xorg:nvidia_current - NVIDIA accelerated graphics driver (Proprietary, Disabled, Not in use)
xorg:nvidia_current_updates - NVIDIA accelerated graphics driver (post-release updates) (Proprietary, Enabled, Not in use)

When I run sudo nvidia-settings it says
You do not appear to be using the NVIDIA X driver.  Please edit your X configuration file (just run `nvidia-xconfig` as root), and restart the X server.'

I typed nvidia-xconfig and rebooted, but jockey-text --list says the same after the reboot: Not in use. The same with nvidia-current - Enabled but Not in use. I also tried nvidia-173 but I ended up in tty immediately at startup so I removed it.
I used to have some problems with Nvidia proprietary drivers on 10.04, I had to put paths to EDID files in /etc/X11/xorg.conf explicitly, but the resolution was as recommended and both monitors were working.
If I understand correctly, nouveau drivers are used now by default because the resolution is still quite high, definitely not 800x600, xrandr showed:
xrandr: Failed to get size of gamma for output default
Screen 0: minimum 320 x 400, current 1600 x 1200, maximum 1600 x 1200
default connected 1600x1200+0+0 0mm x 0mm
   1600x1200      66.0*
   1280x1024      76.0
   1024x768       76.0
   800x600        73.0
   640x480        73.0
   640x400         0.0
   320x400         0.0
  1680x1050_60.00 (0x4f)  146.2MHz
        h: width  1680 start 1784 end 1960 total 2240 skew    0 clock   65.3KHz
        v: height 1050 start 1053 end 1059 total 1089           clock   60.0Hz

However, colors seem a bit faded and blurry with nouveau drivers. Mouse cursor is invisible if it's placed inside Firefox window, and only one monitor is working. I like open source and if it's possible I'd prefer to use nouveau drivers but a few things should be fixed. I'm curious why nvidia-current drivers from the repository don't work now. I read it has something to do with the new X11 server in Ubuntu 12.04, is it true? How can I get it back to work?

A: You could try upgrading the Nvidia blob drivers to the newest release.  You can find the PPA at the:
X-Swat PPA


text:
Q: ASsign IJavaScriptExecutor executescript result to local variable Is it possible to assign value from IJavaScriptExecutor to specific local variable?
IWebElement element= getelement(rowNumber);
IJavaScriptExecutor js = (IJavaScriptExecutor)Utility.Driver;
js.ExecuteScript("ko.dataFor(arguments[0]).Title()", element);

result of this js is a string. I want to assign that string to specific variable and return it as a result of a method.
Is there any way to do it.
I have tried
text=js.ExecuteScript("ko.dataFor(arguments[0]).Title()", element).ToString();

but it is obvious why that cannot work.
Any other way?

A: Try adding a return in your JavaScript code.
text=js.ExecuteScript("return ko.dataFor(arguments[0]).Title()", element).ToString();


text:
Q: Casting to a Subclass When I do this:
Animal dog = new Dog();

where Dog is a subclass of Animal, is the fact that the object is actually a Dog type ever exposed to the system, or is it lost forever? This question pertains to Java and C# because I assume they are similar, but for clarity let's focus on C#.
Based on my knowledge, I'd assume that the object would forever be considered an Animal object. The properties and methods of Dog would be assigned to the object instance but we would never know it was instantiated from a Dog class.

A: In Java you can check whether dog is instance of Dog using instanceof:
if (dog instanceof Dog) ...

A: in C# you can check wheter dog is instance of Dog using is:
if(dog is Dog) ...

or using as:
var dog = animal as Dog;
if( dog != null )
    dog.Bark();

A: You will get access to Dog's proerties/methods by casting instance of Animal to Dog
Animal dog = new Dog();

// then somewhere
var dogDog = (Dog)dog;

In case you not sure is it Dog or not - use "soft" casting
var mayBeDog = animal as Dog;
if (maybeDog != null)
{
    // is Dog
}
else
{
    // wasn't Dog
}

Another question - do we need to care about what is concrete type of Animal?
If you care about - then you shouldn't use inheritance in this case
Assume you have a method which takes Animal as parameter, that mean that you should be able pass any derived class of Animal and your method will work in expected manner.


text:
Q: Prevent modal in hiding scrollbar in materializecss Whenever I open a modal from Materializecss, the scrollbar (my body has inline scrollbar) hides everytime. What should I do so that whenever I open a modal, the body's scrollbar will remain?

  warning

 Are you sure you want to block this guest?

 Confirm

    Cancel

Screenshot before opening a modal
Screenshot when a modal opens. Look at the scrollbar it was removed. And I don't like that because the screen always move.

A: for me, it worked by putting it that way in the css.
body {
   overflow: scroll !important
}


text:
Q: Destructor call for a vector in c++ #include <iostream>
#include <vector>

using namespace std;

class A
{
    public:
         A(){cout<<"A Contruction"<<endl;}
        ~A(){cout<<"A destruction"<<endl;}
};

int main()
{
    vector<A> t;
    A a;
    A b;
    t.push_back(a);
    t.push_back(b);
    return 0;
}

Output:
A Contruction
A Contruction
A destruction
A destruction
A destruction
A destruction
A destruction

Am unable to understand the destruction call.
First 2 destruction are for copy constructor being called in vector.

A: The other three destructions are from objects that get copy and/or move-constructed.
The two calls to push_back will effectively copy-construct a copy of the parameter object in the container itself.
The 2nd call to push_back appears to reallocate the vector, and the sole object in the vector, thus copy-constructing it as well, and then destroying the original object.
Add a copy-constructor to your class, to log the invocations of the copy constructor.
P.S. Actually, if you were to dig into this, it's the 2nd and the third "A destruction" message that log the destruction of your a and b objects. The first "A destruction" message is due to the vector reallocation.


text:
Q: Is there a preferred way for creating a draw feature in a browser? I want to be able to draw circles on picture at a mouseclick or touch on a display. I also want to remove given circles if they're clicked/touched again. I know how to check if a given coordinate is within a circle. The problem is that I don't know the best approach to this task. Atm I'm using HTML5 canvas to draw circles with the .stroke() function, but I don't know how to "store" these circles so I can remove them if the'yre clicked/touched again. Is there a better solution than canvas available, or am I even approaching the problem the right way?

A: This is a solution based on SVG instead of canvas. There is a benefit you might consider: it is easy to store and retrieve, as it is self-describing.

makeSVG = (tag, attrs) => {
    let el = document.createElementNS('http://www.w3.org/2000/svg', tag);
    for (var k in attrs) el.setAttribute(k, attrs[k]);
    return el;
}

$(() => {
  let $svg = $('svg')

  $('svg image').on('click', e => {
    let x = e.pageX - $svg.offset().left;
    let y = e.pageY - $svg.offset().top;

    var circle= makeSVG('circle', {cx: x, cy: y, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});

    $svg.append(circle);
  })

  $('svg').on('click', 'circle', e => {
    $(e.currentTarget).remove()
  })
})
html, body {
  padding:0;
  margin:0;
  height:100%;
  width:100%;
  position: relative;
}

svg {
  height:100%;
  width:100%;
  border: 1px solid red;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <image xlink:href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" height="100%" width="100%"/>
</svg>


text:
Q: Boxplot involving qualitative and quantitative variables I'm using "d.pizza" data. Among others, there is variable called "delivery_min" which is delivery time in minutes. The other variable is variable called "area" which can be one of three areas (Camden, Westminster
and Brent). I want to do boxplot, which compares delivery time in different areas.
I tried
boxplot(pizza_d~area", data = pizza_d$"delivery_min")

or subset(pizza_d, pizza_d$"area" == "Brent","pizza_d$"delivery_min"")
but it's not working
can I use "which" function in boxplot?

A: Have you tried this?
library(DescTools)

data(d.pizza)

boxplot(delivery_min ~ area, data=d.pizza)


text:
Q: FMX: Strange glitch with TCanvas.DrawPath. Why? I draw a path consisting of 2 lines going up and then back down to the same spot, or almost the same spot, but the first line is drawn too high. If I then draw the same lines using DrawLine I don't see the issue. Why is this happening?
Below is an example. Just drop a 400x400 TImage on a blank multiplatform form. The code draws 2 red paths, one with close to a 180 degree angle between the lines and one with less of an angle. The same lines are then drawn using DrawLine in blue. If the DrawPath function works correctly then the blue lines should completely cover the red lines, but they don't. In this example with a scale of 1.5 the path extends 7 pixels too high for the first path. The extent of the error reduces as the lines get further apart. The issue still happens with a scale of 1, but is less obvious.
procedure TForm1.FormActivate(Sender: TObject);
var
  LPath1, LPath2 : TPathData;
  i : Integer;
begin
  // A path of 2 lines going up and then back down to almost the same spot
  LPath1 := TPathData.Create;
  LPath1.MoveTo(PointF(100,200));
  LPath1.LineTo(PointF(100,50 ));
  LPath1.LineTo(PointF(105,200));
  // A path of 2 lines going up and then back down at a wider angle
  LPath2 := TPathData.Create;
  LPath2.MoveTo(PointF(200,200));
  LPath2.LineTo(PointF(200,50 ));
  LPath2.LineTo(PointF(260,200));
  Image1.Bitmap.BitmapScale := 1.5; // The issue shows up more at larger scales
  Image1.Bitmap.SetSize(Trunc(Image1.Width), Trunc(Image1.Height));
  with Image1.Bitmap.Canvas do if BeginScene then begin
    Clear(TAlphaColorRec.White);

    // Draw the paths using DrawPath in red
    Stroke.Color := TAlphaColorRec.Red;
    Stroke.Thickness := 1;
    DrawPath(LPath1, 1);
    DrawPath(LPath2, 1);

    // Draw the paths using DrawLine in blue over the top
    // The red lines should be completely hidden under the blue
    Stroke.Color := TAlphaColorRec.Blue;
    for i := 1 to LPath1.Count - 1 do
      DrawLine(LPath1.Points[i-1].Point, LPath1.Points[i].Point, 1);
    for i := 1 to LPath2.Count - 1 do
      DrawLine(LPath2.Points[i-1].Point, LPath2.Points[i].Point, 1);

    EndScene;
  end;
  LPath1.Free;
  LPath2.Free;

  Image1.Bitmap.SaveToFile('test.png');
end;

Result of the code when run in Windows 10. I'm using Delphi 11, but the same issue happens with Delphi 10. I've tried switching GPU but the same issue occurs.

Enlarged view:

A: I've come to the conclusion that this isn't a glitch at all. It's because the default setting of TCanvas.Stroke.Join is TStrokeJoin.Miter. The artefact seen is just the sharp spike of the mitred corner. Using MoveTo before each line segment when constructing the path does solve the issue (because there's no join between the separate line segments) but so does setting the TCanvas.Stroke.Join parameter to TStrokeJoin.Round or TStrokeJoin.Bevel.
Note that at very sharp angles approaching 180 degrees, the miter join would become infinite. However, it appears to be limited somehow, perhaps in proportion to the stroke thickness. I don't think there's a way to change this miter limit in delphi.

A: This is because by default TPath is making smooth transitions between different path segments. I'm guessing it might be using Quadratic interpolation for making these smooth transitions.
Yes making smooth transition between two lines doesn't seem logical but it looks this is how it is implemented.
Now you can avoid this by telling the TPath that your two lines are not connected and thus should be treated as two separate lines even thou in reality they are connected. And you can do this by simply calling Path.MoveTo which is intended to shift position so you can create another unconnected line that dos not continue from your last path point.
Here is how modified code for your first sharp cornered line would look like:
NOTE that I'm specifying the exact same position for MoveTo command that was used for rendering of previous path line since you don't want the new line to start at new position.
// A path of 2 lines going up and then back down to almost the same spot
  LPath1 := TPathData.Create;
  LPath1.MoveTo(PointF(100,200));
  LPath1.LineTo(PointF(100,50 ));
  //Add move to command to prevent Path from trying to make smooth transitions between two lines
  LPath1.MoveTo(PointF(100,50));
  LPath1.LineTo(PointF(105,200));


text:
Q: isn't intel hd graphics supposed to have directx 11 feature level 11? I have intel HD graphics on my laptop, but every time I try t run a game (valorant and others), it keeps saying:
A D3D11 compatible GPU (feature level 11, shader mode 5.0) is required to run this engine.
According to  Tech power up intel HD graphics have direct x 11 (feature level 11, shader mode 5.0). I ran dxdiag command, and my system shows I have DirectX 11, but the feature level is 10_1. isn't it supposed to have feature level 11 with me having intel HD graphics? or it's just my graphics card got some problems? could you please read the info below and give me a solution? I ran some Windows updates and downloaded DirectX 11 from the ms store (ig). what should I do?

A: That's not your HD Graphics - there were multiple versions released under the same name. Your CPU was released in 2011, two years before that version of HD Graphics.

A: Make sure you are running Windows 10 and the latest Feature pack (19044.1949) or Windows 11 on a machine compatible with Windows 11 (and so Windows 10 as well)>
Direct X for those two above is DirectX12 and then that should probably solve your problem.
Make sure also that you have updated your Video Driver and Chipset.  Use the Manufacturer's Driver Update App to do these updates.
Making sure your hardware supports DX12 will be ideal for you.


text:
Q: Google Maps API and bandwidth consumption I have a site that uses 2 Google Maps APIs.
https://maps.googleapis.com/maps/api/js

and
https://maps.googleapis.com/maps/api/geocode/json

This "mapper" site communicates with 2 Google Maps APIs, geolocates the user, and extracts data from a MySQL database to display markers in a Google Map around the user.
The site was hosted on Digital Ocean / DigitalOcean. A few days after the site was up Digital Ocean claimed that my site was doing a DDOS attack and took it offline.
It's all original code I wrote and there's nothing malicious in the code.
When I put the site up a second time, a few days later Digital Ocean took it offline again, this time claiming it was "too active" and "disrupting traffic."
I do have the cheapest plan ($5 a month), but their the sign-up process doesn't contain anything explicit and obvious about data transfer caps.
Apparently, Google Maps API queries do something to make your site "too active" and "disrupt traffic". When comparing hosting plans and services, what kinds of features should I focus on to evaluate a host that is better suited for this "mapper" website's needs?

A: It's likely less about the traffic that it is creating and more about the server load it's creating. Without seeing the code, I can't be of much help but I'd look into how often you are polling and things like that. Try putting it in a VM and seeing what kind of performance impact it's having on the system.


text:
Q: writing a function in bash profile, calling from terminal I'm new to linux and working in the terminal, and wrote a function to see if I'm on the company network or not
function isCompanyNetwork() {
  if [[ $(ipconfig getifaddr en0) == 3.* ]] || [[ $(ipconfig getifaddr en1) == 3.* ]] ;
 then
   echo yes
 else
   echo no
 fi
}

however, when i type the following in my terminal: isCompanyNetwork
I get:
-bash: isCompanyNetwork: command not found
what am I doing wrong?

A: Add this function to your ~/.bashrc
I'm guessing you wrote this in a file?  If it's .bash_profile or .bashrc, you need to relog in or source the files (i.e. . ~/.bash_profile).  If you did this at the command line and haven't logged out, you can see your defined fuctions by typing declare -F.  Make sure isCompanyNetwork is there, or you did something wrong (created it in another window?).


text:
Q: Is it possible to ad custom block areas through Customizer that would allow adding Gutenberg blocks? Is it fundamentally possible to create a custom area through Customizer that would allow adding Gutenberg blocks. Similar to a widget area but one that can be managed through Customizer panes and allow for Gutenberg blocks instead of widgets.
The user case I am thinking of is have the ability to add CTA buttons, and icon links to the site navbar area within a custom theme. I am aware I can ad a new sidebar and add widgets to it which would render in my navbar, however I hate the contextual disconnect of adding a "sidebar" that is not an actual sidebar. More importantly I want to be able to leverage our design system elements that will already be available as Gutenberg blocks.
As compromise I have added a simple input field in my Customizer settings that I can ad shortcodes to that will render using the do_shortcode function in my header template file, however I have yet to find a intuitive way to make Gutenberg blocks available as shortcodes.


text:
Q: Android Google maps markerClickListener for clusterItems I'm trying to implement clusters for my googlemaps markers. Currently I have some custom marker colors with an API call that fires when you click on them. When those results are loaded, there will open a bottomsheet with the specific information of that marker.
I want to keep the same functionalities (custom markers/clickListeners/radius around markers), but add clusters when zoomed out. I've looked at different sources for help:
Android cluster and marker clicks
Android marker-clustering
MarkerManager.java
But i'm not sure how to implement the custom marker and listener for the clusters items. I'am able to get clusters with standard markers without clicklisteners. Here are some images for illustration:
This is my current situation (I want to cluster these markers). As you can see, the bottom sheet pops up when I click on a marker

This is what I'm currently able to do, but I want to combine it with the previous picture

Here is the important part of my code of my map Fragment, (The Point class does implement the ClusterItem interface):
private Map<Marker, Point> retailerInfo = new HashMap<>();

    private void markGeofencesOnMap() {
        new GeofenceAreasRequest().getAllAreas(new GeofenceAreasCallback() {
            @Override
            public void onAreasLoaded(List<Point> points) {
                for (final Point point : points) {
                    markerForGeofence(point);
                    drawRadius(point);
                }
            }
            @Override
            public void failedOnAreasLoaded(int message) {
                Snackbar.make(coordinatorLayout, R.string.failed_loading_areas, Snackbar.LENGTH_LONG).show();
            }
        });
    }

    private void markerForGeofence(Point point) {
        LatLng latLng = new LatLng(point.getLatitude(), point.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .flat(true)
                .title(point.getTitle())
                .icon(BitmapDescriptorFactory.defaultMarker(195));
//        markerManager.getCollection("markerCollection").addMarker(markerOptions);
//        markerManager.getCollection("markerCollection").setOnMarkerClickListener(this);
//        mClusterManager.addItem(point);
        geoFenceMarker = googleMap.addMarker(markerOptions);
        retailerInfo.put(geoFenceMarker, point);
    }

    private void drawRadius(Point point) {
        CircleOptions circleOptions = new CircleOptions()
                .center(geoFenceMarker.getPosition())
                .strokeColor(Color.argb(50, 70, 70, 70))
                .fillColor(Color.argb(100, 150, 150, 150))
                .radius(point.getRadius());
        googleMap.addCircle(circleOptions);
    }

    private void googleMapSettings() {
        int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true);
        } else {
            SystemRequirementsChecker.checkWithDefaultDialogs(getActivity());
        }
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(getLastLocation()).zoom(12).build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        googleMap.setOnMapClickListener(this);
//        markerManager = new MarkerManager(googleMap);
//        markerManager.newCollection("markerCollection");
//        mClusterManager = new ClusterManager<Point>(getActivity(), googleMap );//, markerManager);
//        googleMap.setOnMarkerClickListener(mClusterManager); //markerManager);
        googleMap.setOnCameraIdleListener(mClusterManager);
        googleMap.setOnMarkerClickListener(this);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (retailerInfo != null) {
            String retailerId = retailerInfo.get(marker).getRetailer();
            new RetailersRequest().getRetailer(retailerId, new RetailersCallback() {
                @Override
                public void onRetailersLoad(List<Retailer> retailers) {
                    for (final Retailer retailer : retailers) {
                        mMapRetailerName.setText(retailer.getName());
                        mMapRetailerStreet.setText(retailer.getStreet());
                        mMapRetailerHouseNr.setText(retailer.getHousenumber());
                        mMapRetailerPostalCode.setText(retailer.getPostalCode());
                        mMapRetailerCity.setText(retailer.getCity());
                    }
                    bottomSheet.setVisibility(View.VISIBLE);
                    mBottomSheetBehavior.setPeekHeight(400);
                    mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }

                @Override
                public void failedOnRetailersLoaded(int code) {
                    Snackbar.make(coordinatorLayout, getString(R.string.failed_loading_retailers) + code, Snackbar.LENGTH_LONG).show();
                }
            });
            CameraPosition cameraPosition = new CameraPosition.Builder().target(marker.getPosition()).zoom(14).build();
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }
        return true;
    }

    @Override
    public void onMapClick(LatLng latLng) {
        bottomSheet.setVisibility(View.GONE);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;
        googleMapSettings();
        markGeofencesOnMap();
    }

I hope someone can help me out in the right direction. Thx!

A: Okay, after some more trail and error, I think I've got it sorted out for the most part. All I had to do was to attach a custom DefaultClusterRenderer to my clusterManager. In the mapfragment I could use onClusterItemClick for handling the marker clicks. The one problem I still have is that the circles are not all properly rendered when zooming in and out.
private void markGeofencesOnMap() {
    new GeofenceAreasRequest().getAllAreas(new GeofenceAreasCallback() {
        @Override
        public void onAreasLoaded(List<Point> points) {
            for (final Point point : points) {
                mClusterManager.addItem(point);
            }
        }
    });
}

private void googleMapSettings() {
    mClusterManager = new ClusterManager<Point>(getActivity(), googleMap );
    // attach custom renderer behaviour
    mClusterManager.setRenderer(new OwnPointRendered(getActivity().getApplicationContext(), googleMap, mClusterManager));
    mClusterManager.setOnClusterItemClickListener(this);
    googleMap.setOnMarkerClickListener(mClusterManager);
    googleMap.setOnCameraIdleListener(mClusterManager);
}

@Override
public boolean onClusterItemClick(ClusterItem clusterItem) {
    // cast ClusterItem to my Point class to handle marker clicks
    Point retailer = (Point) clusterItem;
    String retailerId = retailer.getRetailer();
    return true;
}

OwnPointRendered.class
public class OwnPointRendered extends DefaultClusterRenderer<Point> {
private final GoogleMap map;
private List<Circle> circleList = new ArrayList<>();

public OwnPointRendered(Context context, GoogleMap map,
                        ClusterManager<Point> clusterManager) {
    super(context, map, clusterManager);
    this.map = map;
}

@Override
protected void onBeforeClusterItemRendered(Point item, MarkerOptions markerOptions) {
    markerOptions.flat(true);
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(195));
    drawRadius(item);
    super.onBeforeClusterItemRendered(item, markerOptions);
}

@Override
protected void onClusterRendered(Cluster<Point> cluster, Marker marker) {
    super.onClusterRendered(cluster, marker);
    for (Circle circle : circleList) {
        circle.remove();
    }
    circleList.clear();
}

private void drawRadius(Point point) {
    CircleOptions circleOptions = new CircleOptions()
            .center(point.getPosition())
            .strokeColor(Color.argb(50, 70, 70, 70))
            .fillColor(Color.argb(100, 150, 150, 150))
            .radius(point.getRadius());
    Circle circle = map.addCircle(circleOptions);
    circleList.add(circle);
}


text:
Q: How do I hide the table id of a Fusion Table so the user cannot see the source of the fusion table layer on a Google Map? I am using Fusion Tables to add a FusionTablesLayer to my Google Map that shows some markers. I do not want the user to know where the data is coming from (ie: Fusion Table Id).
How can I hide the table id from the user? Currently it is located in JavaScript:
        var tableId = "not_hidden_from_user";
        var layer = new google.maps.FusionTablesLayer({
            map: map,
            heatmap: { enabled: false },
            query: {
                select: "col12",
                from: tableId,
                where: ""
            }
        });

I know that Google needs to access the Fusion Table but I was hoping there was a way to keep the source from the user. The goal is to filter the Fusion Table and show only certain markers to certain users. I am using ASP.Net.

A: Sometimes the simpler solution is the best. Instead of cracking your head looking for way to hide the table,  I suggest to consider to obfuscate the entire javascript file.  I am  using this service:  https://javascriptobfuscator.com without any problem. But you can test also:
http://www.danstools.com/javascript-obfuscate/
http://javascript2img.com/


text:
Q: Flex datagrid multiple rows single file I have a flex datagrid with 3 columns. The first column contains the image name(unique key). The other two columns have username and size details.
I want to split the username into lastname, firstname, address and some other stuff.
Can we have multiple rows in the grid for one image? Tried multi-line, it works but we need to keep adding spaces and its cumbersome.
Since each row in the flex datagrid is represented by one index in the XMLList which is enumerated, is there a way to have more than one row assigned to one image and shown in the grid? something like this..
http://www.freeimagehosting.net/uploads/b7f4e9c9ba.gif http://www.freeimagehosting.net/uploads/b7f4e9c9ba.gif
Thanks,
Vish.

A: Use a custom itemRenderer for the user column. Here is a sample code snippet, you might want to modify it based on the structure of your dataProvider
<mx:DataGrid id="dg" width="100%" height="100%" dataProvider="{dp}">
    <mx:columns>
            <mx:DataGridColumn dataField="image" headerText="Image"/>
            <mx:DataGridColumn dataField="user" headerText="User" >
              <mx:itemRenderer>
                <mx:Component>
                  <mx:VBox>
                    <mx:Label text="{data.firstName}"/>
                    <mx:Label text="{data.lastName}"/>
                    <mx:Text text="{data.address}"/>
                  </mx:VBox>
                </mx:Component>
              </mx:itemRenderer>
            </mx:DataGridColumn>
            <mx:DataGridColumn dataField="size" headerText="Size"/>
    </mx:columns>
</mx:DataGrid>


text:
Q: Why are controls within custom panel (C# winforms) disappearing in designer? I have been able to create a custom C# winforms control that is basically a panel with a fixed banner (header/footer).  I want to base other user controls on this "banner panel".  I've gotten past the problem with the designer here.  I can successfully add controls to the inner content panel.  Everything looks fine while designing.  However, when I recompile, the controls I added to the content panel disappear.  They are still there (in code) but aren't displayed in the designer.  Is there any thing that I need to do to set the drawing order of the controls?

A: Your controls are still nested correctly within the panel control, they have just lost their z-order.  If you choose the controls from the property panel and right click on the control border that appears within the parent panel and select "Bring To Front" from the layout toolbar, your nested controls will re-appear.  I don't know why it does this, but a workaround is to bring all child controls to the front during control initialization in the code.

A: There is really nothing to go on here without src.  What I would do is to comment everything out including in the InitializeComponent function but a widget in the middle panel and run.  Do whatever it takes to get that one widget to show.  Inherit from UserControl instead of the banner panel.
Then comment in each piece until the widget no longer comes up.  That is what is causing your problems.  Once it all comes up properly, then you make sure the designer portion of the src works.  It is going to potentially be a long process.


text:
Q: Estimating joint distributions using copula package in R I am trying to estimate the joint distribution of stock returns using the copula package. I have read a couple of papers on copulae, but alas my lack of math knowledge prevents me from understanding beyond the basics if that! I am thinking of estimating the joint distribution using the following steps and have a couple of questions about the process in general:

*

*Download stock prices for two companies

*Convert prices to continuous returns

*Transform returns to marginal uniform distribution.

*

*How do I do this??

*Create the copula object

*

*When creating the Copula object using ellipCopula() or archmCopula(), I need to specifiy the type of copula and the parameters. How do I know which copula to use? And how do I obtain the parameters... I thought the point of fitting a copula to the data was to obtain the estimated parameters, so why do I need to specify here? Am I just providing initial estimates of the parameters which are then corrected in the actual fitting?

*Specifiy the bivariate distribution

*

*When specifying the bivariate distribution, I need to specify the margins in mvdc(), since, according to a number of sources, I should convert the data (returns) to uniform distributions, do I specify the margins as 'unif' in the function?

*Define the data to be fitted

*

*I am assuming the will be a matrix with 2 columns in this case, each column being the uniforms

*Fit the data

As you can see I am very new at this and any help would be greatly appreciated!

A: Check out A Short, Comprehensive, Practical Guide to Copulas by Atillio Meucci. The paper provides further references in case you'd like to learn more. Steps #3 and #5 are addressed by this paper.
Step #4 is specific to this particular function which I am not too familiar. Since you have so many questions you'd probably have better success breaking down the problem into related parts. You will be in a better place to frame question #4 after some further background reading. As such you really can't answer the question without going into the background of copulas.
There are parametric and non-parametric methods to estimating copulas. In my view, parametric copulas impose tight restrictions that are not respected by the data (non-stationarity, fat tails, etc.). More recent research on time-varying copulas and Meucci's non-parametric copulas I believe can better cope with these issues.


text:
Q: Difference between filter and reduce? What is the difference between filter() and reduce() methods on spark RDD ? In other words why filter() is transformation and reduce() is action ? To me both sounds similar.So what makes them different? is filter is narrow or wide ?

A: filter is narrow as it only works on the per row level and returns another ( filtered ) rdd.
Reduce actually returns a single value that is computed going over the entire rdd. For this value to be returned an actual computation must occur which is why reduce is an action.
In general rdd.functions that have to return an actual value or write some output are actions while rdd.functions that return another rdd are transformations.
Only when an action is needed, the rdd transformations leading to it will take place ( Spark's laziness property )


text:
Q: Изменение значения глобальной переменной в локальной среде не считывается Значение глобальной переменной currentLength изменяется через введение в input разных значений. Нужно, чтобы значение глобальной переменной currentLength было равно текущему значение в input. При введении числа 120 должен сработать alert, он не срабатывает, что означает, что значение глобальной переменной не переопределяется. Как сделать, чтобы оно переопределялось всё-таки?

function getCurrentLength(){
  let currentLength = 0;
  let output = document.getElementById('output');

  calcLength();

  function calcLength() {
    let total = +output.value;
    let len = document.getElementsByClassName('len');
    for (let i = 0; i < len.length; i++) {
      len[i].addEventListener('input', function() {
        let value = 0;
    currentLength = +len[i].value;
        for (let j = 0; j < len.length; j++) {
          let num = +len[j].value || 0;
          value += num;
        }
        output.value = total + value;
      })
    }
  }

  if(currentLength === 120) {
   alert(currentLength)
  }

}
getCurrentLength();
body {
  display: flex;
  flex-direction: column;
}

input {
  width: 170px;
  margin-bottom: 5px;
}
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" id="output" placeholder="output">

Значение глобальной переменной currentLength изменяется через введение в input разных значений. Нужно, чтобы значение глобальной пременной currentLength было равно текущему значение в input.

let currentLength = 0;
let output = document.getElementById('output');
console.log(currentLength)
calcLength();

function calcLength() {
  let total = +output.value;
  let len = document.getElementsByClassName('len');
  for (let i = 0; i < len.length; i++) {
    len[i].addEventListener('input', function() {
      let value = 0;

      for (let j = 0; j < len.length; j++) {
        let num = +len[j].value || 0;
        value += num;
        currentLength = +len[i].value;
      }
      output.value = total + value;
    })
  }
}
body {
  display: flex;
  flex-direction: column;
}

input {
  width: 170px;
  margin-bottom: 5px;
}
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" id="output" placeholder="output">

A: У переменной меняется значение, просто этого не видно

let currentLength = 0;
let output = document.getElementById('output');
console.log(currentLength)
calcLength();

function calcLength() {
  let total = +output.value;
  let len = document.getElementsByClassName('len');
  for (let i = 0; i < len.length; i++) {
    len[i].addEventListener('input', function() {
      currentLength = +this.value;
      console.log(currentLength) // изменения

      let value = 0;
      for (let j = 0; j < len.length; j++) {
        let num = +len[j].value || 0;
        value += num;
      }
      output.value = total + value;
    })
  }
}
body {
  display: flex;
  flex-direction: column;
}

input {
  width: 170px;
  margin-bottom: 5px;
}
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" placeholder="length" class="len">
<input type="text" id="output" placeholder="output">


text:
Q: How to verify Pacts against multiple versions of PACTS published I have used pact-jvm-provider-maven/ plugin to publish different versions (1.0.0 and 2.0.0) of pacts to Pact-Broker. I'm using following configuration to verify the pacts against the hosted Provider....
<plugin>
                <groupId>au.com.dius</groupId>
                <artifactId>pact-jvm-provider-maven_2.11</artifactId>
                <version>3.5.4</version>
                <configuration>
                    <serviceProviders>
                        <serviceProvider>
                            <name>Books</name>
                        <pactBrokerUrl>http://localhost:80/</pactBrokerUrl>
                        </serviceProvider>
                    </serviceProviders>
                    <configuration>
                        <pact.showStacktrace>true</pact.showStacktrace>
                    </configuration>
                </configuration>
            </plugin>

It is verifying only the latest pact version i.e 2.0.0.
For backword compatibility, i wanted to verify all the versions of PACTS published to Broker against the Provider service.
Has anyone done this successfully?

A: You can verify different versions of pacts by using the tagging feature of the pact broker. See https://github.com/DiUS/pact-jvm/blob/master/pact-jvm-provider-maven/README.md#verifying-pacts-from-an-pact-broker-that-match-particular-tags-version-335 on how to use this with the Maven plugin.
Basically, you assign tags to the different versions (like PROD for 1.0.0 and TEST for 2.0.0), and then you can verify your providers against both of those versions.


text:
Q: how to add dynamic xaxis category label name in new point highchart i need add point to highchart x,y . i cannot add my custom xaxis in the label. label automaticly add index of potit .how can i add my text in new point xaixs label ?
    var chartPresure = $('#PresureContainer').highcharts();
        var series = chartPresure.series[0];
        var newpointPresure = updatedresult.Pressure;
        if (lastDate != updatedresult.RegisterDatePersian) {
            var x = updatedresult.RegisterDatePersian,
                y = updatedresult.Pressure;
            series.addPoint([x, y, updatedresult.RegisterDatePersian], true);

            series.drawPoints();

            lastDate = updatedresult.RegisterDatePersian;
        }

A: You can update the axis labels after point add event
function addPoint() {
  chart.series[0].addPoint(
    Math.floor(Math.random() * 6) + 1,
    true,
    false
  );
  //console.log(chart.xAxis[0].categories)
  chart.xAxis[0].categories.push(chart.series[0].data.length + 'th element')
  //console.log(chart.xAxis[0].categories)
  //update chart with category
  chart.update({
    xAxis: {
      categories: chart.xAxis[0].categories
    },
  });
}

var chart = new Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Stacked column chart'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    },
    stackLabels: {
      enabled: true,
      style: {
        fontWeight: 'bold',
        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
      }
    }
  },
  legend: {
    align: 'right',
    x: -30,
    verticalAlign: 'top',
    y: 25,
    floating: true,
    backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
    borderColor: '#CCC',
    borderWidth: 1,
    shadow: false
  },
  tooltip: {
    headerFormat: '{point.x}
',
    pointFormat: '{series.name}: {point.y}
Total: {point.stackTotal}'
  },
  plotOptions: {
    column: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
      }
    }
  },
  series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2]
  }]
});

function addPoint() {
  chart.series[0].addPoint(
    Math.floor(Math.random() * 6) + 1,
    true,
    false
  );
  //console.log(chart.xAxis[0].categories)
  chart.xAxis[0].categories.push(chart.series[0].data.length + 'th element')
  //console.log(chart.xAxis[0].categories)
  chart.update({
    xAxis: {
      categories: chart.xAxis[0].categories
    },
  });
}

<button onclick="addPoint()" class="autocompare">Add point</button>


text:
Q: Can replaceState() in JavaScript be used to change document title and contents? How can I add a tag <title>Update</title> and
Update
?
jQuery(document).ready(function($){
    $( "a" ).click(function() {
        var url = $(this).attr('href');
        if(url != window.location){
            history.replaceState(null, null, url);
        }
        return false;
    });
});

I need to update eg <title>Home</title> to <title>About</title> and
Home content
 to
About content
 at the transition.

A: It's really unclear what you want to acheive, but if your goal is to set the displayed title of the page, set document.title:
document.title = "Update";

And if you want to add a div:
$('
Update
').appendTo(document.body);

That appends to the body of the page (at the bottom). If you want the div to be somewhere else, you'll want to append it to some other element in the DOM. You can use CSS selectors (plus some additional things) to choose which element to add to.
If you do that twice, the resulting DOM document will be invalid, as you cannot have two elements with the same id. If you want to update the existing one if it's there:
var $div = $("#content");
if (!$div[0]) {
    $div = $('

');
    $div.appendTo(document.body);
}
$div.text("Update"): // Or $div.html("HTML markup here")


text:
Q: Condition statement not clear t->item I have got a got a code to search through a binary search tree, and i can't understand the t->item in the if conditions.
search(item, t) {

     if (t == NULL) // t is an empty tree
       {item is not present  in tree, t, and terminate search }

     else if (item == t->item)
             {item is present in tree, t, and terminate search}

            else if (item < t->item)
                    {search in left subtree (i.e. t->left) recursively}

                  else
                    {search in right subtree (i.e. t->right) recursively}
  }

Can someone explain this to me?

A: item == t->item means "if item is the root of the tree". Otherwise, you'll look whether if it's greater or less than the root to see if you're continuing to search in the left or in the right subtree.


text:
Q: Netty 4.0 - instanciate DefaultChannelGroup I am currently migrating my project from Netty 3.x to 4.0.4 Final and i have a little question about ChannelGroups.
DefaultChannelGroup needs now an EventExecutor in the constructor.
Unfortunately i didn´t really understand the thread model of Netty 4.0 yet.
How can i instanciate an EventExecutor for my ChannelGroups?
I just want the write operations beeing executed in several threads.
ChannelGroup newChannelGroup =
new DefaultChannelGroup(name, new DefaultEventExecutorGroup(1).next());

Is this the right way?

A: The code that's used in the examples is:
ChannelGroup channelGroup =
  new DefaultChannelGroup (name, GlobalEventExecutor.INSTANCE);


text:
Q: Alternative form of moments of expectation of a discrete random variable Consider a positive discrete random variable $X$ taking values in $\mathbb{N}$ and let $r\geq 1$. Is it true that for the $r$ moment of the expectation the following relation holds:
\begin{equation}
\mathbb{E}[X^r] = \sum_{k=1}^\infty k^{r-1} \mathbb{P}\{X>k\}.
\end{equation}
I tried using Abel's partial summation formula to show something similar but it did not work out. Any hints? Thanks!

A: That formula is not correct (just test it for simple cases as in my comment above).
Assuming that $X \in \{1, 2, 3, ...\}$ and $r \in \mathbb{R}$, I think the formula you want is:
$$ X^r = 1 + \sum_{k=1}^{\infty} [(k+1)^r-k^r]1_{\{X>k\}} \implies \boxed{E[X^r] = 1 + \sum_{k=1}^{\infty} [(k+1)^r-k^r]P[X>k]}$$
where $1_{\{X>k\}}$ is an indicator function that is $1$ if $X>k$, and 0 else.


text:
Q: Why this algoritm with recursion gaves duplicates in result? The result should contain only unique elements I try to make function which excludes the same elements from list. The result should be unique elements in list like [a, d, b, c] or in different order it doesnt matter. The below code on not small source data gaves wrong result. For instance,
[a, d, a, a, b, b, c]
::::::::::
------ignore element-------
removed a
------ignore element-------
removed a
------ignore element-------
removed a
------ignore element-------
[a, d, b, b, c]

the code
public class Test {
    String s;
    public Test(String s) {
        this.s = s;
    }

    @Override
    public String toString() {
        return s;
    }

    public static void main(String[] args) {
        ArrayList<Test> arr = new ArrayList<>();
        arr.add(new Test("a"));
        arr.add(new Test("d"));
        arr.add(new Test("a"));
        arr.add(new Test("a"));
        arr.add(new Test("b"));
        arr.add(new Test("b"));
        arr.add(new Test("c"));
        System.out.println(arr);
        System.out.println("::::::::::");
        System.out.println(compare(arr));
    }

    static private ArrayList<Test> compare(ArrayList<Test> arr) {
        ArrayList<Test> result = new ArrayList<>(arr);
        for (Test valueToCompare : arr) {
            for (Test t : arr) {
                if((valueToCompare.s).equals(t.s)) {

                    if(valueToCompare == t) {
                        // it's the same obj
                        System.out.println("------ignore element-------");
                        continue;
                    }
                    // it's identical values and diffrent objects so removing it from result array
                    result.remove(t);
                    System.out.println("removed " + t.s);
                    compare(result); // recursion
                }
            }
            break;
        }
        return result;
    }
}

I know about set and related things so please do not sugest it. It shoud be done in a separate function. How to fix this function to recive correct result?

A: The problem is the "break statement" which always breaks the loop.
Your algorithm works like this.
Step1 -> take "a" (first element) and check for duplicate.
Step2 -> Since there is duplicate the function is called recursively until all duplicates of "a" is removed.
Step3 -> Now reaches the break statement and terminates.
This algorithm is very complex.
I suggest you to use this algorithm
private static ArrayList<Test> compare(ArrayList<Test> list)
{

    // Create a new ArrayList
    ArrayList<Test> newList = new ArrayList<Test>();

    // Traverse through the first list
    for (Test element : list) {

        // If this element is not present in newList
        // then add it
        if (!newList.contains(element)) {

            newList.add(element);
        }
    }

    // return the new list
    return newList;
}

Hope this helps you :).

A: If the list is not huge or memory is not an issue, you can use LinkedHashSet class, which removes the duplicates and maintain the order.
If you care about the order, you can just go with the HashSet class.
Sample code ::
import java.util.*;

public class RemoveDuplicates {

    String s;

    public RemoveDuplicates(String s) {
        this.s = s;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        RemoveDuplicates that = (RemoveDuplicates) o;
        return Objects.equals(s, that.s);
    }

    @Override
    public int hashCode() {
        return Objects.hash(s);
    }

    @Override
    public String toString() {
        return s;
    }

    public static void main(String[] args) {
        List<RemoveDuplicates> arr = new ArrayList<>();
        arr.add(new RemoveDuplicates("a"));
        arr.add(new RemoveDuplicates("d"));
        arr.add(new RemoveDuplicates("a"));
        arr.add(new RemoveDuplicates("a"));
        arr.add(new RemoveDuplicates("b"));
        arr.add(new RemoveDuplicates("b"));
        arr.add(new RemoveDuplicates("c"));

        removeDuplicates(arr);

        System.out.println(arr);
    }

    private static void removeDuplicates(List<RemoveDuplicates> arr) {
        Set<RemoveDuplicates> duplicatesRemoved = new LinkedHashSet<>(arr); // [#1]
        arr.clear();                           // [#2]
        arr.addAll(duplicatesRemoved);         // [#3]
    }
}

PS.
#1. Constructor used to create a new Set from the list given. The catch, Sets uses @equals() method to compare objects, if the equals() method is not overrided, the flow won't work.
#2 & #3. Just to store back the results in the same list. If type is not an issue, just return the Set and use further without clearing and reset the list.
Edit::
Method 2 to remove duplicates
private static List<RemoveDuplicates> removeDuplicatesMethod2(List<RemoveDuplicates> arr) {
     return arr.stream()
             .distinct()
             .collect(Collectors.toList());
}

Uses Java streams to remove duplicates and create new List. Return the list and use it further.